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