29090c6d48199894ee3f7425e1bdc931cda03605
[sfrench/cifs-2.6.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/tech/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  *
28  * This program is free software; you can redistribute it and/or modify
29  * it under the terms of the GNU General Public License version 2 as
30  * published by the Free Software Foundation.
31  *
32  */
33
34 #include <linux/module.h>
35 #include <linux/delay.h>
36 #include <linux/errno.h>
37 #include <linux/err.h>
38 #include <linux/sched.h>
39 #include <linux/slab.h>
40 #include <linux/types.h>
41 #include <linux/mtd/mtd.h>
42 #include <linux/mtd/nand.h>
43 #include <linux/mtd/nand_ecc.h>
44 #include <linux/mtd/compatmac.h>
45 #include <linux/interrupt.h>
46 #include <linux/bitops.h>
47 #include <linux/leds.h>
48 #include <asm/io.h>
49
50 #ifdef CONFIG_MTD_PARTITIONS
51 #include <linux/mtd/partitions.h>
52 #endif
53
54 /* Define default oob placement schemes for large and small page devices */
55 static struct nand_ecclayout nand_oob_8 = {
56         .eccbytes = 3,
57         .eccpos = {0, 1, 2},
58         .oobfree = {
59                 {.offset = 3,
60                  .length = 2},
61                 {.offset = 6,
62                  .length = 2}}
63 };
64
65 static struct nand_ecclayout nand_oob_16 = {
66         .eccbytes = 6,
67         .eccpos = {0, 1, 2, 3, 6, 7},
68         .oobfree = {
69                 {.offset = 8,
70                  . length = 8}}
71 };
72
73 static struct nand_ecclayout nand_oob_64 = {
74         .eccbytes = 24,
75         .eccpos = {
76                    40, 41, 42, 43, 44, 45, 46, 47,
77                    48, 49, 50, 51, 52, 53, 54, 55,
78                    56, 57, 58, 59, 60, 61, 62, 63},
79         .oobfree = {
80                 {.offset = 2,
81                  .length = 38}}
82 };
83
84 static int nand_get_device(struct nand_chip *chip, struct mtd_info *mtd,
85                            int new_state);
86
87 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
88                              struct mtd_oob_ops *ops);
89
90 /*
91  * For devices which display every fart in the system on a seperate LED. Is
92  * compiled away when LED support is disabled.
93  */
94 DEFINE_LED_TRIGGER(nand_led_trigger);
95
96 /**
97  * nand_release_device - [GENERIC] release chip
98  * @mtd:        MTD device structure
99  *
100  * Deselect, release chip lock and wake up anyone waiting on the device
101  */
102 static void nand_release_device(struct mtd_info *mtd)
103 {
104         struct nand_chip *chip = mtd->priv;
105
106         /* De-select the NAND device */
107         chip->select_chip(mtd, -1);
108
109         /* Release the controller and the chip */
110         spin_lock(&chip->controller->lock);
111         chip->controller->active = NULL;
112         chip->state = FL_READY;
113         wake_up(&chip->controller->wq);
114         spin_unlock(&chip->controller->lock);
115 }
116
117 /**
118  * nand_read_byte - [DEFAULT] read one byte from the chip
119  * @mtd:        MTD device structure
120  *
121  * Default read function for 8bit buswith
122  */
123 static uint8_t nand_read_byte(struct mtd_info *mtd)
124 {
125         struct nand_chip *chip = mtd->priv;
126         return readb(chip->IO_ADDR_R);
127 }
128
129 /**
130  * nand_read_byte16 - [DEFAULT] read one byte endianess aware from the chip
131  * @mtd:        MTD device structure
132  *
133  * Default read function for 16bit buswith with
134  * endianess conversion
135  */
136 static uint8_t nand_read_byte16(struct mtd_info *mtd)
137 {
138         struct nand_chip *chip = mtd->priv;
139         return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
140 }
141
142 /**
143  * nand_read_word - [DEFAULT] read one word from the chip
144  * @mtd:        MTD device structure
145  *
146  * Default read function for 16bit buswith without
147  * endianess conversion
148  */
149 static u16 nand_read_word(struct mtd_info *mtd)
150 {
151         struct nand_chip *chip = mtd->priv;
152         return readw(chip->IO_ADDR_R);
153 }
154
155 /**
156  * nand_select_chip - [DEFAULT] control CE line
157  * @mtd:        MTD device structure
158  * @chipnr:     chipnumber to select, -1 for deselect
159  *
160  * Default select function for 1 chip devices.
161  */
162 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
163 {
164         struct nand_chip *chip = mtd->priv;
165
166         switch (chipnr) {
167         case -1:
168                 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
169                 break;
170         case 0:
171                 break;
172
173         default:
174                 BUG();
175         }
176 }
177
178 /**
179  * nand_write_buf - [DEFAULT] write buffer to chip
180  * @mtd:        MTD device structure
181  * @buf:        data buffer
182  * @len:        number of bytes to write
183  *
184  * Default write function for 8bit buswith
185  */
186 static void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
187 {
188         int i;
189         struct nand_chip *chip = mtd->priv;
190
191         for (i = 0; i < len; i++)
192                 writeb(buf[i], chip->IO_ADDR_W);
193 }
194
195 /**
196  * nand_read_buf - [DEFAULT] read chip data into buffer
197  * @mtd:        MTD device structure
198  * @buf:        buffer to store date
199  * @len:        number of bytes to read
200  *
201  * Default read function for 8bit buswith
202  */
203 static void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
204 {
205         int i;
206         struct nand_chip *chip = mtd->priv;
207
208         for (i = 0; i < len; i++)
209                 buf[i] = readb(chip->IO_ADDR_R);
210 }
211
212 /**
213  * nand_verify_buf - [DEFAULT] Verify chip data against buffer
214  * @mtd:        MTD device structure
215  * @buf:        buffer containing the data to compare
216  * @len:        number of bytes to compare
217  *
218  * Default verify function for 8bit buswith
219  */
220 static int nand_verify_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
221 {
222         int i;
223         struct nand_chip *chip = mtd->priv;
224
225         for (i = 0; i < len; i++)
226                 if (buf[i] != readb(chip->IO_ADDR_R))
227                         return -EFAULT;
228         return 0;
229 }
230
231 /**
232  * nand_write_buf16 - [DEFAULT] write buffer to chip
233  * @mtd:        MTD device structure
234  * @buf:        data buffer
235  * @len:        number of bytes to write
236  *
237  * Default write function for 16bit buswith
238  */
239 static void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
240 {
241         int i;
242         struct nand_chip *chip = mtd->priv;
243         u16 *p = (u16 *) buf;
244         len >>= 1;
245
246         for (i = 0; i < len; i++)
247                 writew(p[i], chip->IO_ADDR_W);
248
249 }
250
251 /**
252  * nand_read_buf16 - [DEFAULT] read chip data into buffer
253  * @mtd:        MTD device structure
254  * @buf:        buffer to store date
255  * @len:        number of bytes to read
256  *
257  * Default read function for 16bit buswith
258  */
259 static void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
260 {
261         int i;
262         struct nand_chip *chip = mtd->priv;
263         u16 *p = (u16 *) buf;
264         len >>= 1;
265
266         for (i = 0; i < len; i++)
267                 p[i] = readw(chip->IO_ADDR_R);
268 }
269
270 /**
271  * nand_verify_buf16 - [DEFAULT] Verify chip data against buffer
272  * @mtd:        MTD device structure
273  * @buf:        buffer containing the data to compare
274  * @len:        number of bytes to compare
275  *
276  * Default verify function for 16bit buswith
277  */
278 static int nand_verify_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                 if (p[i] != readw(chip->IO_ADDR_R))
287                         return -EFAULT;
288
289         return 0;
290 }
291
292 /**
293  * nand_block_bad - [DEFAULT] Read bad block marker from the chip
294  * @mtd:        MTD device structure
295  * @ofs:        offset from device start
296  * @getchip:    0, if the chip is already selected
297  *
298  * Check, if the block is bad.
299  */
300 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs, int getchip)
301 {
302         int page, chipnr, res = 0;
303         struct nand_chip *chip = mtd->priv;
304         u16 bad;
305
306         if (getchip) {
307                 page = (int)(ofs >> chip->page_shift);
308                 chipnr = (int)(ofs >> chip->chip_shift);
309
310                 nand_get_device(chip, mtd, FL_READING);
311
312                 /* Select the NAND device */
313                 chip->select_chip(mtd, chipnr);
314         } else
315                 page = (int)ofs;
316
317         if (chip->options & NAND_BUSWIDTH_16) {
318                 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos & 0xFE,
319                               page & chip->pagemask);
320                 bad = cpu_to_le16(chip->read_word(mtd));
321                 if (chip->badblockpos & 0x1)
322                         bad >>= 8;
323                 if ((bad & 0xFF) != 0xff)
324                         res = 1;
325         } else {
326                 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
327                               page & chip->pagemask);
328                 if (chip->read_byte(mtd) != 0xff)
329                         res = 1;
330         }
331
332         if (getchip)
333                 nand_release_device(mtd);
334
335         return res;
336 }
337
338 /**
339  * nand_default_block_markbad - [DEFAULT] mark a block bad
340  * @mtd:        MTD device structure
341  * @ofs:        offset from device start
342  *
343  * This is the default implementation, which can be overridden by
344  * a hardware specific driver.
345 */
346 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
347 {
348         struct nand_chip *chip = mtd->priv;
349         uint8_t buf[2] = { 0, 0 };
350         int block, ret;
351
352         /* Get block number */
353         block = ((int)ofs) >> chip->bbt_erase_shift;
354         if (chip->bbt)
355                 chip->bbt[block >> 2] |= 0x01 << ((block & 0x03) << 1);
356
357         /* Do we have a flash based bad block table ? */
358         if (chip->options & NAND_USE_FLASH_BBT)
359                 ret = nand_update_bbt(mtd, ofs);
360         else {
361                 /* We write two bytes, so we dont have to mess with 16 bit
362                  * access
363                  */
364                 ofs += mtd->oobsize;
365                 chip->ops.len = 2;
366                 chip->ops.datbuf = NULL;
367                 chip->ops.oobbuf = buf;
368                 chip->ops.ooboffs = chip->badblockpos & ~0x01;
369
370                 ret = nand_do_write_oob(mtd, ofs, &chip->ops);
371         }
372         if (!ret)
373                 mtd->ecc_stats.badblocks++;
374         return ret;
375 }
376
377 /**
378  * nand_check_wp - [GENERIC] check if the chip is write protected
379  * @mtd:        MTD device structure
380  * Check, if the device is write protected
381  *
382  * The function expects, that the device is already selected
383  */
384 static int nand_check_wp(struct mtd_info *mtd)
385 {
386         struct nand_chip *chip = mtd->priv;
387         /* Check the WP bit */
388         chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
389         return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
390 }
391
392 /**
393  * nand_block_checkbad - [GENERIC] Check if a block is marked bad
394  * @mtd:        MTD device structure
395  * @ofs:        offset from device start
396  * @getchip:    0, if the chip is already selected
397  * @allowbbt:   1, if its allowed to access the bbt area
398  *
399  * Check, if the block is bad. Either by reading the bad block table or
400  * calling of the scan function.
401  */
402 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int getchip,
403                                int allowbbt)
404 {
405         struct nand_chip *chip = mtd->priv;
406
407         if (!chip->bbt)
408                 return chip->block_bad(mtd, ofs, getchip);
409
410         /* Return info from the table */
411         return nand_isbad_bbt(mtd, ofs, allowbbt);
412 }
413
414 /*
415  * Wait for the ready pin, after a command
416  * The timeout is catched later.
417  */
418 void nand_wait_ready(struct mtd_info *mtd)
419 {
420         struct nand_chip *chip = mtd->priv;
421         unsigned long timeo = jiffies + 2;
422
423         led_trigger_event(nand_led_trigger, LED_FULL);
424         /* wait until command is processed or timeout occures */
425         do {
426                 if (chip->dev_ready(mtd))
427                         break;
428                 touch_softlockup_watchdog();
429         } while (time_before(jiffies, timeo));
430         led_trigger_event(nand_led_trigger, LED_OFF);
431 }
432 EXPORT_SYMBOL_GPL(nand_wait_ready);
433
434 /**
435  * nand_command - [DEFAULT] Send command to NAND device
436  * @mtd:        MTD device structure
437  * @command:    the command to be sent
438  * @column:     the column address for this command, -1 if none
439  * @page_addr:  the page address for this command, -1 if none
440  *
441  * Send command to NAND device. This function is used for small page
442  * devices (256/512 Bytes per page)
443  */
444 static void nand_command(struct mtd_info *mtd, unsigned int command,
445                          int column, int page_addr)
446 {
447         register struct nand_chip *chip = mtd->priv;
448         int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
449
450         /*
451          * Write out the command to the device.
452          */
453         if (command == NAND_CMD_SEQIN) {
454                 int readcmd;
455
456                 if (column >= mtd->writesize) {
457                         /* OOB area */
458                         column -= mtd->writesize;
459                         readcmd = NAND_CMD_READOOB;
460                 } else if (column < 256) {
461                         /* First 256 bytes --> READ0 */
462                         readcmd = NAND_CMD_READ0;
463                 } else {
464                         column -= 256;
465                         readcmd = NAND_CMD_READ1;
466                 }
467                 chip->cmd_ctrl(mtd, readcmd, ctrl);
468                 ctrl &= ~NAND_CTRL_CHANGE;
469         }
470         chip->cmd_ctrl(mtd, command, ctrl);
471
472         /*
473          * Address cycle, when necessary
474          */
475         ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
476         /* Serially input address */
477         if (column != -1) {
478                 /* Adjust columns for 16 bit buswidth */
479                 if (chip->options & NAND_BUSWIDTH_16)
480                         column >>= 1;
481                 chip->cmd_ctrl(mtd, column, ctrl);
482                 ctrl &= ~NAND_CTRL_CHANGE;
483         }
484         if (page_addr != -1) {
485                 chip->cmd_ctrl(mtd, page_addr, ctrl);
486                 ctrl &= ~NAND_CTRL_CHANGE;
487                 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
488                 /* One more address cycle for devices > 32MiB */
489                 if (chip->chipsize > (32 << 20))
490                         chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
491         }
492         chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
493
494         /*
495          * program and erase have their own busy handlers
496          * status and sequential in needs no delay
497          */
498         switch (command) {
499
500         case NAND_CMD_PAGEPROG:
501         case NAND_CMD_ERASE1:
502         case NAND_CMD_ERASE2:
503         case NAND_CMD_SEQIN:
504         case NAND_CMD_STATUS:
505                 return;
506
507         case NAND_CMD_RESET:
508                 if (chip->dev_ready)
509                         break;
510                 udelay(chip->chip_delay);
511                 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
512                                NAND_CTRL_CLE | NAND_CTRL_CHANGE);
513                 chip->cmd_ctrl(mtd,
514                                NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
515                 while (!(chip->read_byte(mtd) & NAND_STATUS_READY)) ;
516                 return;
517
518                 /* This applies to read commands */
519         default:
520                 /*
521                  * If we don't have access to the busy pin, we apply the given
522                  * command delay
523                  */
524                 if (!chip->dev_ready) {
525                         udelay(chip->chip_delay);
526                         return;
527                 }
528         }
529         /* Apply this short delay always to ensure that we do wait tWB in
530          * any case on any machine. */
531         ndelay(100);
532
533         nand_wait_ready(mtd);
534 }
535
536 /**
537  * nand_command_lp - [DEFAULT] Send command to NAND large page device
538  * @mtd:        MTD device structure
539  * @command:    the command to be sent
540  * @column:     the column address for this command, -1 if none
541  * @page_addr:  the page address for this command, -1 if none
542  *
543  * Send command to NAND device. This is the version for the new large page
544  * devices We dont have the separate regions as we have in the small page
545  * devices.  We must emulate NAND_CMD_READOOB to keep the code compatible.
546  */
547 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
548                             int column, int page_addr)
549 {
550         register struct nand_chip *chip = mtd->priv;
551
552         /* Emulate NAND_CMD_READOOB */
553         if (command == NAND_CMD_READOOB) {
554                 column += mtd->writesize;
555                 command = NAND_CMD_READ0;
556         }
557
558         /* Command latch cycle */
559         chip->cmd_ctrl(mtd, command & 0xff,
560                        NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
561
562         if (column != -1 || page_addr != -1) {
563                 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
564
565                 /* Serially input address */
566                 if (column != -1) {
567                         /* Adjust columns for 16 bit buswidth */
568                         if (chip->options & NAND_BUSWIDTH_16)
569                                 column >>= 1;
570                         chip->cmd_ctrl(mtd, column, ctrl);
571                         ctrl &= ~NAND_CTRL_CHANGE;
572                         chip->cmd_ctrl(mtd, column >> 8, ctrl);
573                 }
574                 if (page_addr != -1) {
575                         chip->cmd_ctrl(mtd, page_addr, ctrl);
576                         chip->cmd_ctrl(mtd, page_addr >> 8,
577                                        NAND_NCE | NAND_ALE);
578                         /* One more address cycle for devices > 128MiB */
579                         if (chip->chipsize > (128 << 20))
580                                 chip->cmd_ctrl(mtd, page_addr >> 16,
581                                                NAND_NCE | NAND_ALE);
582                 }
583         }
584         chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
585
586         /*
587          * program and erase have their own busy handlers
588          * status, sequential in, and deplete1 need no delay
589          */
590         switch (command) {
591
592         case NAND_CMD_CACHEDPROG:
593         case NAND_CMD_PAGEPROG:
594         case NAND_CMD_ERASE1:
595         case NAND_CMD_ERASE2:
596         case NAND_CMD_SEQIN:
597         case NAND_CMD_RNDIN:
598         case NAND_CMD_STATUS:
599         case NAND_CMD_DEPLETE1:
600                 return;
601
602                 /*
603                  * read error status commands require only a short delay
604                  */
605         case NAND_CMD_STATUS_ERROR:
606         case NAND_CMD_STATUS_ERROR0:
607         case NAND_CMD_STATUS_ERROR1:
608         case NAND_CMD_STATUS_ERROR2:
609         case NAND_CMD_STATUS_ERROR3:
610                 udelay(chip->chip_delay);
611                 return;
612
613         case NAND_CMD_RESET:
614                 if (chip->dev_ready)
615                         break;
616                 udelay(chip->chip_delay);
617                 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
618                                NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
619                 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
620                                NAND_NCE | NAND_CTRL_CHANGE);
621                 while (!(chip->read_byte(mtd) & NAND_STATUS_READY)) ;
622                 return;
623
624         case NAND_CMD_RNDOUT:
625                 /* No ready / busy check necessary */
626                 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
627                                NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
628                 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
629                                NAND_NCE | NAND_CTRL_CHANGE);
630                 return;
631
632         case NAND_CMD_READ0:
633                 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
634                                NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
635                 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
636                                NAND_NCE | NAND_CTRL_CHANGE);
637
638                 /* This applies to read commands */
639         default:
640                 /*
641                  * If we don't have access to the busy pin, we apply the given
642                  * command delay
643                  */
644                 if (!chip->dev_ready) {
645                         udelay(chip->chip_delay);
646                         return;
647                 }
648         }
649
650         /* Apply this short delay always to ensure that we do wait tWB in
651          * any case on any machine. */
652         ndelay(100);
653
654         nand_wait_ready(mtd);
655 }
656
657 /**
658  * nand_get_device - [GENERIC] Get chip for selected access
659  * @chip:       the nand chip descriptor
660  * @mtd:        MTD device structure
661  * @new_state:  the state which is requested
662  *
663  * Get the device and lock it for exclusive access
664  */
665 static int
666 nand_get_device(struct nand_chip *chip, struct mtd_info *mtd, int new_state)
667 {
668         spinlock_t *lock = &chip->controller->lock;
669         wait_queue_head_t *wq = &chip->controller->wq;
670         DECLARE_WAITQUEUE(wait, current);
671  retry:
672         spin_lock(lock);
673
674         /* Hardware controller shared among independend devices */
675         /* Hardware controller shared among independend devices */
676         if (!chip->controller->active)
677                 chip->controller->active = chip;
678
679         if (chip->controller->active == chip && chip->state == FL_READY) {
680                 chip->state = new_state;
681                 spin_unlock(lock);
682                 return 0;
683         }
684         if (new_state == FL_PM_SUSPENDED) {
685                 spin_unlock(lock);
686                 return (chip->state == FL_PM_SUSPENDED) ? 0 : -EAGAIN;
687         }
688         set_current_state(TASK_UNINTERRUPTIBLE);
689         add_wait_queue(wq, &wait);
690         spin_unlock(lock);
691         schedule();
692         remove_wait_queue(wq, &wait);
693         goto retry;
694 }
695
696 /**
697  * nand_wait - [DEFAULT]  wait until the command is done
698  * @mtd:        MTD device structure
699  * @chip:       NAND chip structure
700  *
701  * Wait for command done. This applies to erase and program only
702  * Erase can take up to 400ms and program up to 20ms according to
703  * general NAND and SmartMedia specs
704  */
705 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
706 {
707
708         unsigned long timeo = jiffies;
709         int status, state = chip->state;
710
711         if (state == FL_ERASING)
712                 timeo += (HZ * 400) / 1000;
713         else
714                 timeo += (HZ * 20) / 1000;
715
716         led_trigger_event(nand_led_trigger, LED_FULL);
717
718         /* Apply this short delay always to ensure that we do wait tWB in
719          * any case on any machine. */
720         ndelay(100);
721
722         if ((state == FL_ERASING) && (chip->options & NAND_IS_AND))
723                 chip->cmdfunc(mtd, NAND_CMD_STATUS_MULTI, -1, -1);
724         else
725                 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
726
727         while (time_before(jiffies, timeo)) {
728                 if (chip->dev_ready) {
729                         if (chip->dev_ready(mtd))
730                                 break;
731                 } else {
732                         if (chip->read_byte(mtd) & NAND_STATUS_READY)
733                                 break;
734                 }
735                 cond_resched();
736         }
737         led_trigger_event(nand_led_trigger, LED_OFF);
738
739         status = (int)chip->read_byte(mtd);
740         return status;
741 }
742
743 /**
744  * nand_read_page_raw - [Intern] read raw page data without ecc
745  * @mtd:        mtd info structure
746  * @chip:       nand chip info structure
747  * @buf:        buffer to store read data
748  */
749 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
750                               uint8_t *buf)
751 {
752         chip->read_buf(mtd, buf, mtd->writesize);
753         chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
754         return 0;
755 }
756
757 /**
758  * nand_read_page_swecc - [REPLACABLE] software ecc based page read function
759  * @mtd:        mtd info structure
760  * @chip:       nand chip info structure
761  * @buf:        buffer to store read data
762  */
763 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
764                                 uint8_t *buf)
765 {
766         int i, eccsize = chip->ecc.size;
767         int eccbytes = chip->ecc.bytes;
768         int eccsteps = chip->ecc.steps;
769         uint8_t *p = buf;
770         uint8_t *ecc_calc = chip->buffers->ecccalc;
771         uint8_t *ecc_code = chip->buffers->ecccode;
772         int *eccpos = chip->ecc.layout->eccpos;
773
774         nand_read_page_raw(mtd, chip, buf);
775
776         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
777                 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
778
779         for (i = 0; i < chip->ecc.total; i++)
780                 ecc_code[i] = chip->oob_poi[eccpos[i]];
781
782         eccsteps = chip->ecc.steps;
783         p = buf;
784
785         for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
786                 int stat;
787
788                 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
789                 if (stat == -1)
790                         mtd->ecc_stats.failed++;
791                 else
792                         mtd->ecc_stats.corrected += stat;
793         }
794         return 0;
795 }
796
797 /**
798  * nand_read_page_hwecc - [REPLACABLE] hardware ecc based page read function
799  * @mtd:        mtd info structure
800  * @chip:       nand chip info structure
801  * @buf:        buffer to store read data
802  *
803  * Not for syndrome calculating ecc controllers which need a special oob layout
804  */
805 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
806                                 uint8_t *buf)
807 {
808         int i, eccsize = chip->ecc.size;
809         int eccbytes = chip->ecc.bytes;
810         int eccsteps = chip->ecc.steps;
811         uint8_t *p = buf;
812         uint8_t *ecc_calc = chip->buffers->ecccalc;
813         uint8_t *ecc_code = chip->buffers->ecccode;
814         int *eccpos = chip->ecc.layout->eccpos;
815
816         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
817                 chip->ecc.hwctl(mtd, NAND_ECC_READ);
818                 chip->read_buf(mtd, p, eccsize);
819                 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
820         }
821         chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
822
823         for (i = 0; i < chip->ecc.total; i++)
824                 ecc_code[i] = chip->oob_poi[eccpos[i]];
825
826         eccsteps = chip->ecc.steps;
827         p = buf;
828
829         for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
830                 int stat;
831
832                 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
833                 if (stat == -1)
834                         mtd->ecc_stats.failed++;
835                 else
836                         mtd->ecc_stats.corrected += stat;
837         }
838         return 0;
839 }
840
841 /**
842  * nand_read_page_syndrome - [REPLACABLE] hardware ecc syndrom based page read
843  * @mtd:        mtd info structure
844  * @chip:       nand chip info structure
845  * @buf:        buffer to store read data
846  *
847  * The hw generator calculates the error syndrome automatically. Therefor
848  * we need a special oob layout and handling.
849  */
850 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
851                                    uint8_t *buf)
852 {
853         int i, eccsize = chip->ecc.size;
854         int eccbytes = chip->ecc.bytes;
855         int eccsteps = chip->ecc.steps;
856         uint8_t *p = buf;
857         uint8_t *oob = chip->oob_poi;
858
859         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
860                 int stat;
861
862                 chip->ecc.hwctl(mtd, NAND_ECC_READ);
863                 chip->read_buf(mtd, p, eccsize);
864
865                 if (chip->ecc.prepad) {
866                         chip->read_buf(mtd, oob, chip->ecc.prepad);
867                         oob += chip->ecc.prepad;
868                 }
869
870                 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
871                 chip->read_buf(mtd, oob, eccbytes);
872                 stat = chip->ecc.correct(mtd, p, oob, NULL);
873
874                 if (stat == -1)
875                         mtd->ecc_stats.failed++;
876                 else
877                         mtd->ecc_stats.corrected += stat;
878
879                 oob += eccbytes;
880
881                 if (chip->ecc.postpad) {
882                         chip->read_buf(mtd, oob, chip->ecc.postpad);
883                         oob += chip->ecc.postpad;
884                 }
885         }
886
887         /* Calculate remaining oob bytes */
888         i = mtd->oobsize - (oob - chip->oob_poi);
889         if (i)
890                 chip->read_buf(mtd, oob, i);
891
892         return 0;
893 }
894
895 /**
896  * nand_transfer_oob - [Internal] Transfer oob to client buffer
897  * @chip:       nand chip structure
898  * @oob:        oob destination address
899  * @ops:        oob ops structure
900  */
901 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
902                                   struct mtd_oob_ops *ops)
903 {
904         size_t len = ops->ooblen;
905
906         switch(ops->mode) {
907
908         case MTD_OOB_PLACE:
909         case MTD_OOB_RAW:
910                 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
911                 return oob + len;
912
913         case MTD_OOB_AUTO: {
914                 struct nand_oobfree *free = chip->ecc.layout->oobfree;
915                 uint32_t boffs = 0, roffs = ops->ooboffs;
916                 size_t bytes = 0;
917
918                 for(; free->length && len; free++, len -= bytes) {
919                         /* Read request not from offset 0 ? */
920                         if (unlikely(roffs)) {
921                                 if (roffs >= free->length) {
922                                         roffs -= free->length;
923                                         continue;
924                                 }
925                                 boffs = free->offset + roffs;
926                                 bytes = min_t(size_t, len,
927                                               (free->length - roffs));
928                                 roffs = 0;
929                         } else {
930                                 bytes = min_t(size_t, len, free->length);
931                                 boffs = free->offset;
932                         }
933                         memcpy(oob, chip->oob_poi + boffs, bytes);
934                         oob += bytes;
935                 }
936                 return oob;
937         }
938         default:
939                 BUG();
940         }
941         return NULL;
942 }
943
944 /**
945  * nand_do_read_ops - [Internal] Read data with ECC
946  *
947  * @mtd:        MTD device structure
948  * @from:       offset to read from
949  * @ops:        oob ops structure
950  *
951  * Internal function. Called with chip held.
952  */
953 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
954                             struct mtd_oob_ops *ops)
955 {
956         int chipnr, page, realpage, col, bytes, aligned;
957         struct nand_chip *chip = mtd->priv;
958         struct mtd_ecc_stats stats;
959         int blkcheck = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
960         int sndcmd = 1;
961         int ret = 0;
962         uint32_t readlen = ops->len;
963         uint8_t *bufpoi, *oob, *buf;
964
965         stats = mtd->ecc_stats;
966
967         chipnr = (int)(from >> chip->chip_shift);
968         chip->select_chip(mtd, chipnr);
969
970         realpage = (int)(from >> chip->page_shift);
971         page = realpage & chip->pagemask;
972
973         col = (int)(from & (mtd->writesize - 1));
974
975         buf = ops->datbuf;
976         oob = ops->oobbuf;
977
978         while(1) {
979                 bytes = min(mtd->writesize - col, readlen);
980                 aligned = (bytes == mtd->writesize);
981
982                 /* Is the current page in the buffer ? */
983                 if (realpage != chip->pagebuf || oob) {
984                         bufpoi = aligned ? buf : chip->buffers->databuf;
985
986                         if (likely(sndcmd)) {
987                                 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
988                                 sndcmd = 0;
989                         }
990
991                         /* Now read the page into the buffer */
992                         if (unlikely(ops->mode == MTD_OOB_RAW))
993                                 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi);
994                         else
995                                 ret = chip->ecc.read_page(mtd, chip, bufpoi);
996                         if (ret < 0)
997                                 break;
998
999                         /* Transfer not aligned data */
1000                         if (!aligned) {
1001                                 chip->pagebuf = realpage;
1002                                 memcpy(buf, chip->buffers->databuf + col, bytes);
1003                         }
1004
1005                         buf += bytes;
1006
1007                         if (unlikely(oob)) {
1008                                 /* Raw mode does data:oob:data:oob */
1009                                 if (ops->mode != MTD_OOB_RAW)
1010                                         oob = nand_transfer_oob(chip, oob, ops);
1011                                 else
1012                                         buf = nand_transfer_oob(chip, buf, ops);
1013                         }
1014
1015                         if (!(chip->options & NAND_NO_READRDY)) {
1016                                 /*
1017                                  * Apply delay or wait for ready/busy pin. Do
1018                                  * this before the AUTOINCR check, so no
1019                                  * problems arise if a chip which does auto
1020                                  * increment is marked as NOAUTOINCR by the
1021                                  * board driver.
1022                                  */
1023                                 if (!chip->dev_ready)
1024                                         udelay(chip->chip_delay);
1025                                 else
1026                                         nand_wait_ready(mtd);
1027                         }
1028                 } else {
1029                         memcpy(buf, chip->buffers->databuf + col, bytes);
1030                         buf += bytes;
1031                 }
1032
1033                 readlen -= bytes;
1034
1035                 if (!readlen)
1036                         break;
1037
1038                 /* For subsequent reads align to page boundary. */
1039                 col = 0;
1040                 /* Increment page address */
1041                 realpage++;
1042
1043                 page = realpage & chip->pagemask;
1044                 /* Check, if we cross a chip boundary */
1045                 if (!page) {
1046                         chipnr++;
1047                         chip->select_chip(mtd, -1);
1048                         chip->select_chip(mtd, chipnr);
1049                 }
1050
1051                 /* Check, if the chip supports auto page increment
1052                  * or if we have hit a block boundary.
1053                  */
1054                 if (!NAND_CANAUTOINCR(chip) || !(page & blkcheck))
1055                         sndcmd = 1;
1056         }
1057
1058         ops->retlen = ops->len - (size_t) readlen;
1059
1060         if (ret)
1061                 return ret;
1062
1063         if (mtd->ecc_stats.failed - stats.failed)
1064                 return -EBADMSG;
1065
1066         return  mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
1067 }
1068
1069 /**
1070  * nand_read - [MTD Interface] MTD compability function for nand_do_read_ecc
1071  * @mtd:        MTD device structure
1072  * @from:       offset to read from
1073  * @len:        number of bytes to read
1074  * @retlen:     pointer to variable to store the number of read bytes
1075  * @buf:        the databuffer to put data
1076  *
1077  * Get hold of the chip and call nand_do_read
1078  */
1079 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
1080                      size_t *retlen, uint8_t *buf)
1081 {
1082         struct nand_chip *chip = mtd->priv;
1083         int ret;
1084
1085         /* Do not allow reads past end of device */
1086         if ((from + len) > mtd->size)
1087                 return -EINVAL;
1088         if (!len)
1089                 return 0;
1090
1091         nand_get_device(chip, mtd, FL_READING);
1092
1093         chip->ops.len = len;
1094         chip->ops.datbuf = buf;
1095         chip->ops.oobbuf = NULL;
1096
1097         ret = nand_do_read_ops(mtd, from, &chip->ops);
1098
1099         *retlen = chip->ops.retlen;
1100
1101         nand_release_device(mtd);
1102
1103         return ret;
1104 }
1105
1106 /**
1107  * nand_read_oob_std - [REPLACABLE] the most common OOB data read function
1108  * @mtd:        mtd info structure
1109  * @chip:       nand chip info structure
1110  * @page:       page number to read
1111  * @sndcmd:     flag whether to issue read command or not
1112  */
1113 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1114                              int page, int sndcmd)
1115 {
1116         if (sndcmd) {
1117                 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1118                 sndcmd = 0;
1119         }
1120         chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1121         return sndcmd;
1122 }
1123
1124 /**
1125  * nand_read_oob_syndrome - [REPLACABLE] OOB data read function for HW ECC
1126  *                          with syndromes
1127  * @mtd:        mtd info structure
1128  * @chip:       nand chip info structure
1129  * @page:       page number to read
1130  * @sndcmd:     flag whether to issue read command or not
1131  */
1132 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1133                                   int page, int sndcmd)
1134 {
1135         uint8_t *buf = chip->oob_poi;
1136         int length = mtd->oobsize;
1137         int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1138         int eccsize = chip->ecc.size;
1139         uint8_t *bufpoi = buf;
1140         int i, toread, sndrnd = 0, pos;
1141
1142         chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
1143         for (i = 0; i < chip->ecc.steps; i++) {
1144                 if (sndrnd) {
1145                         pos = eccsize + i * (eccsize + chunk);
1146                         if (mtd->writesize > 512)
1147                                 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
1148                         else
1149                                 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
1150                 } else
1151                         sndrnd = 1;
1152                 toread = min_t(int, length, chunk);
1153                 chip->read_buf(mtd, bufpoi, toread);
1154                 bufpoi += toread;
1155                 length -= toread;
1156         }
1157         if (length > 0)
1158                 chip->read_buf(mtd, bufpoi, length);
1159
1160         return 1;
1161 }
1162
1163 /**
1164  * nand_write_oob_std - [REPLACABLE] the most common OOB data write function
1165  * @mtd:        mtd info structure
1166  * @chip:       nand chip info structure
1167  * @page:       page number to write
1168  */
1169 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1170                               int page)
1171 {
1172         int status = 0;
1173         const uint8_t *buf = chip->oob_poi;
1174         int length = mtd->oobsize;
1175
1176         chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
1177         chip->write_buf(mtd, buf, length);
1178         /* Send command to program the OOB data */
1179         chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1180
1181         status = chip->waitfunc(mtd, chip);
1182
1183         return status & NAND_STATUS_FAIL ? -EIO : 0;
1184 }
1185
1186 /**
1187  * nand_write_oob_syndrome - [REPLACABLE] OOB data write function for HW ECC
1188  *                           with syndrome - only for large page flash !
1189  * @mtd:        mtd info structure
1190  * @chip:       nand chip info structure
1191  * @page:       page number to write
1192  */
1193 static int nand_write_oob_syndrome(struct mtd_info *mtd,
1194                                    struct nand_chip *chip, int page)
1195 {
1196         int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1197         int eccsize = chip->ecc.size, length = mtd->oobsize;
1198         int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
1199         const uint8_t *bufpoi = chip->oob_poi;
1200
1201         /*
1202          * data-ecc-data-ecc ... ecc-oob
1203          * or
1204          * data-pad-ecc-pad-data-pad .... ecc-pad-oob
1205          */
1206         if (!chip->ecc.prepad && !chip->ecc.postpad) {
1207                 pos = steps * (eccsize + chunk);
1208                 steps = 0;
1209         } else
1210                 pos = eccsize;
1211
1212         chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
1213         for (i = 0; i < steps; i++) {
1214                 if (sndcmd) {
1215                         if (mtd->writesize <= 512) {
1216                                 uint32_t fill = 0xFFFFFFFF;
1217
1218                                 len = eccsize;
1219                                 while (len > 0) {
1220                                         int num = min_t(int, len, 4);
1221                                         chip->write_buf(mtd, (uint8_t *)&fill,
1222                                                         num);
1223                                         len -= num;
1224                                 }
1225                         } else {
1226                                 pos = eccsize + i * (eccsize + chunk);
1227                                 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
1228                         }
1229                 } else
1230                         sndcmd = 1;
1231                 len = min_t(int, length, chunk);
1232                 chip->write_buf(mtd, bufpoi, len);
1233                 bufpoi += len;
1234                 length -= len;
1235         }
1236         if (length > 0)
1237                 chip->write_buf(mtd, bufpoi, length);
1238
1239         chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1240         status = chip->waitfunc(mtd, chip);
1241
1242         return status & NAND_STATUS_FAIL ? -EIO : 0;
1243 }
1244
1245 /**
1246  * nand_do_read_oob - [Intern] NAND read out-of-band
1247  * @mtd:        MTD device structure
1248  * @from:       offset to read from
1249  * @ops:        oob operations description structure
1250  *
1251  * NAND read out-of-band data from the spare area
1252  */
1253 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
1254                             struct mtd_oob_ops *ops)
1255 {
1256         int page, realpage, chipnr, sndcmd = 1;
1257         struct nand_chip *chip = mtd->priv;
1258         int blkcheck = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
1259         int readlen = ops->len;
1260         uint8_t *buf = ops->oobbuf;
1261
1262         DEBUG(MTD_DEBUG_LEVEL3, "nand_read_oob: from = 0x%08Lx, len = %i\n",
1263               (unsigned long long)from, readlen);
1264
1265         chipnr = (int)(from >> chip->chip_shift);
1266         chip->select_chip(mtd, chipnr);
1267
1268         /* Shift to get page */
1269         realpage = (int)(from >> chip->page_shift);
1270         page = realpage & chip->pagemask;
1271
1272         while(1) {
1273                 sndcmd = chip->ecc.read_oob(mtd, chip, page, sndcmd);
1274                 buf = nand_transfer_oob(chip, buf, ops);
1275
1276                 if (!(chip->options & NAND_NO_READRDY)) {
1277                         /*
1278                          * Apply delay or wait for ready/busy pin. Do this
1279                          * before the AUTOINCR check, so no problems arise if a
1280                          * chip which does auto increment is marked as
1281                          * NOAUTOINCR by the board driver.
1282                          */
1283                         if (!chip->dev_ready)
1284                                 udelay(chip->chip_delay);
1285                         else
1286                                 nand_wait_ready(mtd);
1287                 }
1288
1289                 readlen -= ops->ooblen;
1290                 if (!readlen)
1291                         break;
1292
1293                 /* Increment page address */
1294                 realpage++;
1295
1296                 page = realpage & chip->pagemask;
1297                 /* Check, if we cross a chip boundary */
1298                 if (!page) {
1299                         chipnr++;
1300                         chip->select_chip(mtd, -1);
1301                         chip->select_chip(mtd, chipnr);
1302                 }
1303
1304                 /* Check, if the chip supports auto page increment
1305                  * or if we have hit a block boundary.
1306                  */
1307                 if (!NAND_CANAUTOINCR(chip) || !(page & blkcheck))
1308                         sndcmd = 1;
1309         }
1310
1311         ops->retlen = ops->len;
1312         return 0;
1313 }
1314
1315 /**
1316  * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
1317  * @mtd:        MTD device structure
1318  * @from:       offset to read from
1319  * @ops:        oob operation description structure
1320  *
1321  * NAND read data and/or out-of-band data
1322  */
1323 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
1324                          struct mtd_oob_ops *ops)
1325 {
1326         struct nand_chip *chip = mtd->priv;
1327         int ret = -ENOTSUPP;
1328
1329         ops->retlen = 0;
1330
1331         /* Do not allow reads past end of device */
1332         if ((from + ops->len) > mtd->size) {
1333                 DEBUG(MTD_DEBUG_LEVEL0, "nand_read_oob: "
1334                       "Attempt read beyond end of device\n");
1335                 return -EINVAL;
1336         }
1337
1338         nand_get_device(chip, mtd, FL_READING);
1339
1340         switch(ops->mode) {
1341         case MTD_OOB_PLACE:
1342         case MTD_OOB_AUTO:
1343         case MTD_OOB_RAW:
1344                 break;
1345
1346         default:
1347                 goto out;
1348         }
1349
1350         if (!ops->datbuf)
1351                 ret = nand_do_read_oob(mtd, from, ops);
1352         else
1353                 ret = nand_do_read_ops(mtd, from, ops);
1354
1355  out:
1356         nand_release_device(mtd);
1357         return ret;
1358 }
1359
1360
1361 /**
1362  * nand_write_page_raw - [Intern] raw page write function
1363  * @mtd:        mtd info structure
1364  * @chip:       nand chip info structure
1365  * @buf:        data buffer
1366  */
1367 static void nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1368                                 const uint8_t *buf)
1369 {
1370         chip->write_buf(mtd, buf, mtd->writesize);
1371         chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
1372 }
1373
1374 /**
1375  * nand_write_page_swecc - [REPLACABLE] software ecc based page write function
1376  * @mtd:        mtd info structure
1377  * @chip:       nand chip info structure
1378  * @buf:        data buffer
1379  */
1380 static void nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1381                                   const uint8_t *buf)
1382 {
1383         int i, eccsize = chip->ecc.size;
1384         int eccbytes = chip->ecc.bytes;
1385         int eccsteps = chip->ecc.steps;
1386         uint8_t *ecc_calc = chip->buffers->ecccalc;
1387         const uint8_t *p = buf;
1388         int *eccpos = chip->ecc.layout->eccpos;
1389
1390         /* Software ecc calculation */
1391         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1392                 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1393
1394         for (i = 0; i < chip->ecc.total; i++)
1395                 chip->oob_poi[eccpos[i]] = ecc_calc[i];
1396
1397         nand_write_page_raw(mtd, chip, buf);
1398 }
1399
1400 /**
1401  * nand_write_page_hwecc - [REPLACABLE] hardware ecc based page write function
1402  * @mtd:        mtd info structure
1403  * @chip:       nand chip info structure
1404  * @buf:        data buffer
1405  */
1406 static void nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1407                                   const uint8_t *buf)
1408 {
1409         int i, eccsize = chip->ecc.size;
1410         int eccbytes = chip->ecc.bytes;
1411         int eccsteps = chip->ecc.steps;
1412         uint8_t *ecc_calc = chip->buffers->ecccalc;
1413         const uint8_t *p = buf;
1414         int *eccpos = chip->ecc.layout->eccpos;
1415
1416         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1417                 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
1418                 chip->write_buf(mtd, p, eccsize);
1419                 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1420         }
1421
1422         for (i = 0; i < chip->ecc.total; i++)
1423                 chip->oob_poi[eccpos[i]] = ecc_calc[i];
1424
1425         chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
1426 }
1427
1428 /**
1429  * nand_write_page_syndrome - [REPLACABLE] hardware ecc syndrom based page write
1430  * @mtd:        mtd info structure
1431  * @chip:       nand chip info structure
1432  * @buf:        data buffer
1433  *
1434  * The hw generator calculates the error syndrome automatically. Therefor
1435  * we need a special oob layout and handling.
1436  */
1437 static void nand_write_page_syndrome(struct mtd_info *mtd,
1438                                     struct nand_chip *chip, const uint8_t *buf)
1439 {
1440         int i, eccsize = chip->ecc.size;
1441         int eccbytes = chip->ecc.bytes;
1442         int eccsteps = chip->ecc.steps;
1443         const uint8_t *p = buf;
1444         uint8_t *oob = chip->oob_poi;
1445
1446         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1447
1448                 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
1449                 chip->write_buf(mtd, p, eccsize);
1450
1451                 if (chip->ecc.prepad) {
1452                         chip->write_buf(mtd, oob, chip->ecc.prepad);
1453                         oob += chip->ecc.prepad;
1454                 }
1455
1456                 chip->ecc.calculate(mtd, p, oob);
1457                 chip->write_buf(mtd, oob, eccbytes);
1458                 oob += eccbytes;
1459
1460                 if (chip->ecc.postpad) {
1461                         chip->write_buf(mtd, oob, chip->ecc.postpad);
1462                         oob += chip->ecc.postpad;
1463                 }
1464         }
1465
1466         /* Calculate remaining oob bytes */
1467         i = mtd->oobsize - (oob - chip->oob_poi);
1468         if (i)
1469                 chip->write_buf(mtd, oob, i);
1470 }
1471
1472 /**
1473  * nand_write_page - [REPLACEABLE] write one page
1474  * @mtd:        MTD device structure
1475  * @chip:       NAND chip descriptor
1476  * @buf:        the data to write
1477  * @page:       page number to write
1478  * @cached:     cached programming
1479  */
1480 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
1481                            const uint8_t *buf, int page, int cached, int raw)
1482 {
1483         int status;
1484
1485         chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
1486
1487         if (unlikely(raw))
1488                 chip->ecc.write_page_raw(mtd, chip, buf);
1489         else
1490                 chip->ecc.write_page(mtd, chip, buf);
1491
1492         /*
1493          * Cached progamming disabled for now, Not sure if its worth the
1494          * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s)
1495          */
1496         cached = 0;
1497
1498         if (!cached || !(chip->options & NAND_CACHEPRG)) {
1499
1500                 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1501                 status = chip->waitfunc(mtd, chip);
1502                 /*
1503                  * See if operation failed and additional status checks are
1504                  * available
1505                  */
1506                 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
1507                         status = chip->errstat(mtd, chip, FL_WRITING, status,
1508                                                page);
1509
1510                 if (status & NAND_STATUS_FAIL)
1511                         return -EIO;
1512         } else {
1513                 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
1514                 status = chip->waitfunc(mtd, chip);
1515         }
1516
1517 #ifdef CONFIG_MTD_NAND_VERIFY_WRITE
1518         /* Send command to read back the data */
1519         chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1520
1521         if (chip->verify_buf(mtd, buf, mtd->writesize))
1522                 return -EIO;
1523 #endif
1524         return 0;
1525 }
1526
1527 /**
1528  * nand_fill_oob - [Internal] Transfer client buffer to oob
1529  * @chip:       nand chip structure
1530  * @oob:        oob data buffer
1531  * @ops:        oob ops structure
1532  */
1533 static uint8_t *nand_fill_oob(struct nand_chip *chip, uint8_t *oob,
1534                                   struct mtd_oob_ops *ops)
1535 {
1536         size_t len = ops->ooblen;
1537
1538         switch(ops->mode) {
1539
1540         case MTD_OOB_PLACE:
1541         case MTD_OOB_RAW:
1542                 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
1543                 return oob + len;
1544
1545         case MTD_OOB_AUTO: {
1546                 struct nand_oobfree *free = chip->ecc.layout->oobfree;
1547                 uint32_t boffs = 0, woffs = ops->ooboffs;
1548                 size_t bytes = 0;
1549
1550                 for(; free->length && len; free++, len -= bytes) {
1551                         /* Write request not from offset 0 ? */
1552                         if (unlikely(woffs)) {
1553                                 if (woffs >= free->length) {
1554                                         woffs -= free->length;
1555                                         continue;
1556                                 }
1557                                 boffs = free->offset + woffs;
1558                                 bytes = min_t(size_t, len,
1559                                               (free->length - woffs));
1560                                 woffs = 0;
1561                         } else {
1562                                 bytes = min_t(size_t, len, free->length);
1563                                 boffs = free->offset;
1564                         }
1565                         memcpy(chip->oob_poi + boffs, oob, bytes);
1566                         oob += bytes;
1567                 }
1568                 return oob;
1569         }
1570         default:
1571                 BUG();
1572         }
1573         return NULL;
1574 }
1575
1576 #define NOTALIGNED(x) (x & (mtd->writesize-1)) != 0
1577
1578 /**
1579  * nand_do_write_ops - [Internal] NAND write with ECC
1580  * @mtd:        MTD device structure
1581  * @to:         offset to write to
1582  * @ops:        oob operations description structure
1583  *
1584  * NAND write with ECC
1585  */
1586 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
1587                              struct mtd_oob_ops *ops)
1588 {
1589         int chipnr, realpage, page, blockmask;
1590         struct nand_chip *chip = mtd->priv;
1591         uint32_t writelen = ops->len;
1592         uint8_t *oob = ops->oobbuf;
1593         uint8_t *buf = ops->datbuf;
1594         int bytes = mtd->writesize;
1595         int ret;
1596
1597         ops->retlen = 0;
1598
1599         /* reject writes, which are not page aligned */
1600         if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
1601                 printk(KERN_NOTICE "nand_write: "
1602                        "Attempt to write not page aligned data\n");
1603                 return -EINVAL;
1604         }
1605
1606         if (!writelen)
1607                 return 0;
1608
1609         chipnr = (int)(to >> chip->chip_shift);
1610         chip->select_chip(mtd, chipnr);
1611
1612         /* Check, if it is write protected */
1613         if (nand_check_wp(mtd))
1614                 return -EIO;
1615
1616         realpage = (int)(to >> chip->page_shift);
1617         page = realpage & chip->pagemask;
1618         blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
1619
1620         /* Invalidate the page cache, when we write to the cached page */
1621         if (to <= (chip->pagebuf << chip->page_shift) &&
1622             (chip->pagebuf << chip->page_shift) < (to + ops->len))
1623                 chip->pagebuf = -1;
1624
1625         /* If we're not given explicit OOB data, let it be 0xFF */
1626         if (likely(!oob))
1627                 memset(chip->oob_poi, 0xff, mtd->oobsize);
1628
1629         while(1) {
1630                 int cached = writelen > bytes && page != blockmask;
1631
1632                 if (unlikely(oob))
1633                         oob = nand_fill_oob(chip, oob, ops);
1634
1635                 ret = chip->write_page(mtd, chip, buf, page, cached,
1636                                        (ops->mode == MTD_OOB_RAW));
1637                 if (ret)
1638                         break;
1639
1640                 writelen -= bytes;
1641                 if (!writelen)
1642                         break;
1643
1644                 buf += bytes;
1645                 realpage++;
1646
1647                 page = realpage & chip->pagemask;
1648                 /* Check, if we cross a chip boundary */
1649                 if (!page) {
1650                         chipnr++;
1651                         chip->select_chip(mtd, -1);
1652                         chip->select_chip(mtd, chipnr);
1653                 }
1654         }
1655
1656         ops->retlen = ops->len - writelen;
1657         return ret;
1658 }
1659
1660 /**
1661  * nand_write - [MTD Interface] NAND write with ECC
1662  * @mtd:        MTD device structure
1663  * @to:         offset to write to
1664  * @len:        number of bytes to write
1665  * @retlen:     pointer to variable to store the number of written bytes
1666  * @buf:        the data to write
1667  *
1668  * NAND write with ECC
1669  */
1670 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
1671                           size_t *retlen, const uint8_t *buf)
1672 {
1673         struct nand_chip *chip = mtd->priv;
1674         int ret;
1675
1676         /* Do not allow reads past end of device */
1677         if ((to + len) > mtd->size)
1678                 return -EINVAL;
1679         if (!len)
1680                 return 0;
1681
1682         nand_get_device(chip, mtd, FL_WRITING);
1683
1684         chip->ops.len = len;
1685         chip->ops.datbuf = (uint8_t *)buf;
1686         chip->ops.oobbuf = NULL;
1687
1688         ret = nand_do_write_ops(mtd, to, &chip->ops);
1689
1690         *retlen = chip->ops.retlen;
1691
1692         nand_release_device(mtd);
1693
1694         return ret;
1695 }
1696
1697 /**
1698  * nand_do_write_oob - [MTD Interface] NAND write out-of-band
1699  * @mtd:        MTD device structure
1700  * @to:         offset to write to
1701  * @ops:        oob operation description structure
1702  *
1703  * NAND write out-of-band
1704  */
1705 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
1706                              struct mtd_oob_ops *ops)
1707 {
1708         int chipnr, page, status;
1709         struct nand_chip *chip = mtd->priv;
1710
1711         DEBUG(MTD_DEBUG_LEVEL3, "nand_write_oob: to = 0x%08x, len = %i\n",
1712               (unsigned int)to, (int)ops->len);
1713
1714         /* Do not allow write past end of page */
1715         if ((ops->ooboffs + ops->len) > mtd->oobsize) {
1716                 DEBUG(MTD_DEBUG_LEVEL0, "nand_write_oob: "
1717                       "Attempt to write past end of page\n");
1718                 return -EINVAL;
1719         }
1720
1721         chipnr = (int)(to >> chip->chip_shift);
1722         chip->select_chip(mtd, chipnr);
1723
1724         /* Shift to get page */
1725         page = (int)(to >> chip->page_shift);
1726
1727         /*
1728          * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
1729          * of my DiskOnChip 2000 test units) will clear the whole data page too
1730          * if we don't do this. I have no clue why, but I seem to have 'fixed'
1731          * it in the doc2000 driver in August 1999.  dwmw2.
1732          */
1733         chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1734
1735         /* Check, if it is write protected */
1736         if (nand_check_wp(mtd))
1737                 return -EROFS;
1738
1739         /* Invalidate the page cache, if we write to the cached page */
1740         if (page == chip->pagebuf)
1741                 chip->pagebuf = -1;
1742
1743         memset(chip->oob_poi, 0xff, mtd->oobsize);
1744         nand_fill_oob(chip, ops->oobbuf, ops);
1745         status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
1746         memset(chip->oob_poi, 0xff, mtd->oobsize);
1747
1748         if (status)
1749                 return status;
1750
1751         ops->retlen = ops->len;
1752
1753         return 0;
1754 }
1755
1756 /**
1757  * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
1758  * @mtd:        MTD device structure
1759  * @to:         offset to write to
1760  * @ops:        oob operation description structure
1761  */
1762 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
1763                           struct mtd_oob_ops *ops)
1764 {
1765         struct nand_chip *chip = mtd->priv;
1766         int ret = -ENOTSUPP;
1767
1768         ops->retlen = 0;
1769
1770         /* Do not allow writes past end of device */
1771         if ((to + ops->len) > mtd->size) {
1772                 DEBUG(MTD_DEBUG_LEVEL0, "nand_read_oob: "
1773                       "Attempt read beyond end of device\n");
1774                 return -EINVAL;
1775         }
1776
1777         nand_get_device(chip, mtd, FL_WRITING);
1778
1779         switch(ops->mode) {
1780         case MTD_OOB_PLACE:
1781         case MTD_OOB_AUTO:
1782         case MTD_OOB_RAW:
1783                 break;
1784
1785         default:
1786                 goto out;
1787         }
1788
1789         if (!ops->datbuf)
1790                 ret = nand_do_write_oob(mtd, to, ops);
1791         else
1792                 ret = nand_do_write_ops(mtd, to, ops);
1793
1794  out:
1795         nand_release_device(mtd);
1796         return ret;
1797 }
1798
1799 /**
1800  * single_erease_cmd - [GENERIC] NAND standard block erase command function
1801  * @mtd:        MTD device structure
1802  * @page:       the page address of the block which will be erased
1803  *
1804  * Standard erase command for NAND chips
1805  */
1806 static void single_erase_cmd(struct mtd_info *mtd, int page)
1807 {
1808         struct nand_chip *chip = mtd->priv;
1809         /* Send commands to erase a block */
1810         chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
1811         chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
1812 }
1813
1814 /**
1815  * multi_erease_cmd - [GENERIC] AND specific block erase command function
1816  * @mtd:        MTD device structure
1817  * @page:       the page address of the block which will be erased
1818  *
1819  * AND multi block erase command function
1820  * Erase 4 consecutive blocks
1821  */
1822 static void multi_erase_cmd(struct mtd_info *mtd, int page)
1823 {
1824         struct nand_chip *chip = mtd->priv;
1825         /* Send commands to erase a block */
1826         chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page++);
1827         chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page++);
1828         chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page++);
1829         chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
1830         chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
1831 }
1832
1833 /**
1834  * nand_erase - [MTD Interface] erase block(s)
1835  * @mtd:        MTD device structure
1836  * @instr:      erase instruction
1837  *
1838  * Erase one ore more blocks
1839  */
1840 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
1841 {
1842         return nand_erase_nand(mtd, instr, 0);
1843 }
1844
1845 #define BBT_PAGE_MASK   0xffffff3f
1846 /**
1847  * nand_erase_nand - [Internal] erase block(s)
1848  * @mtd:        MTD device structure
1849  * @instr:      erase instruction
1850  * @allowbbt:   allow erasing the bbt area
1851  *
1852  * Erase one ore more blocks
1853  */
1854 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
1855                     int allowbbt)
1856 {
1857         int page, len, status, pages_per_block, ret, chipnr;
1858         struct nand_chip *chip = mtd->priv;
1859         int rewrite_bbt[NAND_MAX_CHIPS]={0};
1860         unsigned int bbt_masked_page = 0xffffffff;
1861
1862         DEBUG(MTD_DEBUG_LEVEL3, "nand_erase: start = 0x%08x, len = %i\n",
1863               (unsigned int)instr->addr, (unsigned int)instr->len);
1864
1865         /* Start address must align on block boundary */
1866         if (instr->addr & ((1 << chip->phys_erase_shift) - 1)) {
1867                 DEBUG(MTD_DEBUG_LEVEL0, "nand_erase: Unaligned address\n");
1868                 return -EINVAL;
1869         }
1870
1871         /* Length must align on block boundary */
1872         if (instr->len & ((1 << chip->phys_erase_shift) - 1)) {
1873                 DEBUG(MTD_DEBUG_LEVEL0, "nand_erase: "
1874                       "Length not block aligned\n");
1875                 return -EINVAL;
1876         }
1877
1878         /* Do not allow erase past end of device */
1879         if ((instr->len + instr->addr) > mtd->size) {
1880                 DEBUG(MTD_DEBUG_LEVEL0, "nand_erase: "
1881                       "Erase past end of device\n");
1882                 return -EINVAL;
1883         }
1884
1885         instr->fail_addr = 0xffffffff;
1886
1887         /* Grab the lock and see if the device is available */
1888         nand_get_device(chip, mtd, FL_ERASING);
1889
1890         /* Shift to get first page */
1891         page = (int)(instr->addr >> chip->page_shift);
1892         chipnr = (int)(instr->addr >> chip->chip_shift);
1893
1894         /* Calculate pages in each block */
1895         pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
1896
1897         /* Select the NAND device */
1898         chip->select_chip(mtd, chipnr);
1899
1900         /* Check, if it is write protected */
1901         if (nand_check_wp(mtd)) {
1902                 DEBUG(MTD_DEBUG_LEVEL0, "nand_erase: "
1903                       "Device is write protected!!!\n");
1904                 instr->state = MTD_ERASE_FAILED;
1905                 goto erase_exit;
1906         }
1907
1908         /*
1909          * If BBT requires refresh, set the BBT page mask to see if the BBT
1910          * should be rewritten. Otherwise the mask is set to 0xffffffff which
1911          * can not be matched. This is also done when the bbt is actually
1912          * erased to avoid recusrsive updates
1913          */
1914         if (chip->options & BBT_AUTO_REFRESH && !allowbbt)
1915                 bbt_masked_page = chip->bbt_td->pages[chipnr] & BBT_PAGE_MASK;
1916
1917         /* Loop through the pages */
1918         len = instr->len;
1919
1920         instr->state = MTD_ERASING;
1921
1922         while (len) {
1923                 /*
1924                  * heck if we have a bad block, we do not erase bad blocks !
1925                  */
1926                 if (nand_block_checkbad(mtd, ((loff_t) page) <<
1927                                         chip->page_shift, 0, allowbbt)) {
1928                         printk(KERN_WARNING "nand_erase: attempt to erase a "
1929                                "bad block at page 0x%08x\n", page);
1930                         instr->state = MTD_ERASE_FAILED;
1931                         goto erase_exit;
1932                 }
1933
1934                 /*
1935                  * Invalidate the page cache, if we erase the block which
1936                  * contains the current cached page
1937                  */
1938                 if (page <= chip->pagebuf && chip->pagebuf <
1939                     (page + pages_per_block))
1940                         chip->pagebuf = -1;
1941
1942                 chip->erase_cmd(mtd, page & chip->pagemask);
1943
1944                 status = chip->waitfunc(mtd, chip);
1945
1946                 /*
1947                  * See if operation failed and additional status checks are
1948                  * available
1949                  */
1950                 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
1951                         status = chip->errstat(mtd, chip, FL_ERASING,
1952                                                status, page);
1953
1954                 /* See if block erase succeeded */
1955                 if (status & NAND_STATUS_FAIL) {
1956                         DEBUG(MTD_DEBUG_LEVEL0, "nand_erase: "
1957                               "Failed erase, page 0x%08x\n", page);
1958                         instr->state = MTD_ERASE_FAILED;
1959                         instr->fail_addr = (page << chip->page_shift);
1960                         goto erase_exit;
1961                 }
1962
1963                 /*
1964                  * If BBT requires refresh, set the BBT rewrite flag to the
1965                  * page being erased
1966                  */
1967                 if (bbt_masked_page != 0xffffffff &&
1968                     (page & BBT_PAGE_MASK) == bbt_masked_page)
1969                             rewrite_bbt[chipnr] = (page << chip->page_shift);
1970
1971                 /* Increment page address and decrement length */
1972                 len -= (1 << chip->phys_erase_shift);
1973                 page += pages_per_block;
1974
1975                 /* Check, if we cross a chip boundary */
1976                 if (len && !(page & chip->pagemask)) {
1977                         chipnr++;
1978                         chip->select_chip(mtd, -1);
1979                         chip->select_chip(mtd, chipnr);
1980
1981                         /*
1982                          * If BBT requires refresh and BBT-PERCHIP, set the BBT
1983                          * page mask to see if this BBT should be rewritten
1984                          */
1985                         if (bbt_masked_page != 0xffffffff &&
1986                             (chip->bbt_td->options & NAND_BBT_PERCHIP))
1987                                 bbt_masked_page = chip->bbt_td->pages[chipnr] &
1988                                         BBT_PAGE_MASK;
1989                 }
1990         }
1991         instr->state = MTD_ERASE_DONE;
1992
1993  erase_exit:
1994
1995         ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
1996         /* Do call back function */
1997         if (!ret)
1998                 mtd_erase_callback(instr);
1999
2000         /* Deselect and wake up anyone waiting on the device */
2001         nand_release_device(mtd);
2002
2003         /*
2004          * If BBT requires refresh and erase was successful, rewrite any
2005          * selected bad block tables
2006          */
2007         if (bbt_masked_page == 0xffffffff || ret)
2008                 return ret;
2009
2010         for (chipnr = 0; chipnr < chip->numchips; chipnr++) {
2011                 if (!rewrite_bbt[chipnr])
2012                         continue;
2013                 /* update the BBT for chip */
2014                 DEBUG(MTD_DEBUG_LEVEL0, "nand_erase_nand: nand_update_bbt "
2015                       "(%d:0x%0x 0x%0x)\n", chipnr, rewrite_bbt[chipnr],
2016                       chip->bbt_td->pages[chipnr]);
2017                 nand_update_bbt(mtd, rewrite_bbt[chipnr]);
2018         }
2019
2020         /* Return more or less happy */
2021         return ret;
2022 }
2023
2024 /**
2025  * nand_sync - [MTD Interface] sync
2026  * @mtd:        MTD device structure
2027  *
2028  * Sync is actually a wait for chip ready function
2029  */
2030 static void nand_sync(struct mtd_info *mtd)
2031 {
2032         struct nand_chip *chip = mtd->priv;
2033
2034         DEBUG(MTD_DEBUG_LEVEL3, "nand_sync: called\n");
2035
2036         /* Grab the lock and see if the device is available */
2037         nand_get_device(chip, mtd, FL_SYNCING);
2038         /* Release it and go back */
2039         nand_release_device(mtd);
2040 }
2041
2042 /**
2043  * nand_block_isbad - [MTD Interface] Check if block at offset is bad
2044  * @mtd:        MTD device structure
2045  * @offs:       offset relative to mtd start
2046  */
2047 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
2048 {
2049         /* Check for invalid offset */
2050         if (offs > mtd->size)
2051                 return -EINVAL;
2052
2053         return nand_block_checkbad(mtd, offs, 1, 0);
2054 }
2055
2056 /**
2057  * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
2058  * @mtd:        MTD device structure
2059  * @ofs:        offset relative to mtd start
2060  */
2061 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
2062 {
2063         struct nand_chip *chip = mtd->priv;
2064         int ret;
2065
2066         if ((ret = nand_block_isbad(mtd, ofs))) {
2067                 /* If it was bad already, return success and do nothing. */
2068                 if (ret > 0)
2069                         return 0;
2070                 return ret;
2071         }
2072
2073         return chip->block_markbad(mtd, ofs);
2074 }
2075
2076 /**
2077  * nand_suspend - [MTD Interface] Suspend the NAND flash
2078  * @mtd:        MTD device structure
2079  */
2080 static int nand_suspend(struct mtd_info *mtd)
2081 {
2082         struct nand_chip *chip = mtd->priv;
2083
2084         return nand_get_device(chip, mtd, FL_PM_SUSPENDED);
2085 }
2086
2087 /**
2088  * nand_resume - [MTD Interface] Resume the NAND flash
2089  * @mtd:        MTD device structure
2090  */
2091 static void nand_resume(struct mtd_info *mtd)
2092 {
2093         struct nand_chip *chip = mtd->priv;
2094
2095         if (chip->state == FL_PM_SUSPENDED)
2096                 nand_release_device(mtd);
2097         else
2098                 printk(KERN_ERR "nand_resume() called for a chip which is not "
2099                        "in suspended state\n");
2100 }
2101
2102 /*
2103  * Set default functions
2104  */
2105 static void nand_set_defaults(struct nand_chip *chip, int busw)
2106 {
2107         /* check for proper chip_delay setup, set 20us if not */
2108         if (!chip->chip_delay)
2109                 chip->chip_delay = 20;
2110
2111         /* check, if a user supplied command function given */
2112         if (chip->cmdfunc == NULL)
2113                 chip->cmdfunc = nand_command;
2114
2115         /* check, if a user supplied wait function given */
2116         if (chip->waitfunc == NULL)
2117                 chip->waitfunc = nand_wait;
2118
2119         if (!chip->select_chip)
2120                 chip->select_chip = nand_select_chip;
2121         if (!chip->read_byte)
2122                 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
2123         if (!chip->read_word)
2124                 chip->read_word = nand_read_word;
2125         if (!chip->block_bad)
2126                 chip->block_bad = nand_block_bad;
2127         if (!chip->block_markbad)
2128                 chip->block_markbad = nand_default_block_markbad;
2129         if (!chip->write_buf)
2130                 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
2131         if (!chip->read_buf)
2132                 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
2133         if (!chip->verify_buf)
2134                 chip->verify_buf = busw ? nand_verify_buf16 : nand_verify_buf;
2135         if (!chip->scan_bbt)
2136                 chip->scan_bbt = nand_default_bbt;
2137
2138         if (!chip->controller) {
2139                 chip->controller = &chip->hwcontrol;
2140                 spin_lock_init(&chip->controller->lock);
2141                 init_waitqueue_head(&chip->controller->wq);
2142         }
2143
2144 }
2145
2146 /*
2147  * Get the flash and manufacturer id and lookup if the type is supported
2148  */
2149 static struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
2150                                                   struct nand_chip *chip,
2151                                                   int busw, int *maf_id)
2152 {
2153         struct nand_flash_dev *type = NULL;
2154         int i, dev_id, maf_idx;
2155
2156         /* Select the device */
2157         chip->select_chip(mtd, 0);
2158
2159         /* Send the command for reading device ID */
2160         chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
2161
2162         /* Read manufacturer and device IDs */
2163         *maf_id = chip->read_byte(mtd);
2164         dev_id = chip->read_byte(mtd);
2165
2166         /* Lookup the flash id */
2167         for (i = 0; nand_flash_ids[i].name != NULL; i++) {
2168                 if (dev_id == nand_flash_ids[i].id) {
2169                         type =  &nand_flash_ids[i];
2170                         break;
2171                 }
2172         }
2173
2174         if (!type)
2175                 return ERR_PTR(-ENODEV);
2176
2177         if (!mtd->name)
2178                 mtd->name = type->name;
2179
2180         chip->chipsize = type->chipsize << 20;
2181
2182         /* Newer devices have all the information in additional id bytes */
2183         if (!type->pagesize) {
2184                 int extid;
2185                 /* The 3rd id byte contains non relevant data ATM */
2186                 extid = chip->read_byte(mtd);
2187                 /* The 4th id byte is the important one */
2188                 extid = chip->read_byte(mtd);
2189                 /* Calc pagesize */
2190                 mtd->writesize = 1024 << (extid & 0x3);
2191                 extid >>= 2;
2192                 /* Calc oobsize */
2193                 mtd->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
2194                 extid >>= 2;
2195                 /* Calc blocksize. Blocksize is multiples of 64KiB */
2196                 mtd->erasesize = (64 * 1024) << (extid & 0x03);
2197                 extid >>= 2;
2198                 /* Get buswidth information */
2199                 busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
2200
2201         } else {
2202                 /*
2203                  * Old devices have chip data hardcoded in the device id table
2204                  */
2205                 mtd->erasesize = type->erasesize;
2206                 mtd->writesize = type->pagesize;
2207                 mtd->oobsize = mtd->writesize / 32;
2208                 busw = type->options & NAND_BUSWIDTH_16;
2209         }
2210
2211         /* Try to identify manufacturer */
2212         for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
2213                 if (nand_manuf_ids[maf_idx].id == *maf_id)
2214                         break;
2215         }
2216
2217         /*
2218          * Check, if buswidth is correct. Hardware drivers should set
2219          * chip correct !
2220          */
2221         if (busw != (chip->options & NAND_BUSWIDTH_16)) {
2222                 printk(KERN_INFO "NAND device: Manufacturer ID:"
2223                        " 0x%02x, Chip ID: 0x%02x (%s %s)\n", *maf_id,
2224                        dev_id, nand_manuf_ids[maf_idx].name, mtd->name);
2225                 printk(KERN_WARNING "NAND bus width %d instead %d bit\n",
2226                        (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
2227                        busw ? 16 : 8);
2228                 return ERR_PTR(-EINVAL);
2229         }
2230
2231         /* Calculate the address shift from the page size */
2232         chip->page_shift = ffs(mtd->writesize) - 1;
2233         /* Convert chipsize to number of pages per chip -1. */
2234         chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
2235
2236         chip->bbt_erase_shift = chip->phys_erase_shift =
2237                 ffs(mtd->erasesize) - 1;
2238         chip->chip_shift = ffs(chip->chipsize) - 1;
2239
2240         /* Set the bad block position */
2241         chip->badblockpos = mtd->writesize > 512 ?
2242                 NAND_LARGE_BADBLOCK_POS : NAND_SMALL_BADBLOCK_POS;
2243
2244         /* Get chip options, preserve non chip based options */
2245         chip->options &= ~NAND_CHIPOPTIONS_MSK;
2246         chip->options |= type->options & NAND_CHIPOPTIONS_MSK;
2247
2248         /*
2249          * Set chip as a default. Board drivers can override it, if necessary
2250          */
2251         chip->options |= NAND_NO_AUTOINCR;
2252
2253         /* Check if chip is a not a samsung device. Do not clear the
2254          * options for chips which are not having an extended id.
2255          */
2256         if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
2257                 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
2258
2259         /* Check for AND chips with 4 page planes */
2260         if (chip->options & NAND_4PAGE_ARRAY)
2261                 chip->erase_cmd = multi_erase_cmd;
2262         else
2263                 chip->erase_cmd = single_erase_cmd;
2264
2265         /* Do not replace user supplied command function ! */
2266         if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
2267                 chip->cmdfunc = nand_command_lp;
2268
2269         printk(KERN_INFO "NAND device: Manufacturer ID:"
2270                " 0x%02x, Chip ID: 0x%02x (%s %s)\n", *maf_id, dev_id,
2271                nand_manuf_ids[maf_idx].name, type->name);
2272
2273         return type;
2274 }
2275
2276 /**
2277  * nand_scan_ident - [NAND Interface] Scan for the NAND device
2278  * @mtd:             MTD device structure
2279  * @maxchips:        Number of chips to scan for
2280  *
2281  * This is the first phase of the normal nand_scan() function. It
2282  * reads the flash ID and sets up MTD fields accordingly.
2283  *
2284  * The mtd->owner field must be set to the module of the caller.
2285  */
2286 int nand_scan_ident(struct mtd_info *mtd, int maxchips)
2287 {
2288         int i, busw, nand_maf_id;
2289         struct nand_chip *chip = mtd->priv;
2290         struct nand_flash_dev *type;
2291
2292         /* Get buswidth to select the correct functions */
2293         busw = chip->options & NAND_BUSWIDTH_16;
2294         /* Set the default functions */
2295         nand_set_defaults(chip, busw);
2296
2297         /* Read the flash type */
2298         type = nand_get_flash_type(mtd, chip, busw, &nand_maf_id);
2299
2300         if (IS_ERR(type)) {
2301                 printk(KERN_WARNING "No NAND device found!!!\n");
2302                 chip->select_chip(mtd, -1);
2303                 return PTR_ERR(type);
2304         }
2305
2306         /* Check for a chip array */
2307         for (i = 1; i < maxchips; i++) {
2308                 chip->select_chip(mtd, i);
2309                 /* Send the command for reading device ID */
2310                 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
2311                 /* Read manufacturer and device IDs */
2312                 if (nand_maf_id != chip->read_byte(mtd) ||
2313                     type->id != chip->read_byte(mtd))
2314                         break;
2315         }
2316         if (i > 1)
2317                 printk(KERN_INFO "%d NAND chips detected\n", i);
2318
2319         /* Store the number of chips and calc total size for mtd */
2320         chip->numchips = i;
2321         mtd->size = i * chip->chipsize;
2322
2323         return 0;
2324 }
2325
2326
2327 /**
2328  * nand_scan_tail - [NAND Interface] Scan for the NAND device
2329  * @mtd:            MTD device structure
2330  * @maxchips:       Number of chips to scan for
2331  *
2332  * This is the second phase of the normal nand_scan() function. It
2333  * fills out all the uninitialized function pointers with the defaults
2334  * and scans for a bad block table if appropriate.
2335  */
2336 int nand_scan_tail(struct mtd_info *mtd)
2337 {
2338         int i;
2339         struct nand_chip *chip = mtd->priv;
2340
2341         if (!(chip->options & NAND_OWN_BUFFERS))
2342                 chip->buffers = kmalloc(sizeof(*chip->buffers), GFP_KERNEL);
2343         if (!chip->buffers)
2344                 return -ENOMEM;
2345
2346         /* Set the internal oob buffer location, just after the page data */
2347         chip->oob_poi = chip->buffers + mtd->writesize;
2348
2349         /*
2350          * If no default placement scheme is given, select an appropriate one
2351          */
2352         if (!chip->ecc.layout) {
2353                 switch (mtd->oobsize) {
2354                 case 8:
2355                         chip->ecc.layout = &nand_oob_8;
2356                         break;
2357                 case 16:
2358                         chip->ecc.layout = &nand_oob_16;
2359                         break;
2360                 case 64:
2361                         chip->ecc.layout = &nand_oob_64;
2362                         break;
2363                 default:
2364                         printk(KERN_WARNING "No oob scheme defined for "
2365                                "oobsize %d\n", mtd->oobsize);
2366                         BUG();
2367                 }
2368         }
2369
2370         if (!chip->write_page)
2371                 chip->write_page = nand_write_page;
2372
2373         /*
2374          * check ECC mode, default to software if 3byte/512byte hardware ECC is
2375          * selected and we have 256 byte pagesize fallback to software ECC
2376          */
2377         if (!chip->ecc.read_page_raw)
2378                 chip->ecc.read_page_raw = nand_read_page_raw;
2379         if (!chip->ecc.write_page_raw)
2380                 chip->ecc.write_page_raw = nand_write_page_raw;
2381
2382         switch (chip->ecc.mode) {
2383         case NAND_ECC_HW:
2384                 /* Use standard hwecc read page function ? */
2385                 if (!chip->ecc.read_page)
2386                         chip->ecc.read_page = nand_read_page_hwecc;
2387                 if (!chip->ecc.write_page)
2388                         chip->ecc.write_page = nand_write_page_hwecc;
2389                 if (!chip->ecc.read_oob)
2390                         chip->ecc.read_oob = nand_read_oob_std;
2391                 if (!chip->ecc.write_oob)
2392                         chip->ecc.write_oob = nand_write_oob_std;
2393
2394         case NAND_ECC_HW_SYNDROME:
2395                 if (!chip->ecc.calculate || !chip->ecc.correct ||
2396                     !chip->ecc.hwctl) {
2397                         printk(KERN_WARNING "No ECC functions supplied, "
2398                                "Hardware ECC not possible\n");
2399                         BUG();
2400                 }
2401                 /* Use standard syndrome read/write page function ? */
2402                 if (!chip->ecc.read_page)
2403                         chip->ecc.read_page = nand_read_page_syndrome;
2404                 if (!chip->ecc.write_page)
2405                         chip->ecc.write_page = nand_write_page_syndrome;
2406                 if (!chip->ecc.read_oob)
2407                         chip->ecc.read_oob = nand_read_oob_syndrome;
2408                 if (!chip->ecc.write_oob)
2409                         chip->ecc.write_oob = nand_write_oob_syndrome;
2410
2411                 if (mtd->writesize >= chip->ecc.size)
2412                         break;
2413                 printk(KERN_WARNING "%d byte HW ECC not possible on "
2414                        "%d byte page size, fallback to SW ECC\n",
2415                        chip->ecc.size, mtd->writesize);
2416                 chip->ecc.mode = NAND_ECC_SOFT;
2417
2418         case NAND_ECC_SOFT:
2419                 chip->ecc.calculate = nand_calculate_ecc;
2420                 chip->ecc.correct = nand_correct_data;
2421                 chip->ecc.read_page = nand_read_page_swecc;
2422                 chip->ecc.write_page = nand_write_page_swecc;
2423                 chip->ecc.read_oob = nand_read_oob_std;
2424                 chip->ecc.write_oob = nand_write_oob_std;
2425                 chip->ecc.size = 256;
2426                 chip->ecc.bytes = 3;
2427                 break;
2428
2429         case NAND_ECC_NONE:
2430                 printk(KERN_WARNING "NAND_ECC_NONE selected by board driver. "
2431                        "This is not recommended !!\n");
2432                 chip->ecc.read_page = nand_read_page_raw;
2433                 chip->ecc.write_page = nand_write_page_raw;
2434                 chip->ecc.read_oob = nand_read_oob_std;
2435                 chip->ecc.write_oob = nand_write_oob_std;
2436                 chip->ecc.size = mtd->writesize;
2437                 chip->ecc.bytes = 0;
2438                 break;
2439
2440         default:
2441                 printk(KERN_WARNING "Invalid NAND_ECC_MODE %d\n",
2442                        chip->ecc.mode);
2443                 BUG();
2444         }
2445
2446         /*
2447          * The number of bytes available for a client to place data into
2448          * the out of band area
2449          */
2450         chip->ecc.layout->oobavail = 0;
2451         for (i = 0; chip->ecc.layout->oobfree[i].length; i++)
2452                 chip->ecc.layout->oobavail +=
2453                         chip->ecc.layout->oobfree[i].length;
2454
2455         /*
2456          * Set the number of read / write steps for one page depending on ECC
2457          * mode
2458          */
2459         chip->ecc.steps = mtd->writesize / chip->ecc.size;
2460         if(chip->ecc.steps * chip->ecc.size != mtd->writesize) {
2461                 printk(KERN_WARNING "Invalid ecc parameters\n");
2462                 BUG();
2463         }
2464         chip->ecc.total = chip->ecc.steps * chip->ecc.bytes;
2465
2466         /* Initialize state */
2467         chip->state = FL_READY;
2468
2469         /* De-select the device */
2470         chip->select_chip(mtd, -1);
2471
2472         /* Invalidate the pagebuffer reference */
2473         chip->pagebuf = -1;
2474
2475         /* Fill in remaining MTD driver data */
2476         mtd->type = MTD_NANDFLASH;
2477         mtd->flags = MTD_CAP_NANDFLASH;
2478         mtd->ecctype = MTD_ECC_SW;
2479         mtd->erase = nand_erase;
2480         mtd->point = NULL;
2481         mtd->unpoint = NULL;
2482         mtd->read = nand_read;
2483         mtd->write = nand_write;
2484         mtd->read_oob = nand_read_oob;
2485         mtd->write_oob = nand_write_oob;
2486         mtd->sync = nand_sync;
2487         mtd->lock = NULL;
2488         mtd->unlock = NULL;
2489         mtd->suspend = nand_suspend;
2490         mtd->resume = nand_resume;
2491         mtd->block_isbad = nand_block_isbad;
2492         mtd->block_markbad = nand_block_markbad;
2493
2494         /* propagate ecc.layout to mtd_info */
2495         mtd->ecclayout = chip->ecc.layout;
2496
2497         /* Check, if we should skip the bad block table scan */
2498         if (chip->options & NAND_SKIP_BBTSCAN)
2499                 return 0;
2500
2501         /* Build bad block table */
2502         return chip->scan_bbt(mtd);
2503 }
2504
2505 /* module_text_address() isn't exported, and it's mostly a pointless
2506    test if this is a module _anyway_ -- they'd have to try _really_ hard
2507    to call us from in-kernel code if the core NAND support is modular. */
2508 #ifdef MODULE
2509 #define caller_is_module() (1)
2510 #else
2511 #define caller_is_module() \
2512         module_text_address((unsigned long)__builtin_return_address(0))
2513 #endif
2514
2515 /**
2516  * nand_scan - [NAND Interface] Scan for the NAND device
2517  * @mtd:        MTD device structure
2518  * @maxchips:   Number of chips to scan for
2519  *
2520  * This fills out all the uninitialized function pointers
2521  * with the defaults.
2522  * The flash ID is read and the mtd/chip structures are
2523  * filled with the appropriate values.
2524  * The mtd->owner field must be set to the module of the caller
2525  *
2526  */
2527 int nand_scan(struct mtd_info *mtd, int maxchips)
2528 {
2529         int ret;
2530
2531         /* Many callers got this wrong, so check for it for a while... */
2532         if (!mtd->owner && caller_is_module()) {
2533                 printk(KERN_CRIT "nand_scan() called with NULL mtd->owner!\n");
2534                 BUG();
2535         }
2536
2537         ret = nand_scan_ident(mtd, maxchips);
2538         if (!ret)
2539                 ret = nand_scan_tail(mtd);
2540         return ret;
2541 }
2542
2543 /**
2544  * nand_release - [NAND Interface] Free resources held by the NAND device
2545  * @mtd:        MTD device structure
2546 */
2547 void nand_release(struct mtd_info *mtd)
2548 {
2549         struct nand_chip *chip = mtd->priv;
2550
2551 #ifdef CONFIG_MTD_PARTITIONS
2552         /* Deregister partitions */
2553         del_mtd_partitions(mtd);
2554 #endif
2555         /* Deregister the device */
2556         del_mtd_device(mtd);
2557
2558         /* Free bad block table memory */
2559         kfree(chip->bbt);
2560         if (!(chip->options & NAND_OWN_BUFFERS))
2561                 kfree(chip->buffers);
2562 }
2563
2564 EXPORT_SYMBOL_GPL(nand_scan);
2565 EXPORT_SYMBOL_GPL(nand_scan_ident);
2566 EXPORT_SYMBOL_GPL(nand_scan_tail);
2567 EXPORT_SYMBOL_GPL(nand_release);
2568
2569 static int __init nand_base_init(void)
2570 {
2571         led_trigger_register_simple("nand-disk", &nand_led_trigger);
2572         return 0;
2573 }
2574
2575 static void __exit nand_base_exit(void)
2576 {
2577         led_trigger_unregister_simple(nand_led_trigger);
2578 }
2579
2580 module_init(nand_base_init);
2581 module_exit(nand_base_exit);
2582
2583 MODULE_LICENSE("GPL");
2584 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>, Thomas Gleixner <tglx@linutronix.de>");
2585 MODULE_DESCRIPTION("Generic NAND flash driver code");