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