Merge to Fedora kernel-2.6.7-1.494 and VServer 1.9.1.12. Fix some previous merge...
[linux-2.6.git] / drivers / mtd / inftlmount.c
1 /* 
2  * inftlmount.c -- INFTL mount code with extensive checks.
3  *
4  * Author: Greg Ungerer (gerg@snapgear.com)
5  * (C) Copyright 2002-2003, Greg Ungerer (gerg@snapgear.com)
6  *
7  * Based heavily on the nftlmount.c code which is:
8  * Author: Fabrice Bellard (fabrice.bellard@netgem.com) 
9  * Copyright (C) 2000 Netgem S.A.
10  *
11  * $Id: inftlmount.c,v 1.13 2004/06/28 16:06:36 dbrown Exp $
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26  */
27
28 #include <linux/kernel.h>
29 #include <linux/module.h>
30 #include <asm/errno.h>
31 #include <asm/io.h>
32 #include <asm/uaccess.h>
33 #include <linux/miscdevice.h>
34 #include <linux/pci.h>
35 #include <linux/delay.h>
36 #include <linux/slab.h>
37 #include <linux/sched.h>
38 #include <linux/init.h>
39 #include <linux/mtd/mtd.h>
40 #include <linux/mtd/nftl.h>
41 #include <linux/mtd/inftl.h>
42 #include <linux/mtd/compatmac.h>
43
44 char inftlmountrev[]="$Revision: 1.13 $";
45
46 /*
47  * find_boot_record: Find the INFTL Media Header and its Spare copy which
48  *      contains the various device information of the INFTL partition and
49  *      Bad Unit Table. Update the PUtable[] table according to the Bad
50  *      Unit Table. PUtable[] is used for management of Erase Unit in
51  *      other routines in inftlcore.c and inftlmount.c.
52  */
53 static int find_boot_record(struct INFTLrecord *inftl)
54 {
55         struct inftl_unittail h1;
56         //struct inftl_oob oob;
57         unsigned int i, block;
58         u8 buf[SECTORSIZE];
59         struct INFTLMediaHeader *mh = &inftl->MediaHdr;
60         struct INFTLPartition *ip;
61         int retlen;
62
63         DEBUG(MTD_DEBUG_LEVEL3, "INFTL: find_boot_record(inftl=0x%x)\n",
64                 (int)inftl);
65
66         /*
67          * Assume logical EraseSize == physical erasesize for starting the
68          * scan. We'll sort it out later if we find a MediaHeader which says
69          * otherwise.
70          */
71         inftl->EraseSize = inftl->mbd.mtd->erasesize;
72         inftl->nb_blocks = inftl->mbd.mtd->size / inftl->EraseSize;
73
74         inftl->MediaUnit = BLOCK_NIL;
75
76         /* Search for a valid boot record */
77         for (block = 0; block < inftl->nb_blocks; block++) {
78                 int ret;
79
80                 /*
81                  * Check for BNAND header first. Then whinge if it's found
82                  * but later checks fail.
83                  */
84                 ret = MTD_READ(inftl->mbd.mtd, block * inftl->EraseSize,
85                     SECTORSIZE, &retlen, buf);
86                 /* We ignore ret in case the ECC of the MediaHeader is invalid
87                    (which is apparently acceptable) */
88                 if (retlen != SECTORSIZE) {
89                         static int warncount = 5;
90
91                         if (warncount) {
92                                 printk(KERN_WARNING "INFTL: block read at 0x%x "
93                                         "of mtd%d failed: %d\n",
94                                         block * inftl->EraseSize,
95                                         inftl->mbd.mtd->index, ret);
96                                 if (!--warncount)
97                                         printk(KERN_WARNING "INFTL: further "
98                                                 "failures for this block will "
99                                                 "not be printed\n");
100                         }
101                         continue;
102                 }
103
104                 if (retlen < 6 || memcmp(buf, "BNAND", 6)) {
105                         /* BNAND\0 not found. Continue */
106                         continue;
107                 }
108
109                 /* To be safer with BIOS, also use erase mark as discriminant */
110                 if ((ret = MTD_READOOB(inftl->mbd.mtd, block * inftl->EraseSize +
111                     SECTORSIZE + 8, 8, &retlen, (char *)&h1) < 0)) {
112                         printk(KERN_WARNING "INFTL: ANAND header found at "
113                                 "0x%x in mtd%d, but OOB data read failed "
114                                 "(err %d)\n", block * inftl->EraseSize,
115                                 inftl->mbd.mtd->index, ret);
116                         continue;
117                 }
118
119
120                 /*
121                  * This is the first we've seen.
122                  * Copy the media header structure into place.
123                  */
124                 memcpy(mh, buf, sizeof(struct INFTLMediaHeader));
125
126                 /* Read the spare media header at offset 4096 */
127                 MTD_READ(inftl->mbd.mtd, block * inftl->EraseSize + 4096,
128                     SECTORSIZE, &retlen, buf);
129                 if (retlen != SECTORSIZE) {
130                         printk(KERN_WARNING "INFTL: Unable to read spare "
131                                "Media Header\n");
132                         return -1;
133                 }
134                 /* Check if this one is the same as the first one we found. */
135                 if (memcmp(mh, buf, sizeof(struct INFTLMediaHeader))) {
136                         printk(KERN_WARNING "INFTL: Primary and spare Media "
137                                "Headers disagree.\n");
138                         return -1;
139                 }
140
141                 mh->NoOfBootImageBlocks = le32_to_cpu(mh->NoOfBootImageBlocks);
142                 mh->NoOfBinaryPartitions = le32_to_cpu(mh->NoOfBinaryPartitions);
143                 mh->NoOfBDTLPartitions = le32_to_cpu(mh->NoOfBDTLPartitions);
144                 mh->BlockMultiplierBits = le32_to_cpu(mh->BlockMultiplierBits);
145                 mh->FormatFlags = le32_to_cpu(mh->FormatFlags);
146                 mh->PercentUsed = le32_to_cpu(mh->PercentUsed);
147
148 #ifdef CONFIG_MTD_DEBUG_VERBOSE
149                 if (CONFIG_MTD_DEBUG_VERBOSE >= 2) {
150                         printk("INFTL: Media Header ->\n"
151                                 "    bootRecordID          = %s\n"
152                                 "    NoOfBootImageBlocks   = %d\n"
153                                 "    NoOfBinaryPartitions  = %d\n"
154                                 "    NoOfBDTLPartitions    = %d\n"
155                                 "    BlockMultiplerBits    = %d\n"
156                                 "    FormatFlgs            = %d\n"
157                                 "    OsakVersion           = 0x%x\n"
158                                 "    PercentUsed           = %d\n",
159                                 mh->bootRecordID, mh->NoOfBootImageBlocks,
160                                 mh->NoOfBinaryPartitions,
161                                 mh->NoOfBDTLPartitions,
162                                 mh->BlockMultiplierBits, mh->FormatFlags,
163                                 mh->OsakVersion, mh->PercentUsed);
164                 }
165 #endif
166
167                 if (mh->NoOfBDTLPartitions == 0) {
168                         printk(KERN_WARNING "INFTL: Media Header sanity check "
169                                 "failed: NoOfBDTLPartitions (%d) == 0, "
170                                 "must be at least 1\n", mh->NoOfBDTLPartitions);
171                         return -1;
172                 }
173
174                 if ((mh->NoOfBDTLPartitions + mh->NoOfBinaryPartitions) > 4) {
175                         printk(KERN_WARNING "INFTL: Media Header sanity check "
176                                 "failed: Total Partitions (%d) > 4, "
177                                 "BDTL=%d Binary=%d\n", mh->NoOfBDTLPartitions +
178                                 mh->NoOfBinaryPartitions,
179                                 mh->NoOfBDTLPartitions,
180                                 mh->NoOfBinaryPartitions);
181                         return -1;
182                 }
183
184                 if (mh->BlockMultiplierBits > 1) {
185                         printk(KERN_WARNING "INFTL: sorry, we don't support "
186                                 "UnitSizeFactor 0x%02x\n",
187                                 mh->BlockMultiplierBits);
188                         return -1;
189                 } else if (mh->BlockMultiplierBits == 1) {
190                         printk(KERN_WARNING "INFTL: support for INFTL with "
191                                 "UnitSizeFactor 0x%02x is experimental\n",
192                                 mh->BlockMultiplierBits);
193                         inftl->EraseSize = inftl->mbd.mtd->erasesize <<
194                                 mh->BlockMultiplierBits;
195                         inftl->nb_blocks = inftl->mbd.mtd->size / inftl->EraseSize;
196                         block >>= mh->BlockMultiplierBits;
197                 }
198
199                 /* Scan the partitions */
200                 for (i = 0; (i < 4); i++) {
201                         ip = &mh->Partitions[i];
202                         ip->virtualUnits = le32_to_cpu(ip->virtualUnits);
203                         ip->firstUnit = le32_to_cpu(ip->firstUnit);
204                         ip->lastUnit = le32_to_cpu(ip->lastUnit);
205                         ip->flags = le32_to_cpu(ip->flags);
206                         ip->spareUnits = le32_to_cpu(ip->spareUnits);
207                         ip->Reserved0 = le32_to_cpu(ip->Reserved0);
208
209 #ifdef CONFIG_MTD_DEBUG_VERBOSE
210                         if (CONFIG_MTD_DEBUG_VERBOSE >= 2) {
211                                 printk("    PARTITION[%d] ->\n"
212                                         "        virtualUnits    = %d\n"
213                                         "        firstUnit       = %d\n"
214                                         "        lastUnit        = %d\n"
215                                         "        flags           = 0x%x\n"
216                                         "        spareUnits      = %d\n",
217                                         i, ip->virtualUnits, ip->firstUnit,
218                                         ip->lastUnit, ip->flags,
219                                         ip->spareUnits);
220                         }
221 #endif
222
223                         if (ip->Reserved0 != ip->firstUnit) {
224                                 struct erase_info *instr = &inftl->instr;
225
226                                 /*
227                                  *      Most likely this is using the
228                                  *      undocumented qiuck mount feature.
229                                  *      We don't support that, we will need
230                                  *      to erase the hidden block for full
231                                  *      compatibility.
232                                  */
233                                 instr->addr = ip->Reserved0 * inftl->EraseSize;
234                                 instr->len = inftl->EraseSize;
235                                 MTD_ERASE(inftl->mbd.mtd, instr);
236                         }
237                         if ((ip->lastUnit - ip->firstUnit + 1) < ip->virtualUnits) {
238                                 printk(KERN_WARNING "INFTL: Media Header "
239                                         "Partition %d sanity check failed\n"
240                                         "    firstUnit %d : lastUnit %d  >  "
241                                         "virtualUnits %d\n", i, ip->lastUnit,
242                                         ip->firstUnit, ip->Reserved0);
243                                 return -1;
244                         }
245                         if (ip->Reserved1 != 0) {
246                                 printk(KERN_WARNING "INFTL: Media Header "
247                                         "Partition %d sanity check failed: "
248                                         "Reserved1 %d != 0\n",
249                                         i, ip->Reserved1);
250                                 return -1;
251                         }
252
253                         if (ip->flags & INFTL_BDTL)
254                                 break;
255                 }
256
257                 if (i >= 4) {
258                         printk(KERN_WARNING "INFTL: Media Header Partition "
259                                 "sanity check failed:\n       No partition "
260                                 "marked as Disk Partition\n");
261                         return -1;
262                 }
263
264                 inftl->nb_boot_blocks = ip->firstUnit;
265                 inftl->numvunits = ip->virtualUnits;
266                 if (inftl->numvunits > (inftl->nb_blocks -
267                     inftl->nb_boot_blocks - 2)) {
268                         printk(KERN_WARNING "INFTL: Media Header sanity check "
269                                 "failed:\n        numvunits (%d) > nb_blocks "
270                                 "(%d) - nb_boot_blocks(%d) - 2\n",
271                                 inftl->numvunits, inftl->nb_blocks,
272                                 inftl->nb_boot_blocks);
273                         return -1;
274                 }
275                 
276                 inftl->mbd.size  = inftl->numvunits *
277                         (inftl->EraseSize / SECTORSIZE);
278
279                 /*
280                  * Block count is set to last used EUN (we won't need to keep
281                  * any meta-data past that point).
282                  */
283                 inftl->firstEUN = ip->firstUnit;
284                 inftl->lastEUN = ip->lastUnit;
285                 inftl->nb_blocks = ip->lastUnit + 1;
286
287                 /* Memory alloc */
288                 inftl->PUtable = kmalloc(inftl->nb_blocks * sizeof(u16), GFP_KERNEL);
289                 if (!inftl->PUtable) {
290                         printk(KERN_WARNING "INFTL: allocation of PUtable "
291                                 "failed (%d bytes)\n",
292                                 inftl->nb_blocks * sizeof(u16));
293                         return -ENOMEM;
294                 }
295
296                 inftl->VUtable = kmalloc(inftl->nb_blocks * sizeof(u16), GFP_KERNEL);
297                 if (!inftl->VUtable) {
298                         kfree(inftl->PUtable);
299                         printk(KERN_WARNING "INFTL: allocation of VUtable "
300                                 "failed (%d bytes)\n",
301                                 inftl->nb_blocks * sizeof(u16));
302                         return -ENOMEM;
303                 }
304                 
305                 /* Mark the blocks before INFTL MediaHeader as reserved */
306                 for (i = 0; i < inftl->nb_boot_blocks; i++)
307                         inftl->PUtable[i] = BLOCK_RESERVED;
308                 /* Mark all remaining blocks as potentially containing data */
309                 for (; i < inftl->nb_blocks; i++)
310                         inftl->PUtable[i] = BLOCK_NOTEXPLORED;
311
312                 /* Mark this boot record (NFTL MediaHeader) block as reserved */
313                 inftl->PUtable[block] = BLOCK_RESERVED;
314
315                 /* Read Bad Erase Unit Table and modify PUtable[] accordingly */
316                 for (i = 0; i < inftl->nb_blocks; i++) {
317                         int physblock;
318                         /* If any of the physical eraseblocks are bad, don't
319                            use the unit. */
320                         for (physblock = 0; physblock < inftl->EraseSize; physblock += inftl->mbd.mtd->erasesize) {
321                                 if (inftl->mbd.mtd->block_isbad(inftl->mbd.mtd, i * inftl->EraseSize + physblock))
322                                         inftl->PUtable[i] = BLOCK_RESERVED;
323                         }
324                 }
325
326                 inftl->MediaUnit = block;
327                 return 0;
328         }
329
330         /* Not found. */
331         return -1;
332 }
333
334 static int memcmpb(void *a, int c, int n)
335 {
336         int i;
337         for (i = 0; i < n; i++) {
338                 if (c != ((unsigned char *)a)[i])
339                         return 1;
340         }
341         return 0;
342 }
343
344 /*
345  * check_free_sector: check if a free sector is actually FREE,
346  *      i.e. All 0xff in data and oob area.
347  */
348 static int check_free_sectors(struct INFTLrecord *inftl, unsigned int address,
349         int len, int check_oob)
350 {
351         int i, retlen;
352         u8 buf[SECTORSIZE + inftl->mbd.mtd->oobsize];
353
354         DEBUG(MTD_DEBUG_LEVEL3, "INFTL: check_free_sectors(inftl=0x%x,"
355                 "address=0x%x,len=%d,check_oob=%d)\n", (int)inftl,
356                 address, len, check_oob);
357
358         for (i = 0; i < len; i += SECTORSIZE) {
359                 if (MTD_READECC(inftl->mbd.mtd, address, SECTORSIZE, &retlen, buf, &buf[SECTORSIZE], &inftl->oobinfo) < 0)
360                         return -1;
361                 if (memcmpb(buf, 0xff, SECTORSIZE) != 0)
362                         return -1;
363
364                 if (check_oob) {
365                         if (memcmpb(buf + SECTORSIZE, 0xff, inftl->mbd.mtd->oobsize) != 0)
366                                 return -1;
367                 }
368                 address += SECTORSIZE;
369         }
370
371         return 0;
372 }
373
374 /*
375  * INFTL_format: format a Erase Unit by erasing ALL Erase Zones in the Erase
376  *               Unit and Update INFTL metadata. Each erase operation is
377  *               checked with check_free_sectors.
378  *
379  * Return: 0 when succeed, -1 on error.
380  *
381  * ToDo: 1. Is it neceressary to check_free_sector after erasing ?? 
382  */
383 int INFTL_formatblock(struct INFTLrecord *inftl, int block)
384 {
385         int retlen;
386         struct inftl_unittail uci;
387         struct erase_info *instr = &inftl->instr;
388         int physblock;
389
390         DEBUG(MTD_DEBUG_LEVEL3, "INFTL: INFTL_formatblock(inftl=0x%x,"
391                 "block=%d)\n", (int)inftl, block);
392
393         memset(instr, 0, sizeof(struct erase_info));
394
395         /* FIXME: Shouldn't we be setting the 'discarded' flag to zero
396            _first_? */
397
398         /* Use async erase interface, test return code */
399         instr->addr = block * inftl->EraseSize;
400         instr->len = inftl->mbd.mtd->erasesize;
401         /* Erase one physical eraseblock at a time, even though the NAND api
402            allows us to group them.  This way we if we have a failure, we can
403            mark only the failed block in the bbt. */
404         for (physblock = 0; physblock < inftl->EraseSize; physblock += instr->len, instr->addr += instr->len) {
405                 MTD_ERASE(inftl->mbd.mtd, instr);
406
407                 if (instr->state == MTD_ERASE_FAILED) {
408                         printk(KERN_WARNING "INFTL: error while formatting block %d\n",
409                                 block);
410                         goto fail;
411                 }
412
413                 /*
414                 * Check the "freeness" of Erase Unit before updating metadata.
415                 * FixMe: is this check really necessary? Since we have check the
416                 *        return code after the erase operation.
417                 */
418                 if (check_free_sectors(inftl, instr->addr, instr->len, 1) != 0)
419                         goto fail;
420         }
421
422         uci.EraseMark = cpu_to_le16(ERASE_MARK);
423         uci.EraseMark1 = cpu_to_le16(ERASE_MARK);
424         uci.Reserved[0] = 0;
425         uci.Reserved[1] = 0;
426         uci.Reserved[2] = 0;
427         uci.Reserved[3] = 0;
428         instr->addr = block * inftl->EraseSize + SECTORSIZE * 2;
429         if (MTD_WRITEOOB(inftl->mbd.mtd, instr->addr +
430             8, 8, &retlen, (char *)&uci) < 0)
431                 goto fail;
432         return 0;
433 fail:
434         /* could not format, update the bad block table (caller is responsible
435            for setting the PUtable to BLOCK_RESERVED on failure) */
436         inftl->mbd.mtd->block_markbad(inftl->mbd.mtd, instr->addr);
437         return -1;
438 }
439
440 /*
441  * format_chain: Format an invalid Virtual Unit chain. It frees all the Erase
442  *      Units in a Virtual Unit Chain, i.e. all the units are disconnected.
443  *
444  *      Since the chain is invalid then we will have to erase it from its
445  *      head (normally for INFTL we go from the oldest). But if it has a
446  *      loop then there is no oldest...
447  */
448 static void format_chain(struct INFTLrecord *inftl, unsigned int first_block)
449 {
450         unsigned int block = first_block, block1;
451
452         printk(KERN_WARNING "INFTL: formatting chain at block %d\n",
453                 first_block);
454
455         for (;;) {
456                 block1 = inftl->PUtable[block];
457
458                 printk(KERN_WARNING "INFTL: formatting block %d\n", block);
459                 if (INFTL_formatblock(inftl, block) < 0) {
460                         /*
461                          * Cannot format !!!! Mark it as Bad Unit,
462                          */
463                         inftl->PUtable[block] = BLOCK_RESERVED;
464                 } else {
465                         inftl->PUtable[block] = BLOCK_FREE;
466                 }
467
468                 /* Goto next block on the chain */
469                 block = block1;
470
471                 if (block == BLOCK_NIL || block >= inftl->lastEUN)
472                         break;
473         }
474 }
475
476 void INFTL_dumptables(struct INFTLrecord *s)
477 {
478         int i;
479
480         printk("-------------------------------------------"
481                 "----------------------------------\n");
482
483         printk("VUtable[%d] ->", s->nb_blocks);
484         for (i = 0; i < s->nb_blocks; i++) {
485                 if ((i % 8) == 0)
486                         printk("\n%04x: ", i);
487                 printk("%04x ", s->VUtable[i]);
488         }
489
490         printk("\n-------------------------------------------"
491                 "----------------------------------\n");
492
493         printk("PUtable[%d-%d=%d] ->", s->firstEUN, s->lastEUN, s->nb_blocks);
494         for (i = 0; i <= s->lastEUN; i++) {
495                 if ((i % 8) == 0)
496                         printk("\n%04x: ", i);
497                 printk("%04x ", s->PUtable[i]);
498         }
499
500         printk("\n-------------------------------------------"
501                 "----------------------------------\n");
502
503         printk("INFTL ->\n"
504                 "  EraseSize       = %d\n"
505                 "  h/s/c           = %d/%d/%d\n"
506                 "  numvunits       = %d\n"
507                 "  firstEUN        = %d\n"
508                 "  lastEUN         = %d\n"
509                 "  numfreeEUNs     = %d\n"
510                 "  LastFreeEUN     = %d\n"
511                 "  nb_blocks       = %d\n"
512                 "  nb_boot_blocks  = %d",
513                 s->EraseSize, s->heads, s->sectors, s->cylinders,
514                 s->numvunits, s->firstEUN, s->lastEUN, s->numfreeEUNs,
515                 s->LastFreeEUN, s->nb_blocks, s->nb_boot_blocks);
516
517         printk("\n-------------------------------------------"
518                 "----------------------------------\n");
519 }
520
521 void INFTL_dumpVUchains(struct INFTLrecord *s)
522 {
523         int logical, block, i;
524
525         printk("-------------------------------------------"
526                 "----------------------------------\n");
527
528         printk("INFTL Virtual Unit Chains:\n");
529         for (logical = 0; logical < s->nb_blocks; logical++) {
530                 block = s->VUtable[logical];
531                 if (block > s->nb_blocks)
532                         continue;
533                 printk("  LOGICAL %d --> %d ", logical, block);
534                 for (i = 0; i < s->nb_blocks; i++) {
535                         if (s->PUtable[block] == BLOCK_NIL)
536                                 break;
537                         block = s->PUtable[block];
538                         printk("%d ", block);
539                 }
540                 printk("\n");
541         }
542
543         printk("-------------------------------------------"
544                 "----------------------------------\n");
545 }
546
547 int INFTL_mount(struct INFTLrecord *s)
548 {
549         unsigned int block, first_block, prev_block, last_block;
550         unsigned int first_logical_block, logical_block, erase_mark;
551         int chain_length, do_format_chain;
552         struct inftl_unithead1 h0;
553         struct inftl_unittail h1;
554         int i, retlen;
555         u8 *ANACtable, ANAC;
556
557         DEBUG(MTD_DEBUG_LEVEL3, "INFTL: INFTL_mount(inftl=0x%x)\n", (int)s);
558
559         /* Search for INFTL MediaHeader and Spare INFTL Media Header */
560         if (find_boot_record(s) < 0) {
561                 printk(KERN_WARNING "INFTL: could not find valid boot record?\n");
562                 return -1;
563         }
564
565         /* Init the logical to physical table */
566         for (i = 0; i < s->nb_blocks; i++)
567                 s->VUtable[i] = BLOCK_NIL;
568
569         logical_block = block = BLOCK_NIL;
570
571         /* Temporary buffer to store ANAC numbers. */
572         ANACtable = kmalloc(s->nb_blocks * sizeof(u8), GFP_KERNEL);
573         memset(ANACtable, 0, s->nb_blocks);
574
575         /*
576          * First pass is to explore each physical unit, and construct the
577          * virtual chains that exist (newest physical unit goes into VUtable).
578          * Any block that is in any way invalid will be left in the
579          * NOTEXPLORED state. Then at the end we will try to format it and
580          * mark it as free.
581          */
582         DEBUG(MTD_DEBUG_LEVEL3, "INFTL: pass 1, explore each unit\n");
583         for (first_block = s->firstEUN; first_block <= s->lastEUN; first_block++) {
584                 if (s->PUtable[first_block] != BLOCK_NOTEXPLORED)
585                         continue;
586
587                 do_format_chain = 0;
588                 first_logical_block = BLOCK_NIL;
589                 last_block = BLOCK_NIL;
590                 block = first_block;
591
592                 for (chain_length = 0; ; chain_length++) {
593
594                         if ((chain_length == 0) && 
595                             (s->PUtable[block] != BLOCK_NOTEXPLORED)) {
596                                 /* Nothing to do here, onto next block */
597                                 break;
598                         }
599
600                         if (MTD_READOOB(s->mbd.mtd, block * s->EraseSize + 8,
601                             8, &retlen, (char *)&h0) < 0 ||
602                             MTD_READOOB(s->mbd.mtd, block * s->EraseSize +
603                             2 * SECTORSIZE + 8, 8, &retlen, (char *)&h1) < 0) {
604                                 /* Should never happen? */
605                                 do_format_chain++;
606                                 break;
607                         }
608
609                         logical_block = le16_to_cpu(h0.virtualUnitNo);
610                         prev_block = le16_to_cpu(h0.prevUnitNo);
611                         erase_mark = le16_to_cpu((h1.EraseMark | h1.EraseMark1));
612                         ANACtable[block] = h0.ANAC;
613
614                         /* Previous block is relative to start of Partition */
615                         if (prev_block < s->nb_blocks)
616                                 prev_block += s->firstEUN;
617
618                         /* Already explored partial chain? */
619                         if (s->PUtable[block] != BLOCK_NOTEXPLORED) {
620                                 /* Check if chain for this logical */
621                                 if (logical_block == first_logical_block) {
622                                         if (last_block != BLOCK_NIL)
623                                                 s->PUtable[last_block] = block;
624                                 }
625                                 break;
626                         }
627
628                         /* Check for invalid block */
629                         if (erase_mark != ERASE_MARK) {
630                                 printk(KERN_WARNING "INFTL: corrupt block %d "
631                                         "in chain %d, chain length %d, erase "
632                                         "mark 0x%x?\n", block, first_block,
633                                         chain_length, erase_mark);
634                                 /*
635                                  * Assume end of chain, probably incomplete
636                                  * fold/erase...
637                                  */
638                                 if (chain_length == 0)
639                                         do_format_chain++;
640                                 break;
641                         }
642
643                         /* Check for it being free already then... */
644                         if ((logical_block == BLOCK_FREE) ||
645                             (logical_block == BLOCK_NIL)) {
646                                 s->PUtable[block] = BLOCK_FREE;
647                                 break;
648                         }
649
650                         /* Sanity checks on block numbers */
651                         if ((logical_block >= s->nb_blocks) ||
652                             ((prev_block >= s->nb_blocks) &&
653                              (prev_block != BLOCK_NIL))) {
654                                 if (chain_length > 0) {
655                                         printk(KERN_WARNING "INFTL: corrupt "
656                                                 "block %d in chain %d?\n",
657                                                 block, first_block);
658                                         do_format_chain++;
659                                 }
660                                 break;
661                         }
662
663                         if (first_logical_block == BLOCK_NIL) {
664                                 first_logical_block = logical_block;
665                         } else {
666                                 if (first_logical_block != logical_block) {
667                                         /* Normal for folded chain... */
668                                         break;
669                                 }
670                         }
671
672                         /*
673                          * Current block is valid, so if we followed a virtual
674                          * chain to get here then we can set the previous
675                          * block pointer in our PUtable now. Then move onto
676                          * the previous block in the chain.
677                          */
678                         s->PUtable[block] = BLOCK_NIL;
679                         if (last_block != BLOCK_NIL)
680                                 s->PUtable[last_block] = block;
681                         last_block = block;
682                         block = prev_block;
683
684                         /* Check for end of chain */
685                         if (block == BLOCK_NIL)
686                                 break;
687
688                         /* Validate next block before following it... */
689                         if (block > s->lastEUN) {
690                                 printk(KERN_WARNING "INFTL: invalid previous "
691                                         "block %d in chain %d?\n", block,
692                                         first_block);
693                                 do_format_chain++;
694                                 break;
695                         }
696                 }
697
698                 if (do_format_chain) {
699                         format_chain(s, first_block);
700                         continue;
701                 }
702
703                 /*
704                  * Looks like a valid chain then. It may not really be the
705                  * newest block in the chain, but it is the newest we have
706                  * found so far. We might update it in later iterations of
707                  * this loop if we find something newer.
708                  */
709                 s->VUtable[first_logical_block] = first_block;
710                 logical_block = BLOCK_NIL;
711         }
712
713 #ifdef CONFIG_MTD_DEBUG_VERBOSE
714         if (CONFIG_MTD_DEBUG_VERBOSE >= 2)
715                 INFTL_dumptables(s);
716 #endif
717
718         /*
719          * Second pass, check for infinite loops in chains. These are
720          * possible because we don't update the previous pointers when
721          * we fold chains. No big deal, just fix them up in PUtable.
722          */
723         DEBUG(MTD_DEBUG_LEVEL3, "INFTL: pass 2, validate virtual chains\n");
724         for (logical_block = 0; logical_block < s->numvunits; logical_block++) {
725                 block = s->VUtable[logical_block];
726                 last_block = BLOCK_NIL;
727
728                 /* Check for free/reserved/nil */
729                 if (block >= BLOCK_RESERVED)
730                         continue;
731
732                 ANAC = ANACtable[block];
733                 for (i = 0; i < s->numvunits; i++) {
734                         if (s->PUtable[block] == BLOCK_NIL)
735                                 break;
736                         if (s->PUtable[block] > s->lastEUN) {
737                                 printk(KERN_WARNING "INFTL: invalid prev %d, "
738                                         "in virtual chain %d\n",
739                                         s->PUtable[block], logical_block);
740                                 s->PUtable[block] = BLOCK_NIL;
741                                         
742                         }
743                         if (ANACtable[block] != ANAC) {
744                                 /*
745                                  * Chain must point back to itself. This is ok,
746                                  * but we will need adjust the tables with this
747                                  * newest block and oldest block.
748                                  */
749                                 s->VUtable[logical_block] = block;
750                                 s->PUtable[last_block] = BLOCK_NIL;
751                                 break;
752                         }
753
754                         ANAC--;
755                         last_block = block;
756                         block = s->PUtable[block];
757                 }
758
759                 if (i >= s->nb_blocks) {
760                         /*
761                          * Uhoo, infinite chain with valid ANACS!
762                          * Format whole chain...
763                          */
764                         format_chain(s, first_block);
765                 }
766         }
767
768 #ifdef CONFIG_MTD_DEBUG_VERBOSE
769         if (CONFIG_MTD_DEBUG_VERBOSE >= 2)
770                 INFTL_dumptables(s);
771         if (CONFIG_MTD_DEBUG_VERBOSE >= 2)
772                 INFTL_dumpVUchains(s);
773 #endif
774
775         /*
776          * Third pass, format unreferenced blocks and init free block count.
777          */
778         s->numfreeEUNs = 0;
779         s->LastFreeEUN = BLOCK_NIL;
780
781         DEBUG(MTD_DEBUG_LEVEL3, "INFTL: pass 3, format unused blocks\n");
782         for (block = s->firstEUN; block <= s->lastEUN; block++) {
783                 if (s->PUtable[block] == BLOCK_NOTEXPLORED) {
784                         printk("INFTL: unreferenced block %d, formatting it\n",
785                                 block);
786                         if (INFTL_formatblock(s, block) < 0)
787                                 s->PUtable[block] = BLOCK_RESERVED;
788                         else
789                                 s->PUtable[block] = BLOCK_FREE;
790                 }
791                 if (s->PUtable[block] == BLOCK_FREE) {
792                         s->numfreeEUNs++;
793                         if (s->LastFreeEUN == BLOCK_NIL)
794                                 s->LastFreeEUN = block;
795                 }
796         }
797
798         kfree(ANACtable);
799         return 0;
800 }