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