arm, kirkwood: added kw_gpio_set_valid() in gpio.h
[platform/kernel/u-boot.git] / common / cmd_doc.c
1 /*
2  * Driver for Disk-On-Chip 2000 and Millennium
3  * (c) 1999 Machine Vision Holdings, Inc.
4  * (c) 1999, 2000 David Woodhouse <dwmw2@infradead.org>
5  *
6  * $Id: doc2000.c,v 1.46 2001/10/02 15:05:13 dwmw2 Exp $
7  */
8
9 #include <common.h>
10 #include <config.h>
11 #include <command.h>
12 #include <malloc.h>
13 #include <asm/io.h>
14 #include <linux/mtd/nftl.h>
15 #include <linux/mtd/doc2000.h>
16
17 #error This code is broken and will be removed outright in the next release.
18 #error If you need diskonchip support, please update the Linux driver in
19 #error drivers/mtd/nand/diskonchip.c to work with u-boot.
20
21 /*
22  * ! BROKEN !
23  *
24  * TODO: must be implemented and tested by someone with HW
25  */
26 #if 0
27 #ifdef CONFIG_SYS_DOC_SUPPORT_2000
28 #define DoC_is_2000(doc) (doc->ChipID == DOC_ChipID_Doc2k)
29 #else
30 #define DoC_is_2000(doc) (0)
31 #endif
32
33 #ifdef CONFIG_SYS_DOC_SUPPORT_MILLENNIUM
34 #define DoC_is_Millennium(doc) (doc->ChipID == DOC_ChipID_DocMil)
35 #else
36 #define DoC_is_Millennium(doc) (0)
37 #endif
38
39 /* CONFIG_SYS_DOC_PASSIVE_PROBE:
40    In order to ensure that the BIOS checksum is correct at boot time, and
41    hence that the onboard BIOS extension gets executed, the DiskOnChip
42    goes into reset mode when it is read sequentially: all registers
43    return 0xff until the chip is woken up again by writing to the
44    DOCControl register.
45
46    Unfortunately, this means that the probe for the DiskOnChip is unsafe,
47    because one of the first things it does is write to where it thinks
48    the DOCControl register should be - which may well be shared memory
49    for another device. I've had machines which lock up when this is
50    attempted. Hence the possibility to do a passive probe, which will fail
51    to detect a chip in reset mode, but is at least guaranteed not to lock
52    the machine.
53
54    If you have this problem, uncomment the following line:
55 #define CONFIG_SYS_DOC_PASSIVE_PROBE
56 */
57
58 #undef  DOC_DEBUG
59 #undef  ECC_DEBUG
60 #undef  PSYCHO_DEBUG
61 #undef  NFTL_DEBUG
62
63 static struct DiskOnChip doc_dev_desc[CONFIG_SYS_MAX_DOC_DEVICE];
64
65 /* Current DOC Device   */
66 static int curr_device = -1;
67
68 /* Supported NAND flash devices */
69 static struct nand_flash_dev nand_flash_ids[] = {
70         {"Toshiba TC5816BDC",     NAND_MFR_TOSHIBA, 0x64, 21, 1, 2, 0x1000, 0},
71         {"Toshiba TC5832DC",      NAND_MFR_TOSHIBA, 0x6b, 22, 0, 2, 0x2000, 0},
72         {"Toshiba TH58V128DC",    NAND_MFR_TOSHIBA, 0x73, 24, 0, 2, 0x4000, 0},
73         {"Toshiba TC58256FT/DC",  NAND_MFR_TOSHIBA, 0x75, 25, 0, 2, 0x4000, 0},
74         {"Toshiba TH58512FT",     NAND_MFR_TOSHIBA, 0x76, 26, 0, 3, 0x4000, 0},
75         {"Toshiba TC58V32DC",     NAND_MFR_TOSHIBA, 0xe5, 22, 0, 2, 0x2000, 0},
76         {"Toshiba TC58V64AFT/DC", NAND_MFR_TOSHIBA, 0xe6, 23, 0, 2, 0x2000, 0},
77         {"Toshiba TC58V16BDC",    NAND_MFR_TOSHIBA, 0xea, 21, 1, 2, 0x1000, 0},
78         {"Toshiba TH58100FT",     NAND_MFR_TOSHIBA, 0x79, 27, 0, 3, 0x4000, 0},
79         {"Samsung KM29N16000",    NAND_MFR_SAMSUNG, 0x64, 21, 1, 2, 0x1000, 0},
80         {"Samsung unknown 4Mb",   NAND_MFR_SAMSUNG, 0x6b, 22, 0, 2, 0x2000, 0},
81         {"Samsung KM29U128T",     NAND_MFR_SAMSUNG, 0x73, 24, 0, 2, 0x4000, 0},
82         {"Samsung KM29U256T",     NAND_MFR_SAMSUNG, 0x75, 25, 0, 2, 0x4000, 0},
83         {"Samsung unknown 64Mb",  NAND_MFR_SAMSUNG, 0x76, 26, 0, 3, 0x4000, 0},
84         {"Samsung KM29W32000",    NAND_MFR_SAMSUNG, 0xe3, 22, 0, 2, 0x2000, 0},
85         {"Samsung unknown 4Mb",   NAND_MFR_SAMSUNG, 0xe5, 22, 0, 2, 0x2000, 0},
86         {"Samsung KM29U64000",    NAND_MFR_SAMSUNG, 0xe6, 23, 0, 2, 0x2000, 0},
87         {"Samsung KM29W16000",    NAND_MFR_SAMSUNG, 0xea, 21, 1, 2, 0x1000, 0},
88         {"Samsung K9F5616Q0C",    NAND_MFR_SAMSUNG, 0x45, 25, 0, 2, 0x4000, 1},
89         {"Samsung K9K1216Q0C",    NAND_MFR_SAMSUNG, 0x46, 26, 0, 3, 0x4000, 1},
90         {"Samsung K9F1G08U0M",    NAND_MFR_SAMSUNG, 0xf1, 27, 0, 2, 0, 0},
91         {NULL,}
92 };
93
94 /* ------------------------------------------------------------------------- */
95
96 int do_doc (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
97 {
98     int rcode = 0;
99
100     switch (argc) {
101     case 0:
102     case 1:
103         cmd_usage(cmdtp);
104         return 1;
105     case 2:
106         if (strcmp(argv[1],"info") == 0) {
107                 int i;
108
109                 putc ('\n');
110
111                 for (i=0; i<CONFIG_SYS_MAX_DOC_DEVICE; ++i) {
112                         if(doc_dev_desc[i].ChipID == DOC_ChipID_UNKNOWN)
113                                 continue; /* list only known devices */
114                         printf ("Device %d: ", i);
115                         doc_print(&doc_dev_desc[i]);
116                 }
117                 return 0;
118
119         } else if (strcmp(argv[1],"device") == 0) {
120                 if ((curr_device < 0) || (curr_device >= CONFIG_SYS_MAX_DOC_DEVICE)) {
121                         puts ("\nno devices available\n");
122                         return 1;
123                 }
124                 printf ("\nDevice %d: ", curr_device);
125                 doc_print(&doc_dev_desc[curr_device]);
126                 return 0;
127         }
128         cmd_usage(cmdtp);
129         return 1;
130     case 3:
131         if (strcmp(argv[1],"device") == 0) {
132                 int dev = (int)simple_strtoul(argv[2], NULL, 10);
133
134                 printf ("\nDevice %d: ", dev);
135                 if (dev >= CONFIG_SYS_MAX_DOC_DEVICE) {
136                         puts ("unknown device\n");
137                         return 1;
138                 }
139                 doc_print(&doc_dev_desc[dev]);
140                 /*doc_print (dev);*/
141
142                 if (doc_dev_desc[dev].ChipID == DOC_ChipID_UNKNOWN) {
143                         return 1;
144                 }
145
146                 curr_device = dev;
147
148                 puts ("... is now current device\n");
149
150                 return 0;
151         }
152
153         cmd_usage(cmdtp);
154         return 1;
155     default:
156         /* at least 4 args */
157
158         if (strcmp(argv[1],"read") == 0 || strcmp(argv[1],"write") == 0) {
159                 ulong addr = simple_strtoul(argv[2], NULL, 16);
160                 ulong off  = simple_strtoul(argv[3], NULL, 16);
161                 ulong size = simple_strtoul(argv[4], NULL, 16);
162                 int cmd    = (strcmp(argv[1],"read") == 0);
163                 int ret, total;
164
165                 printf ("\nDOC %s: device %d offset %ld, size %ld ... ",
166                         cmd ? "read" : "write", curr_device, off, size);
167
168                 ret = doc_rw(doc_dev_desc + curr_device, cmd, off, size,
169                              (size_t *)&total, (u_char*)addr);
170
171                 printf ("%d bytes %s: %s\n", total, cmd ? "read" : "write",
172                         ret ? "ERROR" : "OK");
173
174                 return ret;
175         } else if (strcmp(argv[1],"erase") == 0) {
176                 ulong off = simple_strtoul(argv[2], NULL, 16);
177                 ulong size = simple_strtoul(argv[3], NULL, 16);
178                 int ret;
179
180                 printf ("\nDOC erase: device %d offset %ld, size %ld ... ",
181                         curr_device, off, size);
182
183                 ret = doc_erase (doc_dev_desc + curr_device, off, size);
184
185                 printf("%s\n", ret ? "ERROR" : "OK");
186
187                 return ret;
188         } else {
189                 cmd_usage(cmdtp);
190                 rcode = 1;
191         }
192
193         return rcode;
194     }
195 }
196 U_BOOT_CMD(
197         doc,    5,      1,      do_doc,
198         "Disk-On-Chip sub-system",
199         "info  - show available DOC devices\n"
200         "doc device [dev] - show or set current device\n"
201         "doc read  addr off size\n"
202         "doc write addr off size - read/write `size'"
203         " bytes starting at offset `off'\n"
204         "    to/from memory address `addr'\n"
205         "doc erase off size - erase `size' bytes of DOC from offset `off'"
206 );
207
208 int do_docboot (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
209 {
210         char *boot_device = NULL;
211         char *ep;
212         int dev;
213         ulong cnt;
214         ulong addr;
215         ulong offset = 0;
216         image_header_t *hdr;
217         int rcode = 0;
218 #if defined(CONFIG_FIT)
219         const void *fit_hdr = NULL;
220 #endif
221
222         show_boot_progress (34);
223         switch (argc) {
224         case 1:
225                 addr = CONFIG_SYS_LOAD_ADDR;
226                 boot_device = getenv ("bootdevice");
227                 break;
228         case 2:
229                 addr = simple_strtoul(argv[1], NULL, 16);
230                 boot_device = getenv ("bootdevice");
231                 break;
232         case 3:
233                 addr = simple_strtoul(argv[1], NULL, 16);
234                 boot_device = argv[2];
235                 break;
236         case 4:
237                 addr = simple_strtoul(argv[1], NULL, 16);
238                 boot_device = argv[2];
239                 offset = simple_strtoul(argv[3], NULL, 16);
240                 break;
241         default:
242                 cmd_usage(cmdtp);
243                 show_boot_progress (-35);
244                 return 1;
245         }
246
247         show_boot_progress (35);
248         if (!boot_device) {
249                 puts ("\n** No boot device **\n");
250                 show_boot_progress (-36);
251                 return 1;
252         }
253         show_boot_progress (36);
254
255         dev = simple_strtoul(boot_device, &ep, 16);
256
257         if ((dev >= CONFIG_SYS_MAX_DOC_DEVICE) ||
258             (doc_dev_desc[dev].ChipID == DOC_ChipID_UNKNOWN)) {
259                 printf ("\n** Device %d not available\n", dev);
260                 show_boot_progress (-37);
261                 return 1;
262         }
263         show_boot_progress (37);
264
265         printf ("\nLoading from device %d: %s at 0x%lX (offset 0x%lX)\n",
266                 dev, doc_dev_desc[dev].name, doc_dev_desc[dev].physadr,
267                 offset);
268
269         if (doc_rw (doc_dev_desc + dev, 1, offset,
270                     SECTORSIZE, NULL, (u_char *)addr)) {
271                 printf ("** Read error on %d\n", dev);
272                 show_boot_progress (-38);
273                 return 1;
274         }
275         show_boot_progress (38);
276
277         switch (genimg_get_format ((void *)addr)) {
278         case IMAGE_FORMAT_LEGACY:
279                 hdr = (image_header_t *)addr;
280
281                 image_print_contents (hdr);
282
283                 cnt = image_get_image_size (hdr);
284                 break;
285 #if defined(CONFIG_FIT)
286         case IMAGE_FORMAT_FIT:
287                 fit_hdr = (const void *)addr;
288                 puts ("Fit image detected...\n");
289
290                 cnt = fit_get_size (fit_hdr);
291                 break;
292 #endif
293         default:
294                 show_boot_progress (-39);
295                 puts ("** Unknown image type\n");
296                 return 1;
297         }
298         show_boot_progress (39);
299
300         cnt -= SECTORSIZE;
301         if (doc_rw (doc_dev_desc + dev, 1, offset + SECTORSIZE, cnt,
302                     NULL, (u_char *)(addr+SECTORSIZE))) {
303                 printf ("** Read error on %d\n", dev);
304                 show_boot_progress (-40);
305                 return 1;
306         }
307         show_boot_progress (40);
308
309 #if defined(CONFIG_FIT)
310         /* This cannot be done earlier, we need complete FIT image in RAM first */
311         if (genimg_get_format ((void *)addr) == IMAGE_FORMAT_FIT) {
312                 if (!fit_check_format (fit_hdr)) {
313                         show_boot_progress (-130);
314                         puts ("** Bad FIT image format\n");
315                         return 1;
316                 }
317                 show_boot_progress (131);
318                 fit_print_contents (fit_hdr);
319         }
320 #endif
321
322         /* Loading ok, update default load address */
323
324         load_addr = addr;
325
326         /* Check if we should attempt an auto-start */
327         if (((ep = getenv("autostart")) != NULL) && (strcmp(ep,"yes") == 0)) {
328                 char *local_args[2];
329                 extern int do_bootm (cmd_tbl_t *, int, int, char *[]);
330
331                 local_args[0] = argv[0];
332                 local_args[1] = NULL;
333
334                 printf ("Automatic boot of image at addr 0x%08lX ...\n", addr);
335
336                 do_bootm (cmdtp, 0, 1, local_args);
337                 rcode = 1;
338         }
339         return rcode;
340 }
341
342 U_BOOT_CMD(
343         docboot,        4,      1,      do_docboot,
344         "boot from DOC device",
345         "loadAddr dev"
346 );
347
348 int doc_rw (struct DiskOnChip* this, int cmd,
349             loff_t from, size_t len,
350             size_t * retlen, u_char * buf)
351 {
352         int noecc, ret = 0, n, total = 0;
353         char eccbuf[6];
354
355         while(len) {
356                 /* The ECC will not be calculated correctly if
357                    less than 512 is written or read */
358                 noecc = (from != (from | 0x1ff) + 1) || (len < 0x200);
359
360                 if (cmd)
361                         ret = doc_read_ecc(this, from, len,
362                                            (size_t *)&n, (u_char*)buf,
363                                            noecc ? (uchar *)NULL : (uchar *)eccbuf);
364                 else
365                         ret = doc_write_ecc(this, from, len,
366                                             (size_t *)&n, (u_char*)buf,
367                                             noecc ? (uchar *)NULL : (uchar *)eccbuf);
368
369                 if (ret)
370                         break;
371
372                 from  += n;
373                 buf   += n;
374                 total += n;
375                 len   -= n;
376         }
377
378         if (retlen)
379                 *retlen = total;
380
381         return ret;
382 }
383
384 void doc_print(struct DiskOnChip *this) {
385         printf("%s at 0x%lX,\n"
386                "\t  %d chip%s %s, size %d MB, \n"
387                "\t  total size %ld MB, sector size %ld kB\n",
388                this->name, this->physadr, this->numchips,
389                this->numchips>1 ? "s" : "", this->chips_name,
390                1 << (this->chipshift - 20),
391                this->totlen >> 20, this->erasesize >> 10);
392
393         if (this->nftl_found) {
394                 struct NFTLrecord *nftl = &this->nftl;
395                 unsigned long bin_size, flash_size;
396
397                 bin_size = nftl->nb_boot_blocks * this->erasesize;
398                 flash_size = (nftl->nb_blocks - nftl->nb_boot_blocks) * this->erasesize;
399
400                 printf("\t  NFTL boot record:\n"
401                        "\t    Binary partition: size %ld%s\n"
402                        "\t    Flash disk partition: size %ld%s, offset 0x%lx\n",
403                        bin_size > (1 << 20) ? bin_size >> 20 : bin_size >> 10,
404                        bin_size > (1 << 20) ? "MB" : "kB",
405                        flash_size > (1 << 20) ? flash_size >> 20 : flash_size >> 10,
406                        flash_size > (1 << 20) ? "MB" : "kB", bin_size);
407         } else {
408                 puts ("\t  No NFTL boot record found.\n");
409         }
410 }
411
412 /* ------------------------------------------------------------------------- */
413
414 /* This function is needed to avoid calls of the __ashrdi3 function. */
415 static int shr(int val, int shift) {
416         return val >> shift;
417 }
418
419 /* Perform the required delay cycles by reading from the appropriate register */
420 static void DoC_Delay(struct DiskOnChip *doc, unsigned short cycles)
421 {
422         volatile char dummy;
423         int i;
424
425         for (i = 0; i < cycles; i++) {
426                 if (DoC_is_Millennium(doc))
427                         dummy = ReadDOC(doc->virtadr, NOP);
428                 else
429                         dummy = ReadDOC(doc->virtadr, DOCStatus);
430         }
431
432 }
433
434 /* DOC_WaitReady: Wait for RDY line to be asserted by the flash chip */
435 static int _DoC_WaitReady(struct DiskOnChip *doc)
436 {
437         unsigned long docptr = doc->virtadr;
438         unsigned long start = get_timer(0);
439
440 #ifdef PSYCHO_DEBUG
441         puts ("_DoC_WaitReady called for out-of-line wait\n");
442 #endif
443
444         /* Out-of-line routine to wait for chip response */
445         while (!(ReadDOC(docptr, CDSNControl) & CDSN_CTRL_FR_B)) {
446 #ifdef CONFIG_SYS_DOC_SHORT_TIMEOUT
447                 /* it seems that after a certain time the DoC deasserts
448                  * the CDSN_CTRL_FR_B although it is not ready...
449                  * using a short timout solve this (timer increments every ms) */
450                 if (get_timer(start) > 10) {
451                         return DOC_ETIMEOUT;
452                 }
453 #else
454                 if (get_timer(start) > 10 * 1000) {
455                         puts ("_DoC_WaitReady timed out.\n");
456                         return DOC_ETIMEOUT;
457                 }
458 #endif
459                 udelay(1);
460         }
461
462         return 0;
463 }
464
465 static int DoC_WaitReady(struct DiskOnChip *doc)
466 {
467         unsigned long docptr = doc->virtadr;
468         /* This is inline, to optimise the common case, where it's ready instantly */
469         int ret = 0;
470
471         /* 4 read form NOP register should be issued in prior to the read from CDSNControl
472            see Software Requirement 11.4 item 2. */
473         DoC_Delay(doc, 4);
474
475         if (!(ReadDOC(docptr, CDSNControl) & CDSN_CTRL_FR_B))
476                 /* Call the out-of-line routine to wait */
477                 ret = _DoC_WaitReady(doc);
478
479         /* issue 2 read from NOP register after reading from CDSNControl register
480            see Software Requirement 11.4 item 2. */
481         DoC_Delay(doc, 2);
482
483         return ret;
484 }
485
486 /* DoC_Command: Send a flash command to the flash chip through the CDSN Slow IO register to
487    bypass the internal pipeline. Each of 4 delay cycles (read from the NOP register) is
488    required after writing to CDSN Control register, see Software Requirement 11.4 item 3. */
489
490 static inline int DoC_Command(struct DiskOnChip *doc, unsigned char command,
491                               unsigned char xtraflags)
492 {
493         unsigned long docptr = doc->virtadr;
494
495         if (DoC_is_2000(doc))
496                 xtraflags |= CDSN_CTRL_FLASH_IO;
497
498         /* Assert the CLE (Command Latch Enable) line to the flash chip */
499         WriteDOC(xtraflags | CDSN_CTRL_CLE | CDSN_CTRL_CE, docptr, CDSNControl);
500         DoC_Delay(doc, 4);      /* Software requirement 11.4.3 for Millennium */
501
502         if (DoC_is_Millennium(doc))
503                 WriteDOC(command, docptr, CDSNSlowIO);
504
505         /* Send the command */
506         WriteDOC_(command, docptr, doc->ioreg);
507
508         /* Lower the CLE line */
509         WriteDOC(xtraflags | CDSN_CTRL_CE, docptr, CDSNControl);
510         DoC_Delay(doc, 4);      /* Software requirement 11.4.3 for Millennium */
511
512         /* Wait for the chip to respond - Software requirement 11.4.1 (extended for any command) */
513         return DoC_WaitReady(doc);
514 }
515
516 /* DoC_Address: Set the current address for the flash chip through the CDSN Slow IO register to
517    bypass the internal pipeline. Each of 4 delay cycles (read from the NOP register) is
518    required after writing to CDSN Control register, see Software Requirement 11.4 item 3. */
519
520 static int DoC_Address(struct DiskOnChip *doc, int numbytes, unsigned long ofs,
521                        unsigned char xtraflags1, unsigned char xtraflags2)
522 {
523         unsigned long docptr;
524         int i;
525
526         docptr = doc->virtadr;
527
528         if (DoC_is_2000(doc))
529                 xtraflags1 |= CDSN_CTRL_FLASH_IO;
530
531         /* Assert the ALE (Address Latch Enable) line to the flash chip */
532         WriteDOC(xtraflags1 | CDSN_CTRL_ALE | CDSN_CTRL_CE, docptr, CDSNControl);
533
534         DoC_Delay(doc, 4);      /* Software requirement 11.4.3 for Millennium */
535
536         /* Send the address */
537         /* Devices with 256-byte page are addressed as:
538            Column (bits 0-7), Page (bits 8-15, 16-23, 24-31)
539            * there is no device on the market with page256
540            and more than 24 bits.
541            Devices with 512-byte page are addressed as:
542            Column (bits 0-7), Page (bits 9-16, 17-24, 25-31)
543            * 25-31 is sent only if the chip support it.
544            * bit 8 changes the read command to be sent
545            (NAND_CMD_READ0 or NAND_CMD_READ1).
546          */
547
548         if (numbytes == ADDR_COLUMN || numbytes == ADDR_COLUMN_PAGE) {
549                 if (DoC_is_Millennium(doc))
550                         WriteDOC(ofs & 0xff, docptr, CDSNSlowIO);
551                 WriteDOC_(ofs & 0xff, docptr, doc->ioreg);
552         }
553
554         if (doc->page256) {
555                 ofs = ofs >> 8;
556         } else {
557                 ofs = ofs >> 9;
558         }
559
560         if (numbytes == ADDR_PAGE || numbytes == ADDR_COLUMN_PAGE) {
561                 for (i = 0; i < doc->pageadrlen; i++, ofs = ofs >> 8) {
562                         if (DoC_is_Millennium(doc))
563                                 WriteDOC(ofs & 0xff, docptr, CDSNSlowIO);
564                         WriteDOC_(ofs & 0xff, docptr, doc->ioreg);
565                 }
566         }
567
568         DoC_Delay(doc, 2);      /* Needed for some slow flash chips. mf. */
569
570         /* FIXME: The SlowIO's for millennium could be replaced by
571            a single WritePipeTerm here. mf. */
572
573         /* Lower the ALE line */
574         WriteDOC(xtraflags1 | xtraflags2 | CDSN_CTRL_CE, docptr,
575                  CDSNControl);
576
577         DoC_Delay(doc, 4);      /* Software requirement 11.4.3 for Millennium */
578
579         /* Wait for the chip to respond - Software requirement 11.4.1 */
580         return DoC_WaitReady(doc);
581 }
582
583 /* Read a buffer from DoC, taking care of Millennium oddities */
584 static void DoC_ReadBuf(struct DiskOnChip *doc, u_char * buf, int len)
585 {
586         volatile int dummy;
587         int modulus = 0xffff;
588         unsigned long docptr;
589         int i;
590
591         docptr = doc->virtadr;
592
593         if (len <= 0)
594                 return;
595
596         if (DoC_is_Millennium(doc)) {
597                 /* Read the data via the internal pipeline through CDSN IO register,
598                    see Pipelined Read Operations 11.3 */
599                 dummy = ReadDOC(docptr, ReadPipeInit);
600
601                 /* Millennium should use the LastDataRead register - Pipeline Reads */
602                 len--;
603
604                 /* This is needed for correctly ECC calculation */
605                 modulus = 0xff;
606         }
607
608         for (i = 0; i < len; i++)
609                 buf[i] = ReadDOC_(docptr, doc->ioreg + (i & modulus));
610
611         if (DoC_is_Millennium(doc)) {
612                 buf[i] = ReadDOC(docptr, LastDataRead);
613         }
614 }
615
616 /* Write a buffer to DoC, taking care of Millennium oddities */
617 static void DoC_WriteBuf(struct DiskOnChip *doc, const u_char * buf, int len)
618 {
619         unsigned long docptr;
620         int i;
621
622         docptr = doc->virtadr;
623
624         if (len <= 0)
625                 return;
626
627         for (i = 0; i < len; i++)
628                 WriteDOC_(buf[i], docptr, doc->ioreg + i);
629
630         if (DoC_is_Millennium(doc)) {
631                 WriteDOC(0x00, docptr, WritePipeTerm);
632         }
633 }
634
635
636 /* DoC_SelectChip: Select a given flash chip within the current floor */
637
638 static inline int DoC_SelectChip(struct DiskOnChip *doc, int chip)
639 {
640         unsigned long docptr = doc->virtadr;
641
642         /* Software requirement 11.4.4 before writing DeviceSelect */
643         /* Deassert the CE line to eliminate glitches on the FCE# outputs */
644         WriteDOC(CDSN_CTRL_WP, docptr, CDSNControl);
645         DoC_Delay(doc, 4);      /* Software requirement 11.4.3 for Millennium */
646
647         /* Select the individual flash chip requested */
648         WriteDOC(chip, docptr, CDSNDeviceSelect);
649         DoC_Delay(doc, 4);
650
651         /* Reassert the CE line */
652         WriteDOC(CDSN_CTRL_CE | CDSN_CTRL_FLASH_IO | CDSN_CTRL_WP, docptr,
653                  CDSNControl);
654         DoC_Delay(doc, 4);      /* Software requirement 11.4.3 for Millennium */
655
656         /* Wait for it to be ready */
657         return DoC_WaitReady(doc);
658 }
659
660 /* DoC_SelectFloor: Select a given floor (bank of flash chips) */
661
662 static inline int DoC_SelectFloor(struct DiskOnChip *doc, int floor)
663 {
664         unsigned long docptr = doc->virtadr;
665
666         /* Select the floor (bank) of chips required */
667         WriteDOC(floor, docptr, FloorSelect);
668
669         /* Wait for the chip to be ready */
670         return DoC_WaitReady(doc);
671 }
672
673 /* DoC_IdentChip: Identify a given NAND chip given {floor,chip} */
674
675 static int DoC_IdentChip(struct DiskOnChip *doc, int floor, int chip)
676 {
677         int mfr, id, i;
678         volatile char dummy;
679
680         /* Page in the required floor/chip */
681         DoC_SelectFloor(doc, floor);
682         DoC_SelectChip(doc, chip);
683
684         /* Reset the chip */
685         if (DoC_Command(doc, NAND_CMD_RESET, CDSN_CTRL_WP)) {
686 #ifdef DOC_DEBUG
687                 printf("DoC_Command (reset) for %d,%d returned true\n",
688                        floor, chip);
689 #endif
690                 return 0;
691         }
692
693
694         /* Read the NAND chip ID: 1. Send ReadID command */
695         if (DoC_Command(doc, NAND_CMD_READID, CDSN_CTRL_WP)) {
696 #ifdef DOC_DEBUG
697                 printf("DoC_Command (ReadID) for %d,%d returned true\n",
698                        floor, chip);
699 #endif
700                 return 0;
701         }
702
703         /* Read the NAND chip ID: 2. Send address byte zero */
704         DoC_Address(doc, ADDR_COLUMN, 0, CDSN_CTRL_WP, 0);
705
706         /* Read the manufacturer and device id codes from the device */
707
708         /* CDSN Slow IO register see Software Requirement 11.4 item 5. */
709         dummy = ReadDOC(doc->virtadr, CDSNSlowIO);
710         DoC_Delay(doc, 2);
711         mfr = ReadDOC_(doc->virtadr, doc->ioreg);
712
713         /* CDSN Slow IO register see Software Requirement 11.4 item 5. */
714         dummy = ReadDOC(doc->virtadr, CDSNSlowIO);
715         DoC_Delay(doc, 2);
716         id = ReadDOC_(doc->virtadr, doc->ioreg);
717
718         /* No response - return failure */
719         if (mfr == 0xff || mfr == 0)
720                 return 0;
721
722         /* Check it's the same as the first chip we identified.
723          * M-Systems say that any given DiskOnChip device should only
724          * contain _one_ type of flash part, although that's not a
725          * hardware restriction. */
726         if (doc->mfr) {
727                 if (doc->mfr == mfr && doc->id == id)
728                         return 1;       /* This is another the same the first */
729                 else
730                         printf("Flash chip at floor %d, chip %d is different:\n",
731                                floor, chip);
732         }
733
734         /* Print and store the manufacturer and ID codes. */
735         for (i = 0; nand_flash_ids[i].name != NULL; i++) {
736                 if (mfr == nand_flash_ids[i].manufacture_id &&
737                     id == nand_flash_ids[i].model_id) {
738 #ifdef DOC_DEBUG
739                         printf("Flash chip found: Manufacturer ID: %2.2X, "
740                                "Chip ID: %2.2X (%s)\n", mfr, id,
741                                nand_flash_ids[i].name);
742 #endif
743                         if (!doc->mfr) {
744                                 doc->mfr = mfr;
745                                 doc->id = id;
746                                 doc->chipshift =
747                                     nand_flash_ids[i].chipshift;
748                                 doc->page256 = nand_flash_ids[i].page256;
749                                 doc->pageadrlen =
750                                     nand_flash_ids[i].pageadrlen;
751                                 doc->erasesize =
752                                     nand_flash_ids[i].erasesize;
753                                 doc->chips_name =
754                                     nand_flash_ids[i].name;
755                                 return 1;
756                         }
757                         return 0;
758                 }
759         }
760
761
762 #ifdef DOC_DEBUG
763         /* We haven't fully identified the chip. Print as much as we know. */
764         printf("Unknown flash chip found: %2.2X %2.2X\n",
765                id, mfr);
766 #endif
767
768         return 0;
769 }
770
771 /* DoC_ScanChips: Find all NAND chips present in a DiskOnChip, and identify them */
772
773 static void DoC_ScanChips(struct DiskOnChip *this)
774 {
775         int floor, chip;
776         int numchips[MAX_FLOORS];
777         int maxchips = MAX_CHIPS;
778         int ret = 1;
779
780         this->numchips = 0;
781         this->mfr = 0;
782         this->id = 0;
783
784         if (DoC_is_Millennium(this))
785                 maxchips = MAX_CHIPS_MIL;
786
787         /* For each floor, find the number of valid chips it contains */
788         for (floor = 0; floor < MAX_FLOORS; floor++) {
789                 ret = 1;
790                 numchips[floor] = 0;
791                 for (chip = 0; chip < maxchips && ret != 0; chip++) {
792
793                         ret = DoC_IdentChip(this, floor, chip);
794                         if (ret) {
795                                 numchips[floor]++;
796                                 this->numchips++;
797                         }
798                 }
799         }
800
801         /* If there are none at all that we recognise, bail */
802         if (!this->numchips) {
803                 puts ("No flash chips recognised.\n");
804                 return;
805         }
806
807         /* Allocate an array to hold the information for each chip */
808         this->chips = malloc(sizeof(struct Nand) * this->numchips);
809         if (!this->chips) {
810                 puts ("No memory for allocating chip info structures\n");
811                 return;
812         }
813
814         ret = 0;
815
816         /* Fill out the chip array with {floor, chipno} for each
817          * detected chip in the device. */
818         for (floor = 0; floor < MAX_FLOORS; floor++) {
819                 for (chip = 0; chip < numchips[floor]; chip++) {
820                         this->chips[ret].floor = floor;
821                         this->chips[ret].chip = chip;
822                         this->chips[ret].curadr = 0;
823                         this->chips[ret].curmode = 0x50;
824                         ret++;
825                 }
826         }
827
828         /* Calculate and print the total size of the device */
829         this->totlen = this->numchips * (1 << this->chipshift);
830
831 #ifdef DOC_DEBUG
832         printf("%d flash chips found. Total DiskOnChip size: %ld MB\n",
833                this->numchips, this->totlen >> 20);
834 #endif
835 }
836
837 /* find_boot_record: Find the NFTL Media Header and its Spare copy which contains the
838  *      various device information of the NFTL partition and Bad Unit Table. Update
839  *      the ReplUnitTable[] table accroding to the Bad Unit Table. ReplUnitTable[]
840  *      is used for management of Erase Unit in other routines in nftl.c and nftlmount.c
841  */
842 static int find_boot_record(struct NFTLrecord *nftl)
843 {
844         struct nftl_uci1 h1;
845         struct nftl_oob oob;
846         unsigned int block, boot_record_count = 0;
847         int retlen;
848         u8 buf[SECTORSIZE];
849         struct NFTLMediaHeader *mh = &nftl->MediaHdr;
850         unsigned int i;
851
852         nftl->MediaUnit = BLOCK_NIL;
853         nftl->SpareMediaUnit = BLOCK_NIL;
854
855         /* search for a valid boot record */
856         for (block = 0; block < nftl->nb_blocks; block++) {
857                 int ret;
858
859                 /* Check for ANAND header first. Then can whinge if it's found but later
860                    checks fail */
861                 if ((ret = doc_read_ecc(nftl->mtd, block * nftl->EraseSize, SECTORSIZE,
862                                         (size_t *)&retlen, buf, NULL))) {
863                         static int warncount = 5;
864
865                         if (warncount) {
866                                 printf("Block read at 0x%x failed\n", block * nftl->EraseSize);
867                                 if (!--warncount)
868                                         puts ("Further failures for this block will not be printed\n");
869                         }
870                         continue;
871                 }
872
873                 if (retlen < 6 || memcmp(buf, "ANAND", 6)) {
874                         /* ANAND\0 not found. Continue */
875 #ifdef PSYCHO_DEBUG
876                         printf("ANAND header not found at 0x%x\n", block * nftl->EraseSize);
877 #endif
878                         continue;
879                 }
880
881 #ifdef NFTL_DEBUG
882                 printf("ANAND header found at 0x%x\n", block * nftl->EraseSize);
883 #endif
884
885                 /* To be safer with BIOS, also use erase mark as discriminant */
886                 if ((ret = doc_read_oob(nftl->mtd, block * nftl->EraseSize + SECTORSIZE + 8,
887                                 8, (size_t *)&retlen, (uchar *)&h1) < 0)) {
888 #ifdef NFTL_DEBUG
889                         printf("ANAND header found at 0x%x, but OOB data read failed\n",
890                                block * nftl->EraseSize);
891 #endif
892                         continue;
893                 }
894
895                 /* OK, we like it. */
896
897                 if (boot_record_count) {
898                         /* We've already processed one. So we just check if
899                            this one is the same as the first one we found */
900                         if (memcmp(mh, buf, sizeof(struct NFTLMediaHeader))) {
901 #ifdef NFTL_DEBUG
902                                 printf("NFTL Media Headers at 0x%x and 0x%x disagree.\n",
903                                        nftl->MediaUnit * nftl->EraseSize, block * nftl->EraseSize);
904 #endif
905                                 /* if (debug) Print both side by side */
906                                 return -1;
907                         }
908                         if (boot_record_count == 1)
909                                 nftl->SpareMediaUnit = block;
910
911                         boot_record_count++;
912                         continue;
913                 }
914
915                 /* This is the first we've seen. Copy the media header structure into place */
916                 memcpy(mh, buf, sizeof(struct NFTLMediaHeader));
917
918                 /* Do some sanity checks on it */
919                 if (mh->UnitSizeFactor == 0) {
920 #ifdef NFTL_DEBUG
921                         puts ("UnitSizeFactor 0x00 detected.\n"
922                               "This violates the spec but we think we know what it means...\n");
923 #endif
924                 } else if (mh->UnitSizeFactor != 0xff) {
925                         printf ("Sorry, we don't support UnitSizeFactor "
926                               "of != 1 yet.\n");
927                         return -1;
928                 }
929
930                 nftl->nb_boot_blocks = le16_to_cpu(mh->FirstPhysicalEUN);
931                 if ((nftl->nb_boot_blocks + 2) >= nftl->nb_blocks) {
932                         printf ("NFTL Media Header sanity check failed:\n"
933                                 "nb_boot_blocks (%d) + 2 > nb_blocks (%d)\n",
934                                 nftl->nb_boot_blocks, nftl->nb_blocks);
935                         return -1;
936                 }
937
938                 nftl->numvunits = le32_to_cpu(mh->FormattedSize) / nftl->EraseSize;
939                 if (nftl->numvunits > (nftl->nb_blocks - nftl->nb_boot_blocks - 2)) {
940                         printf ("NFTL Media Header sanity check failed:\n"
941                                 "numvunits (%d) > nb_blocks (%d) - nb_boot_blocks(%d) - 2\n",
942                                 nftl->numvunits,
943                                 nftl->nb_blocks,
944                                 nftl->nb_boot_blocks);
945                         return -1;
946                 }
947
948                 nftl->nr_sects  = nftl->numvunits * (nftl->EraseSize / SECTORSIZE);
949
950                 /* If we're not using the last sectors in the device for some reason,
951                    reduce nb_blocks accordingly so we forget they're there */
952                 nftl->nb_blocks = le16_to_cpu(mh->NumEraseUnits) + le16_to_cpu(mh->FirstPhysicalEUN);
953
954                 /* read the Bad Erase Unit Table and modify ReplUnitTable[] accordingly */
955                 for (i = 0; i < nftl->nb_blocks; i++) {
956                         if ((i & (SECTORSIZE - 1)) == 0) {
957                                 /* read one sector for every SECTORSIZE of blocks */
958                                 if ((ret = doc_read_ecc(nftl->mtd, block * nftl->EraseSize +
959                                                        i + SECTORSIZE, SECTORSIZE,
960                                                        (size_t *)&retlen, buf, (uchar *)&oob)) < 0) {
961                                         puts ("Read of bad sector table failed\n");
962                                         return -1;
963                                 }
964                         }
965                         /* mark the Bad Erase Unit as RESERVED in ReplUnitTable */
966                         if (buf[i & (SECTORSIZE - 1)] != 0xff)
967                                 nftl->ReplUnitTable[i] = BLOCK_RESERVED;
968                 }
969
970                 nftl->MediaUnit = block;
971                 boot_record_count++;
972
973         } /* foreach (block) */
974
975         return boot_record_count?0:-1;
976 }
977
978 /* This routine is made available to other mtd code via
979  * inter_module_register.  It must only be accessed through
980  * inter_module_get which will bump the use count of this module.  The
981  * addresses passed back in mtd are valid as long as the use count of
982  * this module is non-zero, i.e. between inter_module_get and
983  * inter_module_put.  Keith Owens <kaos@ocs.com.au> 29 Oct 2000.
984  */
985 static void DoC2k_init(struct DiskOnChip* this)
986 {
987         struct NFTLrecord *nftl;
988
989         switch (this->ChipID) {
990         case DOC_ChipID_Doc2k:
991                 this->name = "DiskOnChip 2000";
992                 this->ioreg = DoC_2k_CDSN_IO;
993                 break;
994         case DOC_ChipID_DocMil:
995                 this->name = "DiskOnChip Millennium";
996                 this->ioreg = DoC_Mil_CDSN_IO;
997                 break;
998         }
999
1000 #ifdef DOC_DEBUG
1001         printf("%s found at address 0x%lX\n", this->name,
1002                this->physadr);
1003 #endif
1004
1005         this->totlen = 0;
1006         this->numchips = 0;
1007
1008         this->curfloor = -1;
1009         this->curchip = -1;
1010
1011         /* Ident all the chips present. */
1012         DoC_ScanChips(this);
1013         if ((!this->numchips) || (!this->chips))
1014                 return;
1015
1016         nftl = &this->nftl;
1017
1018         /* Get physical parameters */
1019         nftl->EraseSize = this->erasesize;
1020         nftl->nb_blocks = this->totlen / this->erasesize;
1021         nftl->mtd = this;
1022
1023         if (find_boot_record(nftl) != 0)
1024                 this->nftl_found = 0;
1025         else
1026                 this->nftl_found = 1;
1027
1028         printf("%s @ 0x%lX, %ld MB\n", this->name, this->physadr, this->totlen >> 20);
1029 }
1030
1031 int doc_read_ecc(struct DiskOnChip* this, loff_t from, size_t len,
1032                  size_t * retlen, u_char * buf, u_char * eccbuf)
1033 {
1034         unsigned long docptr;
1035         struct Nand *mychip;
1036         unsigned char syndrome[6];
1037         volatile char dummy;
1038         int i, len256 = 0, ret=0;
1039
1040         docptr = this->virtadr;
1041
1042         /* Don't allow read past end of device */
1043         if (from >= this->totlen) {
1044                 puts ("Out of flash\n");
1045                 return DOC_EINVAL;
1046         }
1047
1048         /* Don't allow a single read to cross a 512-byte block boundary */
1049         if (from + len > ((from | 0x1ff) + 1))
1050                 len = ((from | 0x1ff) + 1) - from;
1051
1052         /* The ECC will not be calculated correctly if less than 512 is read */
1053         if (len != 0x200 && eccbuf)
1054                 printf("ECC needs a full sector read (adr: %lx size %lx)\n",
1055                        (long) from, (long) len);
1056
1057 #ifdef PSYCHO_DEBUG
1058         printf("DoC_Read (adr: %lx size %lx)\n", (long) from, (long) len);
1059 #endif
1060
1061         /* Find the chip which is to be used and select it */
1062         mychip = &this->chips[shr(from, this->chipshift)];
1063
1064         if (this->curfloor != mychip->floor) {
1065                 DoC_SelectFloor(this, mychip->floor);
1066                 DoC_SelectChip(this, mychip->chip);
1067         } else if (this->curchip != mychip->chip) {
1068                 DoC_SelectChip(this, mychip->chip);
1069         }
1070
1071         this->curfloor = mychip->floor;
1072         this->curchip = mychip->chip;
1073
1074         DoC_Command(this,
1075                     (!this->page256
1076                      && (from & 0x100)) ? NAND_CMD_READ1 : NAND_CMD_READ0,
1077                     CDSN_CTRL_WP);
1078         DoC_Address(this, ADDR_COLUMN_PAGE, from, CDSN_CTRL_WP,
1079                     CDSN_CTRL_ECC_IO);
1080
1081         if (eccbuf) {
1082                 /* Prime the ECC engine */
1083                 WriteDOC(DOC_ECC_RESET, docptr, ECCConf);
1084                 WriteDOC(DOC_ECC_EN, docptr, ECCConf);
1085         } else {
1086                 /* disable the ECC engine */
1087                 WriteDOC(DOC_ECC_RESET, docptr, ECCConf);
1088                 WriteDOC(DOC_ECC_DIS, docptr, ECCConf);
1089         }
1090
1091         /* treat crossing 256-byte sector for 2M x 8bits devices */
1092         if (this->page256 && from + len > (from | 0xff) + 1) {
1093                 len256 = (from | 0xff) + 1 - from;
1094                 DoC_ReadBuf(this, buf, len256);
1095
1096                 DoC_Command(this, NAND_CMD_READ0, CDSN_CTRL_WP);
1097                 DoC_Address(this, ADDR_COLUMN_PAGE, from + len256,
1098                             CDSN_CTRL_WP, CDSN_CTRL_ECC_IO);
1099         }
1100
1101         DoC_ReadBuf(this, &buf[len256], len - len256);
1102
1103         /* Let the caller know we completed it */
1104         *retlen = len;
1105
1106         if (eccbuf) {
1107                 /* Read the ECC data through the DiskOnChip ECC logic */
1108                 /* Note: this will work even with 2M x 8bit devices as   */
1109                 /*       they have 8 bytes of OOB per 256 page. mf.      */
1110                 DoC_ReadBuf(this, eccbuf, 6);
1111
1112                 /* Flush the pipeline */
1113                 if (DoC_is_Millennium(this)) {
1114                         dummy = ReadDOC(docptr, ECCConf);
1115                         dummy = ReadDOC(docptr, ECCConf);
1116                         i = ReadDOC(docptr, ECCConf);
1117                 } else {
1118                         dummy = ReadDOC(docptr, 2k_ECCStatus);
1119                         dummy = ReadDOC(docptr, 2k_ECCStatus);
1120                         i = ReadDOC(docptr, 2k_ECCStatus);
1121                 }
1122
1123                 /* Check the ECC Status */
1124                 if (i & 0x80) {
1125                         int nb_errors;
1126                         /* There was an ECC error */
1127 #ifdef ECC_DEBUG
1128                         printf("DiskOnChip ECC Error: Read at %lx\n", (long)from);
1129 #endif
1130                         /* Read the ECC syndrom through the DiskOnChip ECC logic.
1131                            These syndrome will be all ZERO when there is no error */
1132                         for (i = 0; i < 6; i++) {
1133                                 syndrome[i] =
1134                                     ReadDOC(docptr, ECCSyndrome0 + i);
1135                         }
1136                         nb_errors = doc_decode_ecc(buf, syndrome);
1137
1138 #ifdef ECC_DEBUG
1139                         printf("Errors corrected: %x\n", nb_errors);
1140 #endif
1141                         if (nb_errors < 0) {
1142                                 /* We return error, but have actually done the read. Not that
1143                                    this can be told to user-space, via sys_read(), but at least
1144                                    MTD-aware stuff can know about it by checking *retlen */
1145                                 printf("ECC Errors at %lx\n", (long)from);
1146                                 ret = DOC_EECC;
1147                         }
1148                 }
1149
1150 #ifdef PSYCHO_DEBUG
1151                 printf("ECC DATA at %lxB: %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X\n",
1152                              (long)from, eccbuf[0], eccbuf[1], eccbuf[2],
1153                              eccbuf[3], eccbuf[4], eccbuf[5]);
1154 #endif
1155
1156                 /* disable the ECC engine */
1157                 WriteDOC(DOC_ECC_DIS, docptr , ECCConf);
1158         }
1159
1160         /* according to 11.4.1, we need to wait for the busy line
1161          * drop if we read to the end of the page.  */
1162         if(0 == ((from + *retlen) & 0x1ff))
1163         {
1164             DoC_WaitReady(this);
1165         }
1166
1167         return ret;
1168 }
1169
1170 int doc_write_ecc(struct DiskOnChip* this, loff_t to, size_t len,
1171                   size_t * retlen, const u_char * buf,
1172                   u_char * eccbuf)
1173 {
1174         int di; /* Yes, DI is a hangover from when I was disassembling the binary driver */
1175         unsigned long docptr;
1176         volatile char dummy;
1177         int len256 = 0;
1178         struct Nand *mychip;
1179
1180         docptr = this->virtadr;
1181
1182         /* Don't allow write past end of device */
1183         if (to >= this->totlen) {
1184                 puts ("Out of flash\n");
1185                 return DOC_EINVAL;
1186         }
1187
1188         /* Don't allow a single write to cross a 512-byte block boundary */
1189         if (to + len > ((to | 0x1ff) + 1))
1190                 len = ((to | 0x1ff) + 1) - to;
1191
1192         /* The ECC will not be calculated correctly if less than 512 is written */
1193         if (len != 0x200 && eccbuf)
1194                 printf("ECC needs a full sector write (adr: %lx size %lx)\n",
1195                        (long) to, (long) len);
1196
1197         /* printf("DoC_Write (adr: %lx size %lx)\n", (long) to, (long) len); */
1198
1199         /* Find the chip which is to be used and select it */
1200         mychip = &this->chips[shr(to, this->chipshift)];
1201
1202         if (this->curfloor != mychip->floor) {
1203                 DoC_SelectFloor(this, mychip->floor);
1204                 DoC_SelectChip(this, mychip->chip);
1205         } else if (this->curchip != mychip->chip) {
1206                 DoC_SelectChip(this, mychip->chip);
1207         }
1208
1209         this->curfloor = mychip->floor;
1210         this->curchip = mychip->chip;
1211
1212         /* Set device to main plane of flash */
1213         DoC_Command(this, NAND_CMD_RESET, CDSN_CTRL_WP);
1214         DoC_Command(this,
1215                     (!this->page256
1216                      && (to & 0x100)) ? NAND_CMD_READ1 : NAND_CMD_READ0,
1217                     CDSN_CTRL_WP);
1218
1219         DoC_Command(this, NAND_CMD_SEQIN, 0);
1220         DoC_Address(this, ADDR_COLUMN_PAGE, to, 0, CDSN_CTRL_ECC_IO);
1221
1222         if (eccbuf) {
1223                 /* Prime the ECC engine */
1224                 WriteDOC(DOC_ECC_RESET, docptr, ECCConf);
1225                 WriteDOC(DOC_ECC_EN | DOC_ECC_RW, docptr, ECCConf);
1226         } else {
1227                 /* disable the ECC engine */
1228                 WriteDOC(DOC_ECC_RESET, docptr, ECCConf);
1229                 WriteDOC(DOC_ECC_DIS, docptr, ECCConf);
1230         }
1231
1232         /* treat crossing 256-byte sector for 2M x 8bits devices */
1233         if (this->page256 && to + len > (to | 0xff) + 1) {
1234                 len256 = (to | 0xff) + 1 - to;
1235                 DoC_WriteBuf(this, buf, len256);
1236
1237                 DoC_Command(this, NAND_CMD_PAGEPROG, 0);
1238
1239                 DoC_Command(this, NAND_CMD_STATUS, CDSN_CTRL_WP);
1240                 /* There's an implicit DoC_WaitReady() in DoC_Command */
1241
1242                 dummy = ReadDOC(docptr, CDSNSlowIO);
1243                 DoC_Delay(this, 2);
1244
1245                 if (ReadDOC_(docptr, this->ioreg) & 1) {
1246                         puts ("Error programming flash\n");
1247                         /* Error in programming */
1248                         *retlen = 0;
1249                         return DOC_EIO;
1250                 }
1251
1252                 DoC_Command(this, NAND_CMD_SEQIN, 0);
1253                 DoC_Address(this, ADDR_COLUMN_PAGE, to + len256, 0,
1254                             CDSN_CTRL_ECC_IO);
1255         }
1256
1257         DoC_WriteBuf(this, &buf[len256], len - len256);
1258
1259         if (eccbuf) {
1260                 WriteDOC(CDSN_CTRL_ECC_IO | CDSN_CTRL_CE, docptr,
1261                          CDSNControl);
1262
1263                 if (DoC_is_Millennium(this)) {
1264                         WriteDOC(0, docptr, NOP);
1265                         WriteDOC(0, docptr, NOP);
1266                         WriteDOC(0, docptr, NOP);
1267                 } else {
1268                         WriteDOC_(0, docptr, this->ioreg);
1269                         WriteDOC_(0, docptr, this->ioreg);
1270                         WriteDOC_(0, docptr, this->ioreg);
1271                 }
1272
1273                 /* Read the ECC data through the DiskOnChip ECC logic */
1274                 for (di = 0; di < 6; di++) {
1275                         eccbuf[di] = ReadDOC(docptr, ECCSyndrome0 + di);
1276                 }
1277
1278                 /* Reset the ECC engine */
1279                 WriteDOC(DOC_ECC_DIS, docptr, ECCConf);
1280
1281 #ifdef PSYCHO_DEBUG
1282                 printf
1283                     ("OOB data at %lx is %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X\n",
1284                      (long) to, eccbuf[0], eccbuf[1], eccbuf[2], eccbuf[3],
1285                      eccbuf[4], eccbuf[5]);
1286 #endif
1287         }
1288
1289         DoC_Command(this, NAND_CMD_PAGEPROG, 0);
1290
1291         DoC_Command(this, NAND_CMD_STATUS, CDSN_CTRL_WP);
1292         /* There's an implicit DoC_WaitReady() in DoC_Command */
1293
1294         dummy = ReadDOC(docptr, CDSNSlowIO);
1295         DoC_Delay(this, 2);
1296
1297         if (ReadDOC_(docptr, this->ioreg) & 1) {
1298                 puts ("Error programming flash\n");
1299                 /* Error in programming */
1300                 *retlen = 0;
1301                 return DOC_EIO;
1302         }
1303
1304         /* Let the caller know we completed it */
1305         *retlen = len;
1306
1307         if (eccbuf) {
1308                 unsigned char x[8];
1309                 size_t dummy;
1310                 int ret;
1311
1312                 /* Write the ECC data to flash */
1313                 for (di=0; di<6; di++)
1314                         x[di] = eccbuf[di];
1315
1316                 x[6]=0x55;
1317                 x[7]=0x55;
1318
1319                 ret = doc_write_oob(this, to, 8, &dummy, x);
1320                 return ret;
1321         }
1322         return 0;
1323 }
1324
1325 int doc_read_oob(struct DiskOnChip* this, loff_t ofs, size_t len,
1326                  size_t * retlen, u_char * buf)
1327 {
1328         int len256 = 0, ret;
1329         unsigned long docptr;
1330         struct Nand *mychip;
1331
1332         docptr = this->virtadr;
1333
1334         mychip = &this->chips[shr(ofs, this->chipshift)];
1335
1336         if (this->curfloor != mychip->floor) {
1337                 DoC_SelectFloor(this, mychip->floor);
1338                 DoC_SelectChip(this, mychip->chip);
1339         } else if (this->curchip != mychip->chip) {
1340                 DoC_SelectChip(this, mychip->chip);
1341         }
1342         this->curfloor = mychip->floor;
1343         this->curchip = mychip->chip;
1344
1345         /* update address for 2M x 8bit devices. OOB starts on the second */
1346         /* page to maintain compatibility with doc_read_ecc. */
1347         if (this->page256) {
1348                 if (!(ofs & 0x8))
1349                         ofs += 0x100;
1350                 else
1351                         ofs -= 0x8;
1352         }
1353
1354         DoC_Command(this, NAND_CMD_READOOB, CDSN_CTRL_WP);
1355         DoC_Address(this, ADDR_COLUMN_PAGE, ofs, CDSN_CTRL_WP, 0);
1356
1357         /* treat crossing 8-byte OOB data for 2M x 8bit devices */
1358         /* Note: datasheet says it should automaticaly wrap to the */
1359         /*       next OOB block, but it didn't work here. mf.      */
1360         if (this->page256 && ofs + len > (ofs | 0x7) + 1) {
1361                 len256 = (ofs | 0x7) + 1 - ofs;
1362                 DoC_ReadBuf(this, buf, len256);
1363
1364                 DoC_Command(this, NAND_CMD_READOOB, CDSN_CTRL_WP);
1365                 DoC_Address(this, ADDR_COLUMN_PAGE, ofs & (~0x1ff),
1366                             CDSN_CTRL_WP, 0);
1367         }
1368
1369         DoC_ReadBuf(this, &buf[len256], len - len256);
1370
1371         *retlen = len;
1372         /* Reading the full OOB data drops us off of the end of the page,
1373          * causing the flash device to go into busy mode, so we need
1374          * to wait until ready 11.4.1 and Toshiba TC58256FT docs */
1375
1376         ret = DoC_WaitReady(this);
1377
1378         return ret;
1379
1380 }
1381
1382 int doc_write_oob(struct DiskOnChip* this, loff_t ofs, size_t len,
1383                   size_t * retlen, const u_char * buf)
1384 {
1385         int len256 = 0;
1386         unsigned long docptr = this->virtadr;
1387         struct Nand *mychip = &this->chips[shr(ofs, this->chipshift)];
1388         volatile int dummy;
1389
1390 #ifdef PSYCHO_DEBUG
1391         printf("doc_write_oob(%lx, %d): %2.2X %2.2X %2.2X %2.2X ... %2.2X %2.2X .. %2.2X %2.2X\n",
1392                (long)ofs, len, buf[0], buf[1], buf[2], buf[3],
1393                buf[8], buf[9], buf[14],buf[15]);
1394 #endif
1395
1396         /* Find the chip which is to be used and select it */
1397         if (this->curfloor != mychip->floor) {
1398                 DoC_SelectFloor(this, mychip->floor);
1399                 DoC_SelectChip(this, mychip->chip);
1400         } else if (this->curchip != mychip->chip) {
1401                 DoC_SelectChip(this, mychip->chip);
1402         }
1403         this->curfloor = mychip->floor;
1404         this->curchip = mychip->chip;
1405
1406         /* disable the ECC engine */
1407         WriteDOC (DOC_ECC_RESET, docptr, ECCConf);
1408         WriteDOC (DOC_ECC_DIS, docptr, ECCConf);
1409
1410         /* Reset the chip, see Software Requirement 11.4 item 1. */
1411         DoC_Command(this, NAND_CMD_RESET, CDSN_CTRL_WP);
1412
1413         /* issue the Read2 command to set the pointer to the Spare Data Area. */
1414         DoC_Command(this, NAND_CMD_READOOB, CDSN_CTRL_WP);
1415
1416         /* update address for 2M x 8bit devices. OOB starts on the second */
1417         /* page to maintain compatibility with doc_read_ecc. */
1418         if (this->page256) {
1419                 if (!(ofs & 0x8))
1420                         ofs += 0x100;
1421                 else
1422                         ofs -= 0x8;
1423         }
1424
1425         /* issue the Serial Data In command to initial the Page Program process */
1426         DoC_Command(this, NAND_CMD_SEQIN, 0);
1427         DoC_Address(this, ADDR_COLUMN_PAGE, ofs, 0, 0);
1428
1429         /* treat crossing 8-byte OOB data for 2M x 8bit devices */
1430         /* Note: datasheet says it should automaticaly wrap to the */
1431         /*       next OOB block, but it didn't work here. mf.      */
1432         if (this->page256 && ofs + len > (ofs | 0x7) + 1) {
1433                 len256 = (ofs | 0x7) + 1 - ofs;
1434                 DoC_WriteBuf(this, buf, len256);
1435
1436                 DoC_Command(this, NAND_CMD_PAGEPROG, 0);
1437                 DoC_Command(this, NAND_CMD_STATUS, 0);
1438                 /* DoC_WaitReady() is implicit in DoC_Command */
1439
1440                 dummy = ReadDOC(docptr, CDSNSlowIO);
1441                 DoC_Delay(this, 2);
1442
1443                 if (ReadDOC_(docptr, this->ioreg) & 1) {
1444                         puts ("Error programming oob data\n");
1445                         /* There was an error */
1446                         *retlen = 0;
1447                         return DOC_EIO;
1448                 }
1449                 DoC_Command(this, NAND_CMD_SEQIN, 0);
1450                 DoC_Address(this, ADDR_COLUMN_PAGE, ofs & (~0x1ff), 0, 0);
1451         }
1452
1453         DoC_WriteBuf(this, &buf[len256], len - len256);
1454
1455         DoC_Command(this, NAND_CMD_PAGEPROG, 0);
1456         DoC_Command(this, NAND_CMD_STATUS, 0);
1457         /* DoC_WaitReady() is implicit in DoC_Command */
1458
1459         dummy = ReadDOC(docptr, CDSNSlowIO);
1460         DoC_Delay(this, 2);
1461
1462         if (ReadDOC_(docptr, this->ioreg) & 1) {
1463                 puts ("Error programming oob data\n");
1464                 /* There was an error */
1465                 *retlen = 0;
1466                 return DOC_EIO;
1467         }
1468
1469         *retlen = len;
1470         return 0;
1471
1472 }
1473
1474 int doc_erase(struct DiskOnChip* this, loff_t ofs, size_t len)
1475 {
1476         volatile int dummy;
1477         unsigned long docptr;
1478         struct Nand *mychip;
1479
1480         if (ofs & (this->erasesize-1) || len & (this->erasesize-1)) {
1481                 puts ("Offset and size must be sector aligned\n");
1482                 return DOC_EINVAL;
1483         }
1484
1485         docptr = this->virtadr;
1486
1487         /* FIXME: Do this in the background. Use timers or schedule_task() */
1488         while(len) {
1489                 mychip = &this->chips[shr(ofs, this->chipshift)];
1490
1491                 if (this->curfloor != mychip->floor) {
1492                         DoC_SelectFloor(this, mychip->floor);
1493                         DoC_SelectChip(this, mychip->chip);
1494                 } else if (this->curchip != mychip->chip) {
1495                         DoC_SelectChip(this, mychip->chip);
1496                 }
1497                 this->curfloor = mychip->floor;
1498                 this->curchip = mychip->chip;
1499
1500                 DoC_Command(this, NAND_CMD_ERASE1, 0);
1501                 DoC_Address(this, ADDR_PAGE, ofs, 0, 0);
1502                 DoC_Command(this, NAND_CMD_ERASE2, 0);
1503
1504                 DoC_Command(this, NAND_CMD_STATUS, CDSN_CTRL_WP);
1505
1506                 dummy = ReadDOC(docptr, CDSNSlowIO);
1507                 DoC_Delay(this, 2);
1508
1509                 if (ReadDOC_(docptr, this->ioreg) & 1) {
1510                         printf("Error erasing at 0x%lx\n", (long)ofs);
1511                         /* There was an error */
1512                         goto callback;
1513                 }
1514                 ofs += this->erasesize;
1515                 len -= this->erasesize;
1516         }
1517
1518  callback:
1519         return 0;
1520 }
1521
1522 static inline int doccheck(unsigned long potential, unsigned long physadr)
1523 {
1524         unsigned long window=potential;
1525         unsigned char tmp, ChipID;
1526 #ifndef DOC_PASSIVE_PROBE
1527         unsigned char tmp2;
1528 #endif
1529
1530         /* Routine copied from the Linux DOC driver */
1531
1532 #ifdef CONFIG_SYS_DOCPROBE_55AA
1533         /* Check for 0x55 0xAA signature at beginning of window,
1534            this is no longer true once we remove the IPL (for Millennium */
1535         if (ReadDOC(window, Sig1) != 0x55 || ReadDOC(window, Sig2) != 0xaa)
1536                 return 0;
1537 #endif /* CONFIG_SYS_DOCPROBE_55AA */
1538
1539 #ifndef DOC_PASSIVE_PROBE
1540         /* It's not possible to cleanly detect the DiskOnChip - the
1541          * bootup procedure will put the device into reset mode, and
1542          * it's not possible to talk to it without actually writing
1543          * to the DOCControl register. So we store the current contents
1544          * of the DOCControl register's location, in case we later decide
1545          * that it's not a DiskOnChip, and want to put it back how we
1546          * found it.
1547          */
1548         tmp2 = ReadDOC(window, DOCControl);
1549
1550         /* Reset the DiskOnChip ASIC */
1551         WriteDOC(DOC_MODE_CLR_ERR | DOC_MODE_MDWREN | DOC_MODE_RESET,
1552                  window, DOCControl);
1553         WriteDOC(DOC_MODE_CLR_ERR | DOC_MODE_MDWREN | DOC_MODE_RESET,
1554                  window, DOCControl);
1555
1556         /* Enable the DiskOnChip ASIC */
1557         WriteDOC(DOC_MODE_CLR_ERR | DOC_MODE_MDWREN | DOC_MODE_NORMAL,
1558                  window, DOCControl);
1559         WriteDOC(DOC_MODE_CLR_ERR | DOC_MODE_MDWREN | DOC_MODE_NORMAL,
1560                  window, DOCControl);
1561 #endif /* !DOC_PASSIVE_PROBE */
1562
1563         ChipID = ReadDOC(window, ChipID);
1564
1565         switch (ChipID) {
1566         case DOC_ChipID_Doc2k:
1567                 /* Check the TOGGLE bit in the ECC register */
1568                 tmp = ReadDOC(window, 2k_ECCStatus) & DOC_TOGGLE_BIT;
1569                 if ((ReadDOC(window, 2k_ECCStatus) & DOC_TOGGLE_BIT) != tmp)
1570                                 return ChipID;
1571                 break;
1572
1573         case DOC_ChipID_DocMil:
1574                 /* Check the TOGGLE bit in the ECC register */
1575                 tmp = ReadDOC(window, ECCConf) & DOC_TOGGLE_BIT;
1576                 if ((ReadDOC(window, ECCConf) & DOC_TOGGLE_BIT) != tmp)
1577                                 return ChipID;
1578                 break;
1579
1580         default:
1581 #ifndef CONFIG_SYS_DOCPROBE_55AA
1582 /*
1583  * if the ID isn't the DoC2000 or DoCMillenium ID, so we can assume
1584  * the DOC is missing
1585  */
1586 # if 0
1587                 printf("Possible DiskOnChip with unknown ChipID %2.2X found at 0x%lx\n",
1588                        ChipID, physadr);
1589 # endif
1590 #endif
1591 #ifndef DOC_PASSIVE_PROBE
1592                 /* Put back the contents of the DOCControl register, in case it's not
1593                  * actually a DiskOnChip.
1594                  */
1595                 WriteDOC(tmp2, window, DOCControl);
1596 #endif
1597                 return 0;
1598         }
1599
1600         puts ("DiskOnChip failed TOGGLE test, dropping.\n");
1601
1602 #ifndef DOC_PASSIVE_PROBE
1603         /* Put back the contents of the DOCControl register: it's not a DiskOnChip */
1604         WriteDOC(tmp2, window, DOCControl);
1605 #endif
1606         return 0;
1607 }
1608
1609 void doc_probe(unsigned long physadr)
1610 {
1611         struct DiskOnChip *this = NULL;
1612         int i=0, ChipID;
1613
1614         if ((ChipID = doccheck(physadr, physadr))) {
1615
1616                 for (i=0; i<CONFIG_SYS_MAX_DOC_DEVICE; i++) {
1617                         if (doc_dev_desc[i].ChipID == DOC_ChipID_UNKNOWN) {
1618                                 this = doc_dev_desc + i;
1619                                 break;
1620                         }
1621                 }
1622
1623                 if (!this) {
1624                         puts ("Cannot allocate memory for data structures.\n");
1625                         return;
1626                 }
1627
1628                 if (curr_device == -1)
1629                         curr_device = i;
1630
1631                 memset((char *)this, 0, sizeof(struct DiskOnChip));
1632
1633                 this->virtadr = physadr;
1634                 this->physadr = physadr;
1635                 this->ChipID = ChipID;
1636
1637                 DoC2k_init(this);
1638         } else {
1639                 puts ("No DiskOnChip found\n");
1640         }
1641 }
1642 #else
1643 void doc_probe(unsigned long physadr) {}
1644 #endif