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