]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - common/cmd_nand.c
af3c6740f9ac14401b50f3167849495b37d0f0b0
[karo-tx-uboot.git] / common / cmd_nand.c
1 /*
2  * Driver for NAND support, Rick Bronson
3  * borrowed heavily from:
4  * (c) 1999 Machine Vision Holdings, Inc.
5  * (c) 1999, 2000 David Woodhouse <dwmw2@infradead.org>
6  */
7
8 #include <common.h>
9 #include <command.h>
10 #include <malloc.h>
11 #include <asm/io.h>
12 #include <watchdog.h>
13
14 #ifdef CONFIG_SHOW_BOOT_PROGRESS
15 # include <status_led.h>
16 # define SHOW_BOOT_PROGRESS(arg)        show_boot_progress(arg)
17 #else
18 # define SHOW_BOOT_PROGRESS(arg)
19 #endif
20
21 #if (CONFIG_COMMANDS & CFG_CMD_NAND)
22
23 #ifdef CONFIG_AT91RM9200DK
24 #include <asm/arch/hardware.h>
25 #endif
26
27 #include <linux/mtd/nand.h>
28 #include <linux/mtd/nand_ids.h>
29 #include <jffs2/jffs2.h>
30
31 #ifdef CONFIG_OMAP1510
32 void archflashwp(void *archdata, int wp);
33 #endif
34
35 #define ROUND_DOWN(value,boundary)      ((value) & (~((boundary)-1)))
36
37 /*
38  * Definition of the out of band configuration structure
39  */
40 struct nand_oob_config {
41         int ecc_pos[6];         /* position of ECC bytes inside oob */
42         int badblock_pos;       /* position of bad block flag inside oob -1 = inactive */
43         int eccvalid_pos;       /* position of ECC valid flag inside oob -1 = inactive */
44 } oob_config = { {0}, 0, 0};
45
46 #undef  NAND_DEBUG
47 #undef  PSYCHO_DEBUG
48
49 /* ****************** WARNING *********************
50  * When ALLOW_ERASE_BAD_DEBUG is non-zero the erase command will
51  * erase (or at least attempt to erase) blocks that are marked
52  * bad. This can be very handy if you are _sure_ that the block
53  * is OK, say because you marked a good block bad to test bad
54  * block handling and you are done testing, or if you have
55  * accidentally marked blocks bad.
56  *
57  * Erasing factory marked bad blocks is a _bad_ idea. If the
58  * erase succeeds there is no reliable way to find them again,
59  * and attempting to program or erase bad blocks can affect
60  * the data in _other_ (good) blocks.
61  */
62 #define  ALLOW_ERASE_BAD_DEBUG 0
63
64 #define CONFIG_MTD_NAND_ECC  /* enable ECC */
65 #define CONFIG_MTD_NAND_ECC_JFFS2
66
67 /* bits for nand_rw() `cmd'; or together as needed */
68 #define NANDRW_READ     0x01
69 #define NANDRW_WRITE    0x00
70 #define NANDRW_JFFS2    0x02
71 #define NANDRW_JFFS2_SKIP       0x04
72
73 /*
74  * Function Prototypes
75  */
76 static void nand_print(struct nand_chip *nand);
77 int nand_rw (struct nand_chip* nand, int cmd,
78             size_t start, size_t len,
79             size_t * retlen, u_char * buf);
80 int nand_erase(struct nand_chip* nand, size_t ofs, size_t len, int clean);
81 static int nand_read_ecc(struct nand_chip *nand, size_t start, size_t len,
82                  size_t * retlen, u_char *buf, u_char *ecc_code);
83 static int nand_write_ecc (struct nand_chip* nand, size_t to, size_t len,
84                            size_t * retlen, const u_char * buf, u_char * ecc_code);
85 static void nand_print_bad(struct nand_chip *nand);
86 static int nand_read_oob(struct nand_chip* nand, size_t ofs, size_t len,
87                  size_t * retlen, u_char * buf);
88 static int nand_write_oob(struct nand_chip* nand, size_t ofs, size_t len,
89                  size_t * retlen, const u_char * buf);
90 static int NanD_WaitReady(struct nand_chip *nand, int ale_wait);
91 #ifdef CONFIG_MTD_NAND_ECC
92 static int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
93 static void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
94 #endif
95
96 struct nand_chip nand_dev_desc[CFG_MAX_NAND_DEVICE] = {{0}};
97
98 /* Current NAND Device  */
99 static int curr_device = -1;
100
101 /* ------------------------------------------------------------------------- */
102
103 int do_nand (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
104 {
105     int rcode = 0;
106
107     switch (argc) {
108     case 0:
109     case 1:
110         printf ("Usage:\n%s\n", cmdtp->usage);
111         return 1;
112     case 2:
113         if (strcmp(argv[1],"info") == 0) {
114                 int i;
115
116                 putc ('\n');
117
118                 for (i=0; i<CFG_MAX_NAND_DEVICE; ++i) {
119                         if(nand_dev_desc[i].ChipID == NAND_ChipID_UNKNOWN)
120                                 continue; /* list only known devices */
121                         printf ("Device %d: ", i);
122                         nand_print(&nand_dev_desc[i]);
123                 }
124                 return 0;
125
126         } else if (strcmp(argv[1],"device") == 0) {
127                 if ((curr_device < 0) || (curr_device >= CFG_MAX_NAND_DEVICE)) {
128                         puts ("\nno devices available\n");
129                         return 1;
130                 }
131                 printf ("\nDevice %d: ", curr_device);
132                 nand_print(&nand_dev_desc[curr_device]);
133                 return 0;
134
135         } else if (strcmp(argv[1],"bad") == 0) {
136                 if ((curr_device < 0) || (curr_device >= CFG_MAX_NAND_DEVICE)) {
137                         puts ("\nno devices available\n");
138                         return 1;
139                 }
140                 printf ("\nDevice %d bad blocks:\n", curr_device);
141                 nand_print_bad(&nand_dev_desc[curr_device]);
142                 return 0;
143
144         }
145         printf ("Usage:\n%s\n", cmdtp->usage);
146         return 1;
147     case 3:
148         if (strcmp(argv[1],"device") == 0) {
149                 int dev = (int)simple_strtoul(argv[2], NULL, 10);
150
151                 printf ("\nDevice %d: ", dev);
152                 if (dev >= CFG_MAX_NAND_DEVICE) {
153                         puts ("unknown device\n");
154                         return 1;
155                 }
156                 nand_print(&nand_dev_desc[dev]);
157                 /*nand_print (dev);*/
158
159                 if (nand_dev_desc[dev].ChipID == NAND_ChipID_UNKNOWN) {
160                         return 1;
161                 }
162
163                 curr_device = dev;
164
165                 puts ("... is now current device\n");
166
167                 return 0;
168         }
169         else if (strcmp(argv[1],"erase") == 0 && strcmp(argv[2], "clean") == 0) {
170                 struct nand_chip* nand = &nand_dev_desc[curr_device];
171                 ulong off = 0;
172                 ulong size = nand->totlen;
173                 int ret;
174
175                 printf ("\nNAND erase: device %d offset %ld, size %ld ... ",
176                         curr_device, off, size);
177
178                 ret = nand_erase (nand, off, size, 1);
179
180                 printf("%s\n", ret ? "ERROR" : "OK");
181
182                 return ret;
183         }
184
185         printf ("Usage:\n%s\n", cmdtp->usage);
186         return 1;
187     default:
188         /* at least 4 args */
189
190         if (strncmp(argv[1], "read", 4) == 0 ||
191             strncmp(argv[1], "write", 5) == 0) {
192                 ulong addr = simple_strtoul(argv[2], NULL, 16);
193                 ulong off  = simple_strtoul(argv[3], NULL, 16);
194                 ulong size = simple_strtoul(argv[4], NULL, 16);
195                 int cmd    = (strncmp(argv[1], "read", 4) == 0) ?
196                                 NANDRW_READ : NANDRW_WRITE;
197                 int ret, total;
198                 char* cmdtail = strchr(argv[1], '.');
199
200                 if (cmdtail && !strncmp(cmdtail, ".oob", 2)) {
201                         /* read out-of-band data */
202                         if (cmd & NANDRW_READ) {
203                                 ret = nand_read_oob(nand_dev_desc + curr_device,
204                                                     off, size, &total,
205                                                     (u_char*)addr);
206                         }
207                         else {
208                                 ret = nand_write_oob(nand_dev_desc + curr_device,
209                                                      off, size, &total,
210                                                      (u_char*)addr);
211                         }
212                         return ret;
213                 }
214                 else if (cmdtail && !strncmp(cmdtail, ".jffs2", 2))
215                         cmd |= NANDRW_JFFS2;    /* skip bad blocks */
216                 else if (cmdtail && !strncmp(cmdtail, ".jffs2s", 2)) {
217                         cmd |= NANDRW_JFFS2;    /* skip bad blocks (on read too) */
218                         if (cmd & NANDRW_READ)
219                                 cmd |= NANDRW_JFFS2_SKIP;       /* skip bad blocks (on read too) */
220                 }
221 #ifdef SXNI855T
222                 /* need ".e" same as ".j" for compatibility with older units */
223                 else if (cmdtail && !strcmp(cmdtail, ".e"))
224                         cmd |= NANDRW_JFFS2;    /* skip bad blocks */
225 #endif
226 #ifdef CFG_NAND_SKIP_BAD_DOT_I
227                 /* need ".i" same as ".jffs2s" for compatibility with older units (esd) */
228                 /* ".i" for image -> read skips bad block (no 0xff) */
229                 else if (cmdtail && !strcmp(cmdtail, ".i"))
230                         cmd |= NANDRW_JFFS2;    /* skip bad blocks (on read too) */
231                         if (cmd & NANDRW_READ)
232                                 cmd |= NANDRW_JFFS2_SKIP;       /* skip bad blocks (on read too) */
233 #endif /* CFG_NAND_SKIP_BAD_DOT_I */
234                 else if (cmdtail) {
235                         printf ("Usage:\n%s\n", cmdtp->usage);
236                         return 1;
237                 }
238
239                 printf ("\nNAND %s: device %d offset %ld, size %ld ... ",
240                         (cmd & NANDRW_READ) ? "read" : "write",
241                         curr_device, off, size);
242
243                 ret = nand_rw(nand_dev_desc + curr_device, cmd, off, size,
244                              &total, (u_char*)addr);
245
246                 printf (" %d bytes %s: %s\n", total,
247                         (cmd & NANDRW_READ) ? "read" : "written",
248                         ret ? "ERROR" : "OK");
249
250                 return ret;
251         } else if (strcmp(argv[1],"erase") == 0 &&
252                    (argc == 4 || strcmp("clean", argv[2]) == 0)) {
253                 int clean = argc == 5;
254                 ulong off = simple_strtoul(argv[2 + clean], NULL, 16);
255                 ulong size = simple_strtoul(argv[3 + clean], NULL, 16);
256                 int ret;
257
258                 printf ("\nNAND erase: device %d offset %ld, size %ld ... ",
259                         curr_device, off, size);
260
261                 ret = nand_erase (nand_dev_desc + curr_device, off, size, clean);
262
263                 printf("%s\n", ret ? "ERROR" : "OK");
264
265                 return ret;
266         } else {
267                 printf ("Usage:\n%s\n", cmdtp->usage);
268                 rcode = 1;
269         }
270
271         return rcode;
272     }
273 }
274
275 U_BOOT_CMD(
276         nand,   5,      1,      do_nand,
277         "nand    - NAND sub-system\n",
278         "info  - show available NAND devices\n"
279         "nand device [dev] - show or set current device\n"
280         "nand read[.jffs2[s]]  addr off size\n"
281         "nand write[.jffs2] addr off size - read/write `size' bytes starting\n"
282         "    at offset `off' to/from memory address `addr'\n"
283         "nand erase [clean] [off size] - erase `size' bytes from\n"
284         "    offset `off' (entire device if not specified)\n"
285         "nand bad - show bad blocks\n"
286         "nand read.oob addr off size - read out-of-band data\n"
287         "nand write.oob addr off size - read out-of-band data\n"
288 );
289
290 int do_nandboot (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
291 {
292         char *boot_device = NULL;
293         char *ep;
294         int dev;
295         ulong cnt;
296         ulong addr;
297         ulong offset = 0;
298         image_header_t *hdr;
299         int rcode = 0;
300         switch (argc) {
301         case 1:
302                 addr = CFG_LOAD_ADDR;
303                 boot_device = getenv ("bootdevice");
304                 break;
305         case 2:
306                 addr = simple_strtoul(argv[1], NULL, 16);
307                 boot_device = getenv ("bootdevice");
308                 break;
309         case 3:
310                 addr = simple_strtoul(argv[1], NULL, 16);
311                 boot_device = argv[2];
312                 break;
313         case 4:
314                 addr = simple_strtoul(argv[1], NULL, 16);
315                 boot_device = argv[2];
316                 offset = simple_strtoul(argv[3], NULL, 16);
317                 break;
318         default:
319                 printf ("Usage:\n%s\n", cmdtp->usage);
320                 SHOW_BOOT_PROGRESS (-1);
321                 return 1;
322         }
323
324         if (!boot_device) {
325                 puts ("\n** No boot device **\n");
326                 SHOW_BOOT_PROGRESS (-1);
327                 return 1;
328         }
329
330         dev = simple_strtoul(boot_device, &ep, 16);
331
332         if ((dev >= CFG_MAX_NAND_DEVICE) ||
333             (nand_dev_desc[dev].ChipID == NAND_ChipID_UNKNOWN)) {
334                 printf ("\n** Device %d not available\n", dev);
335                 SHOW_BOOT_PROGRESS (-1);
336                 return 1;
337         }
338
339         printf ("\nLoading from device %d: %s at 0x%lx (offset 0x%lx)\n",
340                 dev, nand_dev_desc[dev].name, nand_dev_desc[dev].IO_ADDR,
341                 offset);
342
343         if (nand_rw (nand_dev_desc + dev, NANDRW_READ, offset,
344                     SECTORSIZE, NULL, (u_char *)addr)) {
345                 printf ("** Read error on %d\n", dev);
346                 SHOW_BOOT_PROGRESS (-1);
347                 return 1;
348         }
349
350         hdr = (image_header_t *)addr;
351
352         if (ntohl(hdr->ih_magic) == IH_MAGIC) {
353
354                 print_image_hdr (hdr);
355
356                 cnt = (ntohl(hdr->ih_size) + sizeof(image_header_t));
357                 cnt -= SECTORSIZE;
358         } else {
359                 printf ("\n** Bad Magic Number 0x%x **\n", hdr->ih_magic);
360                 SHOW_BOOT_PROGRESS (-1);
361                 return 1;
362         }
363
364         if (nand_rw (nand_dev_desc + dev, NANDRW_READ, offset + SECTORSIZE, cnt,
365                     NULL, (u_char *)(addr+SECTORSIZE))) {
366                 printf ("** Read error on %d\n", dev);
367                 SHOW_BOOT_PROGRESS (-1);
368                 return 1;
369         }
370
371         /* Loading ok, update default load address */
372
373         load_addr = addr;
374
375         /* Check if we should attempt an auto-start */
376         if (((ep = getenv("autostart")) != NULL) && (strcmp(ep,"yes") == 0)) {
377                 char *local_args[2];
378                 extern int do_bootm (cmd_tbl_t *, int, int, char *[]);
379
380                 local_args[0] = argv[0];
381                 local_args[1] = NULL;
382
383                 printf ("Automatic boot of image at addr 0x%08lx ...\n", addr);
384
385                 do_bootm (cmdtp, 0, 1, local_args);
386                 rcode = 1;
387         }
388         return rcode;
389 }
390
391 U_BOOT_CMD(
392         nboot,  4,      1,      do_nandboot,
393         "nboot   - boot from NAND device\n",
394         "loadAddr dev\n"
395 );
396
397 /* returns 0 if block containing pos is OK:
398  *              valid erase block and
399  *              not marked bad, or no bad mark position is specified
400  * returns 1 if marked bad or otherwise invalid
401  */
402 int check_block(struct nand_chip* nand, unsigned long pos)
403 {
404         int retlen;
405         uint8_t oob_data;
406         int page0 = pos & (-nand->erasesize);
407         int page1 = page0 + nand->oobblock;
408         int badpos = oob_config.badblock_pos;
409
410         if (pos >= nand->totlen)
411                 return 1;
412
413         if (badpos < 0)
414                 return 0;       /* no way to check, assume OK */
415
416         /* Note - bad block marker can be on first or second page */
417         if (nand_read_oob(nand, page0 + badpos, 1, &retlen, &oob_data) ||
418             oob_data != 0xff ||
419             nand_read_oob(nand, page1 + badpos, 1, &retlen, &oob_data) ||
420             oob_data != 0xff)
421                 return 1;
422
423         return 0;
424 }
425
426 /* print bad blocks in NAND flash */
427 static void nand_print_bad(struct nand_chip* nand)
428 {
429         unsigned long pos;
430
431         for (pos = 0; pos < nand->totlen; pos += nand->erasesize) {
432                 if (check_block(nand, pos))
433                         printf(" 0x%8.8lx\n", pos);
434         }
435         puts("\n");
436 }
437
438 /* cmd: 0: NANDRW_WRITE                 write, fail on bad block
439  *      1: NANDRW_READ                  read, fail on bad block
440  *      2: NANDRW_WRITE | NANDRW_JFFS2  write, skip bad blocks
441  *      3: NANDRW_READ | NANDRW_JFFS2   read, data all 0xff for bad blocks
442  *      7: NANDRW_READ | NANDRW_JFFS2 | NANDRW_JFFS2_SKIP read, skip bad blocks
443  */
444 int nand_rw (struct nand_chip* nand, int cmd,
445             size_t start, size_t len,
446             size_t * retlen, u_char * buf)
447 {
448         int ret = 0, n, total = 0;
449         char eccbuf[6];
450         /* eblk (once set) is the start of the erase block containing the
451          * data being processed.
452          */
453         unsigned long eblk = ~0;        /* force mismatch on first pass */
454         unsigned long erasesize = nand->erasesize;
455
456         while (len) {
457                 if ((start & (-erasesize)) != eblk) {
458                         /* have crossed into new erase block, deal with
459                          * it if it is sure marked bad.
460                          */
461                         eblk = start & (-erasesize); /* start of block */
462                         if (check_block(nand, eblk)) {
463                                 if (cmd == (NANDRW_READ | NANDRW_JFFS2)) {
464                                         while (len > 0 &&
465                                                start - eblk < erasesize) {
466                                                 *(buf++) = 0xff;
467                                                 ++start;
468                                                 ++total;
469                                                 --len;
470                                         }
471                                         continue;
472                                 }
473                                 else if (cmd == (NANDRW_READ | NANDRW_JFFS2 | NANDRW_JFFS2_SKIP)) {
474                                         start += erasesize;
475                                         continue;
476                                 }
477                                 else if (cmd == (NANDRW_WRITE | NANDRW_JFFS2)) {
478                                         /* skip bad block */
479                                         start += erasesize;
480                                         continue;
481                                 }
482                                 else {
483                                         ret = 1;
484                                         break;
485                                 }
486                         }
487                 }
488                 /* The ECC will not be calculated correctly if
489                    less than 512 is written or read */
490                 /* Is request at least 512 bytes AND it starts on a proper boundry */
491                 if((start != ROUND_DOWN(start, 0x200)) || (len < 0x200))
492                         printf("Warning block writes should be at least 512 bytes and start on a 512 byte boundry\n");
493
494                 if (cmd & NANDRW_READ)
495                         ret = nand_read_ecc(nand, start,
496                                            min(len, eblk + erasesize - start),
497                                            &n, (u_char*)buf, eccbuf);
498                 else
499                         ret = nand_write_ecc(nand, start,
500                                             min(len, eblk + erasesize - start),
501                                             &n, (u_char*)buf, eccbuf);
502
503                 if (ret)
504                         break;
505
506                 start  += n;
507                 buf   += n;
508                 total += n;
509                 len   -= n;
510         }
511         if (retlen)
512                 *retlen = total;
513
514         return ret;
515 }
516
517 static void nand_print(struct nand_chip *nand)
518 {
519         if (nand->numchips > 1) {
520                 printf("%s at 0x%lx,\n"
521                        "\t  %d chips %s, size %d MB, \n"
522                        "\t  total size %ld MB, sector size %ld kB\n",
523                        nand->name, nand->IO_ADDR, nand->numchips,
524                        nand->chips_name, 1 << (nand->chipshift - 20),
525                        nand->totlen >> 20, nand->erasesize >> 10);
526         }
527         else {
528                 printf("%s at 0x%lx (", nand->chips_name, nand->IO_ADDR);
529                 print_size(nand->totlen, ", ");
530                 print_size(nand->erasesize, " sector)\n");
531         }
532 }
533
534 /* ------------------------------------------------------------------------- */
535
536 static int NanD_WaitReady(struct nand_chip *nand, int ale_wait)
537 {
538         /* This is inline, to optimise the common case, where it's ready instantly */
539         int ret = 0;
540
541 #ifdef NAND_NO_RB       /* in config file, shorter delays currently wrap accesses */
542         if(ale_wait)
543                 NAND_WAIT_READY(nand);  /* do the worst case 25us wait */
544         else
545                 udelay(10);
546 #else   /* has functional r/b signal */
547         NAND_WAIT_READY(nand);
548 #endif
549         return ret;
550 }
551
552 /* NanD_Command: Send a flash command to the flash chip */
553
554 static inline int NanD_Command(struct nand_chip *nand, unsigned char command)
555 {
556         unsigned long nandptr = nand->IO_ADDR;
557
558         /* Assert the CLE (Command Latch Enable) line to the flash chip */
559         NAND_CTL_SETCLE(nandptr);
560
561         /* Send the command */
562         WRITE_NAND_COMMAND(command, nandptr);
563
564         /* Lower the CLE line */
565         NAND_CTL_CLRCLE(nandptr);
566
567 #ifdef NAND_NO_RB
568         if(command == NAND_CMD_RESET){
569                 u_char ret_val;
570                 NanD_Command(nand, NAND_CMD_STATUS);
571                 do{
572                         ret_val = READ_NAND(nandptr);/* wait till ready */
573                 } while((ret_val & 0x40) != 0x40);
574         }
575 #endif
576         return NanD_WaitReady(nand, 0);
577 }
578
579 /* NanD_Address: Set the current address for the flash chip */
580
581 static int NanD_Address(struct nand_chip *nand, int numbytes, unsigned long ofs)
582 {
583         unsigned long nandptr;
584         int i;
585
586         nandptr = nand->IO_ADDR;
587
588         /* Assert the ALE (Address Latch Enable) line to the flash chip */
589         NAND_CTL_SETALE(nandptr);
590
591         /* Send the address */
592         /* Devices with 256-byte page are addressed as:
593          * Column (bits 0-7), Page (bits 8-15, 16-23, 24-31)
594          * there is no device on the market with page256
595          * and more than 24 bits.
596          * Devices with 512-byte page are addressed as:
597          * Column (bits 0-7), Page (bits 9-16, 17-24, 25-31)
598          * 25-31 is sent only if the chip support it.
599          * bit 8 changes the read command to be sent
600          * (NAND_CMD_READ0 or NAND_CMD_READ1).
601          */
602
603         if (numbytes == ADDR_COLUMN || numbytes == ADDR_COLUMN_PAGE)
604                 WRITE_NAND_ADDRESS(ofs, nandptr);
605
606         ofs = ofs >> nand->page_shift;
607
608         if (numbytes == ADDR_PAGE || numbytes == ADDR_COLUMN_PAGE)
609                 for (i = 0; i < nand->pageadrlen; i++, ofs = ofs >> 8)
610                         WRITE_NAND_ADDRESS(ofs, nandptr);
611
612         /* Lower the ALE line */
613         NAND_CTL_CLRALE(nandptr);
614
615         /* Wait for the chip to respond */
616         return NanD_WaitReady(nand, 1);
617 }
618
619 /* NanD_SelectChip: Select a given flash chip within the current floor */
620
621 static inline int NanD_SelectChip(struct nand_chip *nand, int chip)
622 {
623         /* Wait for it to be ready */
624         return NanD_WaitReady(nand, 0);
625 }
626
627 /* NanD_IdentChip: Identify a given NAND chip given {floor,chip} */
628
629 static int NanD_IdentChip(struct nand_chip *nand, int floor, int chip)
630 {
631         int mfr, id, i;
632
633         NAND_ENABLE_CE(nand);  /* set pin low */
634         /* Reset the chip */
635         if (NanD_Command(nand, NAND_CMD_RESET)) {
636 #ifdef NAND_DEBUG
637                 printf("NanD_Command (reset) for %d,%d returned true\n",
638                        floor, chip);
639 #endif
640                 NAND_DISABLE_CE(nand);  /* set pin high */
641                 return 0;
642         }
643
644         /* Read the NAND chip ID: 1. Send ReadID command */
645         if (NanD_Command(nand, NAND_CMD_READID)) {
646 #ifdef NAND_DEBUG
647                 printf("NanD_Command (ReadID) for %d,%d returned true\n",
648                        floor, chip);
649 #endif
650                 NAND_DISABLE_CE(nand);  /* set pin high */
651                 return 0;
652         }
653
654         /* Read the NAND chip ID: 2. Send address byte zero */
655         NanD_Address(nand, ADDR_COLUMN, 0);
656
657         /* Read the manufacturer and device id codes from the device */
658
659         mfr = READ_NAND(nand->IO_ADDR);
660
661         id = READ_NAND(nand->IO_ADDR);
662
663         NAND_DISABLE_CE(nand);  /* set pin high */
664         /* No response - return failure */
665         if (mfr == 0xff || mfr == 0) {
666 #ifdef NAND_DEBUG
667                 printf("NanD_Command (ReadID) got %d %d\n", mfr, id);
668 #endif
669                 return 0;
670         }
671
672         /* Check it's the same as the first chip we identified.
673          * M-Systems say that any given nand_chip device should only
674          * contain _one_ type of flash part, although that's not a
675          * hardware restriction. */
676         if (nand->mfr) {
677                 if (nand->mfr == mfr && nand->id == id)
678                         return 1;       /* This is another the same the first */
679                 else
680                         printf("Flash chip at floor %d, chip %d is different:\n",
681                                floor, chip);
682         }
683
684         /* Print and store the manufacturer and ID codes. */
685         for (i = 0; nand_flash_ids[i].name != NULL; i++) {
686                 if (mfr == nand_flash_ids[i].manufacture_id &&
687                     id == nand_flash_ids[i].model_id) {
688 #ifdef NAND_DEBUG
689                         printf("Flash chip found:\n\t Manufacturer ID: 0x%2.2X, "
690                                "Chip ID: 0x%2.2X (%s)\n", mfr, id,
691                                nand_flash_ids[i].name);
692 #endif
693                         if (!nand->mfr) {
694                                 nand->mfr = mfr;
695                                 nand->id = id;
696                                 nand->chipshift =
697                                     nand_flash_ids[i].chipshift;
698                                 nand->page256 = nand_flash_ids[i].page256;
699                                 nand->eccsize = 256;
700                                 if (nand->page256) {
701                                         nand->oobblock = 256;
702                                         nand->oobsize = 8;
703                                         nand->page_shift = 8;
704                                 } else {
705                                         nand->oobblock = 512;
706                                         nand->oobsize = 16;
707                                         nand->page_shift = 9;
708                                 }
709                                 nand->pageadrlen =
710                                     nand_flash_ids[i].pageadrlen;
711                                 nand->erasesize =
712                                     nand_flash_ids[i].erasesize;
713                                 nand->chips_name =
714                                     nand_flash_ids[i].name;
715                                 return 1;
716                         }
717                         return 0;
718                 }
719         }
720
721
722 #ifdef NAND_DEBUG
723         /* We haven't fully identified the chip. Print as much as we know. */
724         printf("Unknown flash chip found: %2.2X %2.2X\n",
725                id, mfr);
726 #endif
727
728         return 0;
729 }
730
731 /* NanD_ScanChips: Find all NAND chips present in a nand_chip, and identify them */
732
733 static void NanD_ScanChips(struct nand_chip *nand)
734 {
735         int floor, chip;
736         int numchips[NAND_MAX_FLOORS];
737         int maxchips = NAND_MAX_CHIPS;
738         int ret = 1;
739
740         nand->numchips = 0;
741         nand->mfr = 0;
742         nand->id = 0;
743
744
745         /* For each floor, find the number of valid chips it contains */
746         for (floor = 0; floor < NAND_MAX_FLOORS; floor++) {
747                 ret = 1;
748                 numchips[floor] = 0;
749                 for (chip = 0; chip < maxchips && ret != 0; chip++) {
750
751                         ret = NanD_IdentChip(nand, floor, chip);
752                         if (ret) {
753                                 numchips[floor]++;
754                                 nand->numchips++;
755                         }
756                 }
757         }
758
759         /* If there are none at all that we recognise, bail */
760         if (!nand->numchips) {
761 #ifdef NAND_DEBUG
762                 puts ("No NAND flash chips recognised.\n");
763 #endif
764                 return;
765         }
766
767         /* Allocate an array to hold the information for each chip */
768         nand->chips = malloc(sizeof(struct Nand) * nand->numchips);
769         if (!nand->chips) {
770                 puts ("No memory for allocating chip info structures\n");
771                 return;
772         }
773
774         ret = 0;
775
776         /* Fill out the chip array with {floor, chipno} for each
777          * detected chip in the device. */
778         for (floor = 0; floor < NAND_MAX_FLOORS; floor++) {
779                 for (chip = 0; chip < numchips[floor]; chip++) {
780                         nand->chips[ret].floor = floor;
781                         nand->chips[ret].chip = chip;
782                         nand->chips[ret].curadr = 0;
783                         nand->chips[ret].curmode = 0x50;
784                         ret++;
785                 }
786         }
787
788         /* Calculate and print the total size of the device */
789         nand->totlen = nand->numchips * (1 << nand->chipshift);
790
791 #ifdef NAND_DEBUG
792         printf("%d flash chips found. Total nand_chip size: %ld MB\n",
793                nand->numchips, nand->totlen >> 20);
794 #endif
795 }
796
797 /* we need to be fast here, 1 us per read translates to 1 second per meg */
798 static void NanD_ReadBuf(struct nand_chip *nand, u_char *data_buf, int cntr)
799 {
800         unsigned long nandptr = nand->IO_ADDR;
801
802         while (cntr >= 16) {
803                 *data_buf++ = READ_NAND(nandptr);
804                 *data_buf++ = READ_NAND(nandptr);
805                 *data_buf++ = READ_NAND(nandptr);
806                 *data_buf++ = READ_NAND(nandptr);
807                 *data_buf++ = READ_NAND(nandptr);
808                 *data_buf++ = READ_NAND(nandptr);
809                 *data_buf++ = READ_NAND(nandptr);
810                 *data_buf++ = READ_NAND(nandptr);
811                 *data_buf++ = READ_NAND(nandptr);
812                 *data_buf++ = READ_NAND(nandptr);
813                 *data_buf++ = READ_NAND(nandptr);
814                 *data_buf++ = READ_NAND(nandptr);
815                 *data_buf++ = READ_NAND(nandptr);
816                 *data_buf++ = READ_NAND(nandptr);
817                 *data_buf++ = READ_NAND(nandptr);
818                 *data_buf++ = READ_NAND(nandptr);
819                 cntr -= 16;
820         }
821
822         while (cntr > 0) {
823                 *data_buf++ = READ_NAND(nandptr);
824                 cntr--;
825         }
826 }
827
828 /*
829  * NAND read with ECC
830  */
831 static int nand_read_ecc(struct nand_chip *nand, size_t start, size_t len,
832                  size_t * retlen, u_char *buf, u_char *ecc_code)
833 {
834         int col, page;
835         int ecc_status = 0;
836 #ifdef CONFIG_MTD_NAND_ECC
837         int j;
838         int ecc_failed = 0;
839         u_char *data_poi;
840         u_char ecc_calc[6];
841 #endif
842
843         /* Do not allow reads past end of device */
844         if ((start + len) > nand->totlen) {
845                 printf ("%s: Attempt read beyond end of device %x %x %x\n", __FUNCTION__, (uint) start, (uint) len, (uint) nand->totlen);
846                 *retlen = 0;
847                 return -1;
848         }
849
850         /* First we calculate the starting page */
851         /*page = shr(start, nand->page_shift);*/
852         page = start >> nand->page_shift;
853
854         /* Get raw starting column */
855         col = start & (nand->oobblock - 1);
856
857         /* Initialize return value */
858         *retlen = 0;
859
860         /* Select the NAND device */
861         NAND_ENABLE_CE(nand);  /* set pin low */
862
863         /* Loop until all data read */
864         while (*retlen < len) {
865
866
867 #ifdef CONFIG_MTD_NAND_ECC
868
869                 /* Do we have this page in cache ? */
870                 if (nand->cache_page == page)
871                         goto readdata;
872                 /* Send the read command */
873                 NanD_Command(nand, NAND_CMD_READ0);
874                 NanD_Address(nand, ADDR_COLUMN_PAGE, (page << nand->page_shift) + col);
875                 /* Read in a page + oob data */
876                 NanD_ReadBuf(nand, nand->data_buf, nand->oobblock + nand->oobsize);
877
878                 /* copy data into cache, for read out of cache and if ecc fails */
879                 if (nand->data_cache)
880                         memcpy (nand->data_cache, nand->data_buf, nand->oobblock + nand->oobsize);
881
882                 /* Pick the ECC bytes out of the oob data */
883                 for (j = 0; j < 6; j++)
884                         ecc_code[j] = nand->data_buf[(nand->oobblock + oob_config.ecc_pos[j])];
885
886                 /* Calculate the ECC and verify it */
887                 /* If block was not written with ECC, skip ECC */
888                 if (oob_config.eccvalid_pos != -1 &&
889                     (nand->data_buf[nand->oobblock + oob_config.eccvalid_pos] & 0x0f) != 0x0f) {
890
891                         nand_calculate_ecc (&nand->data_buf[0], &ecc_calc[0]);
892                         switch (nand_correct_data (&nand->data_buf[0], &ecc_code[0], &ecc_calc[0])) {
893                         case -1:
894                                 printf ("%s: Failed ECC read, page 0x%08x\n", __FUNCTION__, page);
895                                 ecc_failed++;
896                                 break;
897                         case 1:
898                         case 2: /* transfer ECC corrected data to cache */
899                                 if (nand->data_cache)
900                                         memcpy (nand->data_cache, nand->data_buf, 256);
901                                 break;
902                         }
903                 }
904
905                 if (oob_config.eccvalid_pos != -1 &&
906                     nand->oobblock == 512 && (nand->data_buf[nand->oobblock + oob_config.eccvalid_pos] & 0xf0) != 0xf0) {
907
908                         nand_calculate_ecc (&nand->data_buf[256], &ecc_calc[3]);
909                         switch (nand_correct_data (&nand->data_buf[256], &ecc_code[3], &ecc_calc[3])) {
910                         case -1:
911                                 printf ("%s: Failed ECC read, page 0x%08x\n", __FUNCTION__, page);
912                                 ecc_failed++;
913                                 break;
914                         case 1:
915                         case 2: /* transfer ECC corrected data to cache */
916                                 if (nand->data_cache)
917                                         memcpy (&nand->data_cache[256], &nand->data_buf[256], 256);
918                                 break;
919                         }
920                 }
921 readdata:
922                 /* Read the data from ECC data buffer into return buffer */
923                 data_poi = (nand->data_cache) ? nand->data_cache : nand->data_buf;
924                 data_poi += col;
925                 if ((*retlen + (nand->oobblock - col)) >= len) {
926                         memcpy (buf + *retlen, data_poi, len - *retlen);
927                         *retlen = len;
928                 } else {
929                         memcpy (buf + *retlen, data_poi,  nand->oobblock - col);
930                         *retlen += nand->oobblock - col;
931                 }
932                 /* Set cache page address, invalidate, if ecc_failed */
933                 nand->cache_page = (nand->data_cache && !ecc_failed) ? page : -1;
934
935                 ecc_status += ecc_failed;
936                 ecc_failed = 0;
937
938 #else
939                 /* Send the read command */
940                 NanD_Command(nand, NAND_CMD_READ0);
941                 NanD_Address(nand, ADDR_COLUMN_PAGE, (page << nand->page_shift) + col);
942                 /* Read the data directly into the return buffer */
943                 if ((*retlen + (nand->oobblock - col)) >= len) {
944                         NanD_ReadBuf(nand, buf + *retlen, len - *retlen);
945                         *retlen = len;
946                         /* We're done */
947                         continue;
948                 } else {
949                         NanD_ReadBuf(nand, buf + *retlen, nand->oobblock - col);
950                         *retlen += nand->oobblock - col;
951                         }
952 #endif
953                 /* For subsequent reads align to page boundary. */
954                 col = 0;
955                 /* Increment page address */
956                 page++;
957         }
958
959         /* De-select the NAND device */
960         NAND_DISABLE_CE(nand);  /* set pin high */
961
962         /*
963          * Return success, if no ECC failures, else -EIO
964          * fs driver will take care of that, because
965          * retlen == desired len and result == -EIO
966          */
967         return ecc_status ? -1 : 0;
968 }
969
970 /*
971  *      Nand_page_program function is used for write and writev !
972  */
973 static int nand_write_page (struct nand_chip *nand,
974                             int page, int col, int last, u_char * ecc_code)
975 {
976
977         int i;
978         unsigned long nandptr = nand->IO_ADDR;
979 #ifdef CONFIG_MTD_NAND_ECC
980 #ifdef CONFIG_MTD_NAND_VERIFY_WRITE
981         int ecc_bytes = (nand->oobblock == 512) ? 6 : 3;
982 #endif
983 #endif
984         /* pad oob area */
985         for (i = nand->oobblock; i < nand->oobblock + nand->oobsize; i++)
986                 nand->data_buf[i] = 0xff;
987
988 #ifdef CONFIG_MTD_NAND_ECC
989         /* Zero out the ECC array */
990         for (i = 0; i < 6; i++)
991                 ecc_code[i] = 0x00;
992
993         /* Read back previous written data, if col > 0 */
994         if (col) {
995                 NanD_Command(nand, NAND_CMD_READ0);
996                 NanD_Address(nand, ADDR_COLUMN_PAGE, (page << nand->page_shift) + col);
997                 for (i = 0; i < col; i++)
998                         nand->data_buf[i] = READ_NAND (nandptr);
999         }
1000
1001         /* Calculate and write the ECC if we have enough data */
1002         if ((col < nand->eccsize) && (last >= nand->eccsize)) {
1003                 nand_calculate_ecc (&nand->data_buf[0], &(ecc_code[0]));
1004                 for (i = 0; i < 3; i++)
1005                         nand->data_buf[(nand->oobblock + oob_config.ecc_pos[i])] = ecc_code[i];
1006                 if (oob_config.eccvalid_pos != -1)
1007                         nand->data_buf[nand->oobblock + oob_config.eccvalid_pos] = 0xf0;
1008         }
1009
1010         /* Calculate and write the second ECC if we have enough data */
1011         if ((nand->oobblock == 512) && (last == nand->oobblock)) {
1012                 nand_calculate_ecc (&nand->data_buf[256], &(ecc_code[3]));
1013                 for (i = 3; i < 6; i++)
1014                         nand->data_buf[(nand->oobblock + oob_config.ecc_pos[i])] = ecc_code[i];
1015                 if (oob_config.eccvalid_pos != -1)
1016                         nand->data_buf[nand->oobblock + oob_config.eccvalid_pos] &= 0x0f;
1017         }
1018 #endif
1019         /* Prepad for partial page programming !!! */
1020         for (i = 0; i < col; i++)
1021                 nand->data_buf[i] = 0xff;
1022
1023         /* Postpad for partial page programming !!! oob is already padded */
1024         for (i = last; i < nand->oobblock; i++)
1025                 nand->data_buf[i] = 0xff;
1026
1027         /* Send command to begin auto page programming */
1028         NanD_Command(nand, NAND_CMD_READ0);
1029         NanD_Command(nand, NAND_CMD_SEQIN);
1030         NanD_Address(nand, ADDR_COLUMN_PAGE, (page << nand->page_shift) + col);
1031
1032         /* Write out complete page of data */
1033         for (i = 0; i < (nand->oobblock + nand->oobsize); i++)
1034                 WRITE_NAND(nand->data_buf[i], nand->IO_ADDR);
1035
1036         /* Send command to actually program the data */
1037         NanD_Command(nand, NAND_CMD_PAGEPROG);
1038         NanD_Command(nand, NAND_CMD_STATUS);
1039 #ifdef NAND_NO_RB
1040         { u_char ret_val;
1041
1042           do{
1043                 ret_val = READ_NAND(nandptr);   /* wait till ready */
1044           } while((ret_val & 0x40) != 0x40);
1045         }
1046 #endif
1047         /* See if device thinks it succeeded */
1048         if (READ_NAND(nand->IO_ADDR) & 0x01) {
1049                 printf ("%s: Failed write, page 0x%08x, ", __FUNCTION__, page);
1050                 return -1;
1051         }
1052
1053 #ifdef CONFIG_MTD_NAND_VERIFY_WRITE
1054         /*
1055          * The NAND device assumes that it is always writing to
1056          * a cleanly erased page. Hence, it performs its internal
1057          * write verification only on bits that transitioned from
1058          * 1 to 0. The device does NOT verify the whole page on a
1059          * byte by byte basis. It is possible that the page was
1060          * not completely erased or the page is becoming unusable
1061          * due to wear. The read with ECC would catch the error
1062          * later when the ECC page check fails, but we would rather
1063          * catch it early in the page write stage. Better to write
1064          * no data than invalid data.
1065          */
1066
1067         /* Send command to read back the page */
1068         if (col < nand->eccsize)
1069                 NanD_Command(nand, NAND_CMD_READ0);
1070         else
1071                 NanD_Command(nand, NAND_CMD_READ1);
1072         NanD_Address(nand, ADDR_COLUMN_PAGE, (page << nand->page_shift) + col);
1073
1074         /* Loop through and verify the data */
1075         for (i = col; i < last; i++) {
1076                 if (nand->data_buf[i] != readb (nand->IO_ADDR)) {
1077                         printf ("%s: Failed write verify, page 0x%08x ", __FUNCTION__, page);
1078                         return -1;
1079                 }
1080         }
1081
1082 #ifdef CONFIG_MTD_NAND_ECC
1083         /*
1084          * We also want to check that the ECC bytes wrote
1085          * correctly for the same reasons stated above.
1086          */
1087         NanD_Command(nand, NAND_CMD_READOOB);
1088         NanD_Address(nand, ADDR_COLUMN_PAGE, (page << nand->page_shift) + col);
1089         for (i = 0; i < nand->oobsize; i++)
1090                 nand->data_buf[i] = readb (nand->IO_ADDR);
1091         for (i = 0; i < ecc_bytes; i++) {
1092                 if ((nand->data_buf[(oob_config.ecc_pos[i])] != ecc_code[i]) && ecc_code[i]) {
1093                         printf ("%s: Failed ECC write "
1094                                "verify, page 0x%08x, " "%6i bytes were succesful\n", __FUNCTION__, page, i);
1095                         return -1;
1096                 }
1097         }
1098 #endif
1099 #endif
1100         return 0;
1101 }
1102
1103 static int nand_write_ecc (struct nand_chip* nand, size_t to, size_t len,
1104                            size_t * retlen, const u_char * buf, u_char * ecc_code)
1105 {
1106         int i, page, col, cnt, ret = 0;
1107
1108         /* Do not allow write past end of device */
1109         if ((to + len) > nand->totlen) {
1110                 printf ("%s: Attempt to write past end of page\n", __FUNCTION__);
1111                 return -1;
1112         }
1113
1114         /* Shift to get page */
1115         page = ((int) to) >> nand->page_shift;
1116
1117         /* Get the starting column */
1118         col = to & (nand->oobblock - 1);
1119
1120         /* Initialize return length value */
1121         *retlen = 0;
1122
1123         /* Select the NAND device */
1124 #ifdef CONFIG_OMAP1510
1125         archflashwp(0,0);
1126 #endif
1127         NAND_ENABLE_CE(nand);  /* set pin low */
1128
1129         /* Check the WP bit */
1130         NanD_Command(nand, NAND_CMD_STATUS);
1131         if (!(READ_NAND(nand->IO_ADDR) & 0x80)) {
1132                 printf ("%s: Device is write protected!!!\n", __FUNCTION__);
1133                 ret = -1;
1134                 goto out;
1135         }
1136
1137         /* Loop until all data is written */
1138         while (*retlen < len) {
1139                 /* Invalidate cache, if we write to this page */
1140                 if (nand->cache_page == page)
1141                         nand->cache_page = -1;
1142
1143                 /* Write data into buffer */
1144                 if ((col + len) >= nand->oobblock)
1145                         for (i = col, cnt = 0; i < nand->oobblock; i++, cnt++)
1146                                 nand->data_buf[i] = buf[(*retlen + cnt)];
1147                 else
1148                         for (i = col, cnt = 0; cnt < (len - *retlen); i++, cnt++)
1149                                 nand->data_buf[i] = buf[(*retlen + cnt)];
1150                 /* We use the same function for write and writev !) */
1151                 ret = nand_write_page (nand, page, col, i, ecc_code);
1152                 if (ret)
1153                         goto out;
1154
1155                 /* Next data start at page boundary */
1156                 col = 0;
1157
1158                 /* Update written bytes count */
1159                 *retlen += cnt;
1160
1161                 /* Increment page address */
1162                 page++;
1163         }
1164
1165         /* Return happy */
1166         *retlen = len;
1167
1168 out:
1169         /* De-select the NAND device */
1170         NAND_DISABLE_CE(nand);  /* set pin high */
1171 #ifdef CONFIG_OMAP1510
1172         archflashwp(0,1);
1173 #endif
1174         return ret;
1175 }
1176
1177 /* read from the 16 bytes of oob data that correspond to a 512 byte
1178  * page or 2 256-byte pages.
1179  */
1180 static int nand_read_oob(struct nand_chip* nand, size_t ofs, size_t len,
1181                          size_t * retlen, u_char * buf)
1182 {
1183         int len256 = 0;
1184         struct Nand *mychip;
1185         int ret = 0;
1186
1187         mychip = &nand->chips[ofs >> nand->chipshift];
1188
1189         /* update address for 2M x 8bit devices. OOB starts on the second */
1190         /* page to maintain compatibility with nand_read_ecc. */
1191         if (nand->page256) {
1192                 if (!(ofs & 0x8))
1193                         ofs += 0x100;
1194                 else
1195                         ofs -= 0x8;
1196         }
1197
1198         NAND_ENABLE_CE(nand);  /* set pin low */
1199         NanD_Command(nand, NAND_CMD_READOOB);
1200         NanD_Address(nand, ADDR_COLUMN_PAGE, ofs);
1201
1202         /* treat crossing 8-byte OOB data for 2M x 8bit devices */
1203         /* Note: datasheet says it should automaticaly wrap to the */
1204         /*       next OOB block, but it didn't work here. mf.      */
1205         if (nand->page256 && ofs + len > (ofs | 0x7) + 1) {
1206                 len256 = (ofs | 0x7) + 1 - ofs;
1207                 NanD_ReadBuf(nand, buf, len256);
1208
1209                 NanD_Command(nand, NAND_CMD_READOOB);
1210                 NanD_Address(nand, ADDR_COLUMN_PAGE, ofs & (~0x1ff));
1211         }
1212
1213         NanD_ReadBuf(nand, &buf[len256], len - len256);
1214
1215         *retlen = len;
1216         /* Reading the full OOB data drops us off of the end of the page,
1217          * causing the flash device to go into busy mode, so we need
1218          * to wait until ready 11.4.1 and Toshiba TC58256FT nands */
1219
1220         ret = NanD_WaitReady(nand, 1);
1221         NAND_DISABLE_CE(nand);  /* set pin high */
1222
1223         return ret;
1224
1225 }
1226
1227 /* write to the 16 bytes of oob data that correspond to a 512 byte
1228  * page or 2 256-byte pages.
1229  */
1230 static int nand_write_oob(struct nand_chip* nand, size_t ofs, size_t len,
1231                   size_t * retlen, const u_char * buf)
1232 {
1233         int len256 = 0;
1234         int i;
1235         unsigned long nandptr = nand->IO_ADDR;
1236
1237 #ifdef PSYCHO_DEBUG
1238         printf("nand_write_oob(%lx, %d): %2.2X %2.2X %2.2X %2.2X ... %2.2X %2.2X .. %2.2X %2.2X\n",
1239                (long)ofs, len, buf[0], buf[1], buf[2], buf[3],
1240                buf[8], buf[9], buf[14],buf[15]);
1241 #endif
1242
1243         NAND_ENABLE_CE(nand);  /* set pin low to enable chip */
1244
1245         /* Reset the chip */
1246         NanD_Command(nand, NAND_CMD_RESET);
1247
1248         /* issue the Read2 command to set the pointer to the Spare Data Area. */
1249         NanD_Command(nand, NAND_CMD_READOOB);
1250         NanD_Address(nand, ADDR_COLUMN_PAGE, ofs);
1251
1252         /* update address for 2M x 8bit devices. OOB starts on the second */
1253         /* page to maintain compatibility with nand_read_ecc. */
1254         if (nand->page256) {
1255                 if (!(ofs & 0x8))
1256                         ofs += 0x100;
1257                 else
1258                         ofs -= 0x8;
1259         }
1260
1261         /* issue the Serial Data In command to initial the Page Program process */
1262         NanD_Command(nand, NAND_CMD_SEQIN);
1263         NanD_Address(nand, ADDR_COLUMN_PAGE, ofs);
1264
1265         /* treat crossing 8-byte OOB data for 2M x 8bit devices */
1266         /* Note: datasheet says it should automaticaly wrap to the */
1267         /*       next OOB block, but it didn't work here. mf.      */
1268         if (nand->page256 && ofs + len > (ofs | 0x7) + 1) {
1269                 len256 = (ofs | 0x7) + 1 - ofs;
1270                 for (i = 0; i < len256; i++)
1271                         WRITE_NAND(buf[i], nandptr);
1272
1273                 NanD_Command(nand, NAND_CMD_PAGEPROG);
1274                 NanD_Command(nand, NAND_CMD_STATUS);
1275 #ifdef NAND_NO_RB
1276                 { u_char ret_val;
1277                   do{
1278                         ret_val = READ_NAND(nandptr); /* wait till ready */
1279                   }while((ret_val & 0x40) != 0x40);
1280                 }
1281 #endif
1282                 if (READ_NAND(nandptr) & 1) {
1283                         puts ("Error programming oob data\n");
1284                         /* There was an error */
1285                         NAND_DISABLE_CE(nand);  /* set pin high */
1286                         *retlen = 0;
1287                         return -1;
1288                 }
1289                 NanD_Command(nand, NAND_CMD_SEQIN);
1290                 NanD_Address(nand, ADDR_COLUMN_PAGE, ofs & (~0x1ff));
1291         }
1292
1293         for (i = len256; i < len; i++)
1294                 WRITE_NAND(buf[i], nandptr);
1295
1296         NanD_Command(nand, NAND_CMD_PAGEPROG);
1297         NanD_Command(nand, NAND_CMD_STATUS);
1298 #ifdef NAND_NO_RB
1299         { u_char ret_val;
1300           do{
1301                 ret_val = READ_NAND(nandptr); /* wait till ready */
1302           } while((ret_val & 0x40) != 0x40);
1303         }
1304 #endif
1305         if (READ_NAND(nandptr) & 1) {
1306                 puts ("Error programming oob data\n");
1307                 /* There was an error */
1308                 NAND_DISABLE_CE(nand);  /* set pin high */
1309                 *retlen = 0;
1310                 return -1;
1311         }
1312
1313         NAND_DISABLE_CE(nand);  /* set pin high */
1314         *retlen = len;
1315         return 0;
1316
1317 }
1318
1319 int nand_erase(struct nand_chip* nand, size_t ofs, size_t len, int clean)
1320 {
1321         /* This is defined as a structure so it will work on any system
1322          * using native endian jffs2 (the default).
1323          */
1324         static struct jffs2_unknown_node clean_marker = {
1325                 JFFS2_MAGIC_BITMASK,
1326                 JFFS2_NODETYPE_CLEANMARKER,
1327                 8               /* 8 bytes in this node */
1328         };
1329         unsigned long nandptr;
1330         struct Nand *mychip;
1331         int ret = 0;
1332
1333         if (ofs & (nand->erasesize-1) || len & (nand->erasesize-1)) {
1334                 printf ("Offset and size must be sector aligned, erasesize = %d\n",
1335                         (int) nand->erasesize);
1336                 return -1;
1337         }
1338
1339         nandptr = nand->IO_ADDR;
1340
1341         /* Select the NAND device */
1342 #ifdef CONFIG_OMAP1510
1343         archflashwp(0,0);
1344 #endif
1345     NAND_ENABLE_CE(nand);  /* set pin low */
1346
1347         /* Check the WP bit */
1348         NanD_Command(nand, NAND_CMD_STATUS);
1349         if (!(READ_NAND(nand->IO_ADDR) & 0x80)) {
1350                 printf ("nand_write_ecc: Device is write protected!!!\n");
1351                 ret = -1;
1352                 goto out;
1353         }
1354
1355         /* Check the WP bit */
1356         NanD_Command(nand, NAND_CMD_STATUS);
1357         if (!(READ_NAND(nand->IO_ADDR) & 0x80)) {
1358                 printf ("%s: Device is write protected!!!\n", __FUNCTION__);
1359                 ret = -1;
1360                 goto out;
1361         }
1362
1363         /* FIXME: Do nand in the background. Use timers or schedule_task() */
1364         while(len) {
1365                 /*mychip = &nand->chips[shr(ofs, nand->chipshift)];*/
1366                 mychip = &nand->chips[ofs >> nand->chipshift];
1367
1368                 /* always check for bad block first, genuine bad blocks
1369                  * should _never_  be erased.
1370                  */
1371                 if (ALLOW_ERASE_BAD_DEBUG || !check_block(nand, ofs)) {
1372                         /* Select the NAND device */
1373                         NAND_ENABLE_CE(nand);  /* set pin low */
1374
1375                         NanD_Command(nand, NAND_CMD_ERASE1);
1376                         NanD_Address(nand, ADDR_PAGE, ofs);
1377                         NanD_Command(nand, NAND_CMD_ERASE2);
1378
1379                         NanD_Command(nand, NAND_CMD_STATUS);
1380
1381 #ifdef NAND_NO_RB
1382                         { u_char ret_val;
1383                           do{
1384                                 ret_val = READ_NAND(nandptr); /* wait till ready */
1385                           } while((ret_val & 0x40) != 0x40);
1386                         }
1387 #endif
1388                         if (READ_NAND(nandptr) & 1) {
1389                                 printf ("%s: Error erasing at 0x%lx\n",
1390                                         __FUNCTION__, (long)ofs);
1391                                 /* There was an error */
1392                                 ret = -1;
1393                                 goto out;
1394                         }
1395                         if (clean) {
1396                                 int n;  /* return value not used */
1397                                 int p, l;
1398
1399                                 /* clean marker position and size depend
1400                                  * on the page size, since 256 byte pages
1401                                  * only have 8 bytes of oob data
1402                                  */
1403                                 if (nand->page256) {
1404                                         p = NAND_JFFS2_OOB8_FSDAPOS;
1405                                         l = NAND_JFFS2_OOB8_FSDALEN;
1406                                 }
1407                                 else {
1408                                         p = NAND_JFFS2_OOB16_FSDAPOS;
1409                                         l = NAND_JFFS2_OOB16_FSDALEN;
1410                                 }
1411
1412                                 ret = nand_write_oob(nand, ofs + p, l, &n,
1413                                                      (u_char *)&clean_marker);
1414                                 /* quit here if write failed */
1415                                 if (ret)
1416                                         goto out;
1417                         }
1418                 }
1419                 ofs += nand->erasesize;
1420                 len -= nand->erasesize;
1421         }
1422
1423 out:
1424         /* De-select the NAND device */
1425         NAND_DISABLE_CE(nand);  /* set pin high */
1426 #ifdef CONFIG_OMAP1510
1427         archflashwp(0,1);
1428 #endif
1429         return ret;
1430 }
1431
1432 static inline int nandcheck(unsigned long potential, unsigned long physadr)
1433 {
1434         return 0;
1435 }
1436
1437 unsigned long nand_probe(unsigned long physadr)
1438 {
1439         struct nand_chip *nand = NULL;
1440         int i = 0, ChipID = 1;
1441
1442 #ifdef CONFIG_MTD_NAND_ECC_JFFS2
1443         oob_config.ecc_pos[0] = NAND_JFFS2_OOB_ECCPOS0;
1444         oob_config.ecc_pos[1] = NAND_JFFS2_OOB_ECCPOS1;
1445         oob_config.ecc_pos[2] = NAND_JFFS2_OOB_ECCPOS2;
1446         oob_config.ecc_pos[3] = NAND_JFFS2_OOB_ECCPOS3;
1447         oob_config.ecc_pos[4] = NAND_JFFS2_OOB_ECCPOS4;
1448         oob_config.ecc_pos[5] = NAND_JFFS2_OOB_ECCPOS5;
1449         oob_config.eccvalid_pos = 4;
1450 #else
1451         oob_config.ecc_pos[0] = NAND_NOOB_ECCPOS0;
1452         oob_config.ecc_pos[1] = NAND_NOOB_ECCPOS1;
1453         oob_config.ecc_pos[2] = NAND_NOOB_ECCPOS2;
1454         oob_config.ecc_pos[3] = NAND_NOOB_ECCPOS3;
1455         oob_config.ecc_pos[4] = NAND_NOOB_ECCPOS4;
1456         oob_config.ecc_pos[5] = NAND_NOOB_ECCPOS5;
1457         oob_config.eccvalid_pos = NAND_NOOB_ECCVPOS;
1458 #endif
1459         oob_config.badblock_pos = 5;
1460
1461         for (i=0; i<CFG_MAX_NAND_DEVICE; i++) {
1462                 if (nand_dev_desc[i].ChipID == NAND_ChipID_UNKNOWN) {
1463                         nand = &nand_dev_desc[i];
1464                         break;
1465                 }
1466         }
1467         if (!nand)
1468                 return (0);
1469
1470         memset((char *)nand, 0, sizeof(struct nand_chip));
1471
1472         nand->IO_ADDR = physadr;
1473         nand->cache_page = -1;  /* init the cache page */
1474         NanD_ScanChips(nand);
1475
1476         if (nand->totlen == 0) {
1477                 /* no chips found, clean up and quit */
1478                 memset((char *)nand, 0, sizeof(struct nand_chip));
1479                 nand->ChipID = NAND_ChipID_UNKNOWN;
1480                 return (0);
1481         }
1482
1483         nand->ChipID = ChipID;
1484         if (curr_device == -1)
1485                 curr_device = i;
1486
1487         nand->data_buf = malloc (nand->oobblock + nand->oobsize);
1488         if (!nand->data_buf) {
1489                 puts ("Cannot allocate memory for data structures.\n");
1490                 return (0);
1491         }
1492
1493         return (nand->totlen);
1494 }
1495
1496 #ifdef CONFIG_MTD_NAND_ECC
1497 /*
1498  * Pre-calculated 256-way 1 byte column parity
1499  */
1500 static const u_char nand_ecc_precalc_table[] = {
1501         0x00, 0x55, 0x56, 0x03, 0x59, 0x0c, 0x0f, 0x5a, 0x5a, 0x0f, 0x0c, 0x59, 0x03, 0x56, 0x55, 0x00,
1502         0x65, 0x30, 0x33, 0x66, 0x3c, 0x69, 0x6a, 0x3f, 0x3f, 0x6a, 0x69, 0x3c, 0x66, 0x33, 0x30, 0x65,
1503         0x66, 0x33, 0x30, 0x65, 0x3f, 0x6a, 0x69, 0x3c, 0x3c, 0x69, 0x6a, 0x3f, 0x65, 0x30, 0x33, 0x66,
1504         0x03, 0x56, 0x55, 0x00, 0x5a, 0x0f, 0x0c, 0x59, 0x59, 0x0c, 0x0f, 0x5a, 0x00, 0x55, 0x56, 0x03,
1505         0x69, 0x3c, 0x3f, 0x6a, 0x30, 0x65, 0x66, 0x33, 0x33, 0x66, 0x65, 0x30, 0x6a, 0x3f, 0x3c, 0x69,
1506         0x0c, 0x59, 0x5a, 0x0f, 0x55, 0x00, 0x03, 0x56, 0x56, 0x03, 0x00, 0x55, 0x0f, 0x5a, 0x59, 0x0c,
1507         0x0f, 0x5a, 0x59, 0x0c, 0x56, 0x03, 0x00, 0x55, 0x55, 0x00, 0x03, 0x56, 0x0c, 0x59, 0x5a, 0x0f,
1508         0x6a, 0x3f, 0x3c, 0x69, 0x33, 0x66, 0x65, 0x30, 0x30, 0x65, 0x66, 0x33, 0x69, 0x3c, 0x3f, 0x6a,
1509         0x6a, 0x3f, 0x3c, 0x69, 0x33, 0x66, 0x65, 0x30, 0x30, 0x65, 0x66, 0x33, 0x69, 0x3c, 0x3f, 0x6a,
1510         0x0f, 0x5a, 0x59, 0x0c, 0x56, 0x03, 0x00, 0x55, 0x55, 0x00, 0x03, 0x56, 0x0c, 0x59, 0x5a, 0x0f,
1511         0x0c, 0x59, 0x5a, 0x0f, 0x55, 0x00, 0x03, 0x56, 0x56, 0x03, 0x00, 0x55, 0x0f, 0x5a, 0x59, 0x0c,
1512         0x69, 0x3c, 0x3f, 0x6a, 0x30, 0x65, 0x66, 0x33, 0x33, 0x66, 0x65, 0x30, 0x6a, 0x3f, 0x3c, 0x69,
1513         0x03, 0x56, 0x55, 0x00, 0x5a, 0x0f, 0x0c, 0x59, 0x59, 0x0c, 0x0f, 0x5a, 0x00, 0x55, 0x56, 0x03,
1514         0x66, 0x33, 0x30, 0x65, 0x3f, 0x6a, 0x69, 0x3c, 0x3c, 0x69, 0x6a, 0x3f, 0x65, 0x30, 0x33, 0x66,
1515         0x65, 0x30, 0x33, 0x66, 0x3c, 0x69, 0x6a, 0x3f, 0x3f, 0x6a, 0x69, 0x3c, 0x66, 0x33, 0x30, 0x65,
1516         0x00, 0x55, 0x56, 0x03, 0x59, 0x0c, 0x0f, 0x5a, 0x5a, 0x0f, 0x0c, 0x59, 0x03, 0x56, 0x55, 0x00
1517 };
1518
1519
1520 /*
1521  * Creates non-inverted ECC code from line parity
1522  */
1523 static void nand_trans_result(u_char reg2, u_char reg3,
1524         u_char *ecc_code)
1525 {
1526         u_char a, b, i, tmp1, tmp2;
1527
1528         /* Initialize variables */
1529         a = b = 0x80;
1530         tmp1 = tmp2 = 0;
1531
1532         /* Calculate first ECC byte */
1533         for (i = 0; i < 4; i++) {
1534                 if (reg3 & a)           /* LP15,13,11,9 --> ecc_code[0] */
1535                         tmp1 |= b;
1536                 b >>= 1;
1537                 if (reg2 & a)           /* LP14,12,10,8 --> ecc_code[0] */
1538                         tmp1 |= b;
1539                 b >>= 1;
1540                 a >>= 1;
1541         }
1542
1543         /* Calculate second ECC byte */
1544         b = 0x80;
1545         for (i = 0; i < 4; i++) {
1546                 if (reg3 & a)           /* LP7,5,3,1 --> ecc_code[1] */
1547                         tmp2 |= b;
1548                 b >>= 1;
1549                 if (reg2 & a)           /* LP6,4,2,0 --> ecc_code[1] */
1550                         tmp2 |= b;
1551                 b >>= 1;
1552                 a >>= 1;
1553         }
1554
1555         /* Store two of the ECC bytes */
1556         ecc_code[0] = tmp1;
1557         ecc_code[1] = tmp2;
1558 }
1559
1560 /*
1561  * Calculate 3 byte ECC code for 256 byte block
1562  */
1563 static void nand_calculate_ecc (const u_char *dat, u_char *ecc_code)
1564 {
1565         u_char idx, reg1, reg3;
1566         int j;
1567
1568         /* Initialize variables */
1569         reg1 = reg3 = 0;
1570         ecc_code[0] = ecc_code[1] = ecc_code[2] = 0;
1571
1572         /* Build up column parity */
1573         for(j = 0; j < 256; j++) {
1574
1575                 /* Get CP0 - CP5 from table */
1576                 idx = nand_ecc_precalc_table[dat[j]];
1577                 reg1 ^= idx;
1578
1579                 /* All bit XOR = 1 ? */
1580                 if (idx & 0x40) {
1581                         reg3 ^= (u_char) j;
1582                 }
1583         }
1584
1585         /* Create non-inverted ECC code from line parity */
1586         nand_trans_result((reg1 & 0x40) ? ~reg3 : reg3, reg3, ecc_code);
1587
1588         /* Calculate final ECC code */
1589         ecc_code[0] = ~ecc_code[0];
1590         ecc_code[1] = ~ecc_code[1];
1591         ecc_code[2] = ((~reg1) << 2) | 0x03;
1592 }
1593
1594 /*
1595  * Detect and correct a 1 bit error for 256 byte block
1596  */
1597 static int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc)
1598 {
1599         u_char a, b, c, d1, d2, d3, add, bit, i;
1600
1601         /* Do error detection */
1602         d1 = calc_ecc[0] ^ read_ecc[0];
1603         d2 = calc_ecc[1] ^ read_ecc[1];
1604         d3 = calc_ecc[2] ^ read_ecc[2];
1605
1606         if ((d1 | d2 | d3) == 0) {
1607                 /* No errors */
1608                 return 0;
1609         }
1610         else {
1611                 a = (d1 ^ (d1 >> 1)) & 0x55;
1612                 b = (d2 ^ (d2 >> 1)) & 0x55;
1613                 c = (d3 ^ (d3 >> 1)) & 0x54;
1614
1615                 /* Found and will correct single bit error in the data */
1616                 if ((a == 0x55) && (b == 0x55) && (c == 0x54)) {
1617                         c = 0x80;
1618                         add = 0;
1619                         a = 0x80;
1620                         for (i=0; i<4; i++) {
1621                                 if (d1 & c)
1622                                         add |= a;
1623                                 c >>= 2;
1624                                 a >>= 1;
1625                         }
1626                         c = 0x80;
1627                         for (i=0; i<4; i++) {
1628                                 if (d2 & c)
1629                                         add |= a;
1630                                 c >>= 2;
1631                                 a >>= 1;
1632                         }
1633                         bit = 0;
1634                         b = 0x04;
1635                         c = 0x80;
1636                         for (i=0; i<3; i++) {
1637                                 if (d3 & c)
1638                                         bit |= b;
1639                                 c >>= 2;
1640                                 b >>= 1;
1641                         }
1642                         b = 0x01;
1643                         a = dat[add];
1644                         a ^= (b << bit);
1645                         dat[add] = a;
1646                         return 1;
1647                 }
1648                 else {
1649                         i = 0;
1650                         while (d1) {
1651                                 if (d1 & 0x01)
1652                                         ++i;
1653                                 d1 >>= 1;
1654                         }
1655                         while (d2) {
1656                                 if (d2 & 0x01)
1657                                         ++i;
1658                                 d2 >>= 1;
1659                         }
1660                         while (d3) {
1661                                 if (d3 & 0x01)
1662                                         ++i;
1663                                 d3 >>= 1;
1664                         }
1665                         if (i == 1) {
1666                                 /* ECC Code Error Correction */
1667                                 read_ecc[0] = calc_ecc[0];
1668                                 read_ecc[1] = calc_ecc[1];
1669                                 read_ecc[2] = calc_ecc[2];
1670                                 return 2;
1671                         }
1672                         else {
1673                                 /* Uncorrectable Error */
1674                                 return -1;
1675                         }
1676                 }
1677         }
1678
1679         /* Should never happen */
1680         return -1;
1681 }
1682
1683 #endif
1684
1685 #ifdef CONFIG_JFFS2_NAND
1686
1687 int read_jffs2_nand(size_t start, size_t len,
1688                     size_t * retlen, u_char * buf, int nanddev)
1689 {
1690         return nand_rw(nand_dev_desc + nanddev, NANDRW_READ | NANDRW_JFFS2,
1691                        start, len, retlen, buf);
1692 }
1693
1694 #endif /* CONFIG_JFFS2_NAND */
1695
1696
1697 #endif /* (CONFIG_COMMANDS & CFG_CMD_NAND) */