xref: /openbmc/u-boot/fs/fat/fat.c (revision 5ff8b354)
1 /*
2  * fat.c
3  *
4  * R/O (V)FAT 12/16/32 filesystem implementation by Marcus Sundberg
5  *
6  * 2002-07-28 - rjones@nexus-tech.net - ported to ppcboot v1.1.6
7  * 2003-03-10 - kharris@nexus-tech.net - ported to uboot
8  *
9  * See file CREDITS for list of people who contributed to this
10  * project.
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License as
14  * published by the Free Software Foundation; either version 2 of
15  * the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
25  * MA 02111-1307 USA
26  */
27 
28 #include <common.h>
29 #include <config.h>
30 #include <exports.h>
31 #include <fat.h>
32 #include <asm/byteorder.h>
33 #include <part.h>
34 
35 /*
36  * Convert a string to lowercase.
37  */
38 static void downcase (char *str)
39 {
40 	while (*str != '\0') {
41 		TOLOWER(*str);
42 		str++;
43 	}
44 }
45 
46 static block_dev_desc_t *cur_dev = NULL;
47 
48 static unsigned long part_offset = 0;
49 static unsigned long part_size;
50 
51 static int cur_part = 1;
52 
53 #define DOS_PART_TBL_OFFSET	0x1be
54 #define DOS_PART_MAGIC_OFFSET	0x1fe
55 #define DOS_FS_TYPE_OFFSET	0x36
56 #define DOS_FS32_TYPE_OFFSET	0x52
57 
58 static int disk_read (__u32 startblock, __u32 getsize, __u8 * bufptr)
59 {
60 	if (cur_dev == NULL)
61 		return -1;
62 
63 	startblock += part_offset;
64 
65 	if (cur_dev->block_read) {
66 		return cur_dev->block_read(cur_dev->dev, startblock, getsize,
67 					   (unsigned long *) bufptr);
68 	}
69 	return -1;
70 }
71 
72 int fat_register_device (block_dev_desc_t * dev_desc, int part_no)
73 {
74 	unsigned char buffer[dev_desc->blksz];
75 	disk_partition_t info;
76 
77 	if (!dev_desc->block_read)
78 		return -1;
79 
80 	cur_dev = dev_desc;
81 	/* check if we have a MBR (on floppies we have only a PBR) */
82 	if (dev_desc->block_read(dev_desc->dev, 0, 1, (ulong *)buffer) != 1) {
83 		printf("** Can't read from device %d **\n",
84 			dev_desc->dev);
85 		return -1;
86 	}
87 	if (buffer[DOS_PART_MAGIC_OFFSET] != 0x55 ||
88 	    buffer[DOS_PART_MAGIC_OFFSET + 1] != 0xaa) {
89 		/* no signature found */
90 		return -1;
91 	}
92 #if (defined(CONFIG_CMD_IDE) || \
93      defined(CONFIG_CMD_MG_DISK) || \
94      defined(CONFIG_CMD_SATA) || \
95      defined(CONFIG_CMD_SCSI) || \
96      defined(CONFIG_CMD_USB) || \
97      defined(CONFIG_MMC) || \
98      defined(CONFIG_SYSTEMACE) )
99 	/* First we assume there is a MBR */
100 	if (!get_partition_info(dev_desc, part_no, &info)) {
101 		part_offset = info.start;
102 		cur_part = part_no;
103 		part_size = info.size;
104 	} else if ((strncmp((char *)&buffer[DOS_FS_TYPE_OFFSET], "FAT", 3) == 0) ||
105 		   (strncmp((char *)&buffer[DOS_FS32_TYPE_OFFSET], "FAT32", 5) == 0)) {
106 		/* ok, we assume we are on a PBR only */
107 		cur_part = 1;
108 		part_offset = 0;
109 	} else {
110 		printf("** Partition %d not valid on device %d **\n",
111 			part_no, dev_desc->dev);
112 		return -1;
113 	}
114 
115 #else
116 	if ((strncmp((char *)&buffer[DOS_FS_TYPE_OFFSET], "FAT", 3) == 0) ||
117 	    (strncmp((char *)&buffer[DOS_FS32_TYPE_OFFSET], "FAT32", 5) == 0)) {
118 		/* ok, we assume we are on a PBR only */
119 		cur_part = 1;
120 		part_offset = 0;
121 		info.start = part_offset;
122 	} else {
123 		/* FIXME we need to determine the start block of the
124 		 * partition where the DOS FS resides. This can be done
125 		 * by using the get_partition_info routine. For this
126 		 * purpose the libpart must be included.
127 		 */
128 		part_offset = 32;
129 		cur_part = 1;
130 	}
131 #endif
132 	return 0;
133 }
134 
135 /*
136  * Get the first occurence of a directory delimiter ('/' or '\') in a string.
137  * Return index into string if found, -1 otherwise.
138  */
139 static int dirdelim (char *str)
140 {
141 	char *start = str;
142 
143 	while (*str != '\0') {
144 		if (ISDIRDELIM(*str))
145 			return str - start;
146 		str++;
147 	}
148 	return -1;
149 }
150 
151 /*
152  * Extract zero terminated short name from a directory entry.
153  */
154 static void get_name (dir_entry *dirent, char *s_name)
155 {
156 	char *ptr;
157 
158 	memcpy(s_name, dirent->name, 8);
159 	s_name[8] = '\0';
160 	ptr = s_name;
161 	while (*ptr && *ptr != ' ')
162 		ptr++;
163 	if (dirent->ext[0] && dirent->ext[0] != ' ') {
164 		*ptr = '.';
165 		ptr++;
166 		memcpy(ptr, dirent->ext, 3);
167 		ptr[3] = '\0';
168 		while (*ptr && *ptr != ' ')
169 			ptr++;
170 	}
171 	*ptr = '\0';
172 	if (*s_name == DELETED_FLAG)
173 		*s_name = '\0';
174 	else if (*s_name == aRING)
175 		*s_name = DELETED_FLAG;
176 	downcase(s_name);
177 }
178 
179 /*
180  * Get the entry at index 'entry' in a FAT (12/16/32) table.
181  * On failure 0x00 is returned.
182  */
183 static __u32 get_fatent (fsdata *mydata, __u32 entry)
184 {
185 	__u32 bufnum;
186 	__u32 off16, offset;
187 	__u32 ret = 0x00;
188 	__u16 val1, val2;
189 
190 	switch (mydata->fatsize) {
191 	case 32:
192 		bufnum = entry / FAT32BUFSIZE;
193 		offset = entry - bufnum * FAT32BUFSIZE;
194 		break;
195 	case 16:
196 		bufnum = entry / FAT16BUFSIZE;
197 		offset = entry - bufnum * FAT16BUFSIZE;
198 		break;
199 	case 12:
200 		bufnum = entry / FAT12BUFSIZE;
201 		offset = entry - bufnum * FAT12BUFSIZE;
202 		break;
203 
204 	default:
205 		/* Unsupported FAT size */
206 		return ret;
207 	}
208 
209 	debug("FAT%d: entry: 0x%04x = %d, offset: 0x%04x = %d\n",
210 	       mydata->fatsize, entry, entry, offset, offset);
211 
212 	/* Read a new block of FAT entries into the cache. */
213 	if (bufnum != mydata->fatbufnum) {
214 		__u32 getsize = FATBUFBLOCKS;
215 		__u8 *bufptr = mydata->fatbuf;
216 		__u32 fatlength = mydata->fatlength;
217 		__u32 startblock = bufnum * FATBUFBLOCKS;
218 
219 		if (getsize > fatlength)
220 			getsize = fatlength;
221 
222 		fatlength *= mydata->sect_size;	/* We want it in bytes now */
223 		startblock += mydata->fat_sect;	/* Offset from start of disk */
224 
225 		if (disk_read(startblock, getsize, bufptr) < 0) {
226 			debug("Error reading FAT blocks\n");
227 			return ret;
228 		}
229 		mydata->fatbufnum = bufnum;
230 	}
231 
232 	/* Get the actual entry from the table */
233 	switch (mydata->fatsize) {
234 	case 32:
235 		ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]);
236 		break;
237 	case 16:
238 		ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]);
239 		break;
240 	case 12:
241 		off16 = (offset * 3) / 4;
242 
243 		switch (offset & 0x3) {
244 		case 0:
245 			ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[off16]);
246 			ret &= 0xfff;
247 			break;
248 		case 1:
249 			val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
250 			val1 &= 0xf000;
251 			val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]);
252 			val2 &= 0x00ff;
253 			ret = (val2 << 4) | (val1 >> 12);
254 			break;
255 		case 2:
256 			val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
257 			val1 &= 0xff00;
258 			val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]);
259 			val2 &= 0x000f;
260 			ret = (val2 << 8) | (val1 >> 8);
261 			break;
262 		case 3:
263 			ret = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
264 			ret = (ret & 0xfff0) >> 4;
265 			break;
266 		default:
267 			break;
268 		}
269 		break;
270 	}
271 	debug("FAT%d: ret: %08x, offset: %04x\n",
272 	       mydata->fatsize, ret, offset);
273 
274 	return ret;
275 }
276 
277 /*
278  * Read at most 'size' bytes from the specified cluster into 'buffer'.
279  * Return 0 on success, -1 otherwise.
280  */
281 static int
282 get_cluster (fsdata *mydata, __u32 clustnum, __u8 *buffer,
283 	     unsigned long size)
284 {
285 	__u32 idx = 0;
286 	__u32 startsect;
287 
288 	if (clustnum > 0) {
289 		startsect = mydata->data_begin +
290 				clustnum * mydata->clust_size;
291 	} else {
292 		startsect = mydata->rootdir_sect;
293 	}
294 
295 	debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect);
296 
297 	if (disk_read(startsect, size / mydata->sect_size, buffer) < 0) {
298 		debug("Error reading data\n");
299 		return -1;
300 	}
301 	if (size % mydata->sect_size) {
302 		__u8 tmpbuf[mydata->sect_size];
303 
304 		idx = size / mydata->sect_size;
305 		if (disk_read(startsect + idx, 1, tmpbuf) < 0) {
306 			debug("Error reading data\n");
307 			return -1;
308 		}
309 		buffer += idx * mydata->sect_size;
310 
311 		memcpy(buffer, tmpbuf, size % mydata->sect_size);
312 		return 0;
313 	}
314 
315 	return 0;
316 }
317 
318 /*
319  * Read at most 'maxsize' bytes from the file associated with 'dentptr'
320  * into 'buffer'.
321  * Return the number of bytes read or -1 on fatal errors.
322  */
323 static long
324 get_contents (fsdata *mydata, dir_entry *dentptr, __u8 *buffer,
325 	      unsigned long maxsize)
326 {
327 	unsigned long filesize = FAT2CPU32(dentptr->size), gotsize = 0;
328 	unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
329 	__u32 curclust = START(dentptr);
330 	__u32 endclust, newclust;
331 	unsigned long actsize;
332 
333 	debug("Filesize: %ld bytes\n", filesize);
334 
335 	if (maxsize > 0 && filesize > maxsize)
336 		filesize = maxsize;
337 
338 	debug("%ld bytes\n", filesize);
339 
340 	actsize = bytesperclust;
341 	endclust = curclust;
342 
343 	do {
344 		/* search for consecutive clusters */
345 		while (actsize < filesize) {
346 			newclust = get_fatent(mydata, endclust);
347 			if ((newclust - 1) != endclust)
348 				goto getit;
349 			if (CHECK_CLUST(newclust, mydata->fatsize)) {
350 				debug("curclust: 0x%x\n", newclust);
351 				debug("Invalid FAT entry\n");
352 				return gotsize;
353 			}
354 			endclust = newclust;
355 			actsize += bytesperclust;
356 		}
357 
358 		/* actsize >= file size */
359 		actsize -= bytesperclust;
360 
361 		/* get remaining clusters */
362 		if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
363 			printf("Error reading cluster\n");
364 			return -1;
365 		}
366 
367 		/* get remaining bytes */
368 		gotsize += (int)actsize;
369 		filesize -= actsize;
370 		buffer += actsize;
371 		actsize = filesize;
372 		if (get_cluster(mydata, endclust, buffer, (int)actsize) != 0) {
373 			printf("Error reading cluster\n");
374 			return -1;
375 		}
376 		gotsize += actsize;
377 		return gotsize;
378 getit:
379 		if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
380 			printf("Error reading cluster\n");
381 			return -1;
382 		}
383 		gotsize += (int)actsize;
384 		filesize -= actsize;
385 		buffer += actsize;
386 
387 		curclust = get_fatent(mydata, endclust);
388 		if (CHECK_CLUST(curclust, mydata->fatsize)) {
389 			debug("curclust: 0x%x\n", curclust);
390 			printf("Invalid FAT entry\n");
391 			return gotsize;
392 		}
393 		actsize = bytesperclust;
394 		endclust = curclust;
395 	} while (1);
396 }
397 
398 #ifdef CONFIG_SUPPORT_VFAT
399 /*
400  * Extract the file name information from 'slotptr' into 'l_name',
401  * starting at l_name[*idx].
402  * Return 1 if terminator (zero byte) is found, 0 otherwise.
403  */
404 static int slot2str (dir_slot *slotptr, char *l_name, int *idx)
405 {
406 	int j;
407 
408 	for (j = 0; j <= 8; j += 2) {
409 		l_name[*idx] = slotptr->name0_4[j];
410 		if (l_name[*idx] == 0x00)
411 			return 1;
412 		(*idx)++;
413 	}
414 	for (j = 0; j <= 10; j += 2) {
415 		l_name[*idx] = slotptr->name5_10[j];
416 		if (l_name[*idx] == 0x00)
417 			return 1;
418 		(*idx)++;
419 	}
420 	for (j = 0; j <= 2; j += 2) {
421 		l_name[*idx] = slotptr->name11_12[j];
422 		if (l_name[*idx] == 0x00)
423 			return 1;
424 		(*idx)++;
425 	}
426 
427 	return 0;
428 }
429 
430 /*
431  * Extract the full long filename starting at 'retdent' (which is really
432  * a slot) into 'l_name'. If successful also copy the real directory entry
433  * into 'retdent'
434  * Return 0 on success, -1 otherwise.
435  */
436 __attribute__ ((__aligned__ (__alignof__ (dir_entry))))
437 __u8 get_vfatname_block[MAX_CLUSTSIZE];
438 
439 static int
440 get_vfatname (fsdata *mydata, int curclust, __u8 *cluster,
441 	      dir_entry *retdent, char *l_name)
442 {
443 	dir_entry *realdent;
444 	dir_slot *slotptr = (dir_slot *)retdent;
445 	__u8 *buflimit = cluster + mydata->sect_size * ((curclust == 0) ?
446 							PREFETCH_BLOCKS :
447 							mydata->clust_size);
448 	__u8 counter = (slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff;
449 	int idx = 0;
450 
451 	if (counter > VFAT_MAXSEQ) {
452 		debug("Error: VFAT name is too long\n");
453 		return -1;
454 	}
455 
456 	while ((__u8 *)slotptr < buflimit) {
457 		if (counter == 0)
458 			break;
459 		if (((slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff) != counter)
460 			return -1;
461 		slotptr++;
462 		counter--;
463 	}
464 
465 	if ((__u8 *)slotptr >= buflimit) {
466 		dir_slot *slotptr2;
467 
468 		if (curclust == 0)
469 			return -1;
470 		curclust = get_fatent(mydata, curclust);
471 		if (CHECK_CLUST(curclust, mydata->fatsize)) {
472 			debug("curclust: 0x%x\n", curclust);
473 			printf("Invalid FAT entry\n");
474 			return -1;
475 		}
476 
477 		if (get_cluster(mydata, curclust, get_vfatname_block,
478 				mydata->clust_size * mydata->sect_size) != 0) {
479 			debug("Error: reading directory block\n");
480 			return -1;
481 		}
482 
483 		slotptr2 = (dir_slot *)get_vfatname_block;
484 		while (counter > 0) {
485 			if (((slotptr2->id & ~LAST_LONG_ENTRY_MASK)
486 			    & 0xff) != counter)
487 				return -1;
488 			slotptr2++;
489 			counter--;
490 		}
491 
492 		/* Save the real directory entry */
493 		realdent = (dir_entry *)slotptr2;
494 		while ((__u8 *)slotptr2 > get_vfatname_block) {
495 			slotptr2--;
496 			slot2str(slotptr2, l_name, &idx);
497 		}
498 	} else {
499 		/* Save the real directory entry */
500 		realdent = (dir_entry *)slotptr;
501 	}
502 
503 	do {
504 		slotptr--;
505 		if (slot2str(slotptr, l_name, &idx))
506 			break;
507 	} while (!(slotptr->id & LAST_LONG_ENTRY_MASK));
508 
509 	l_name[idx] = '\0';
510 	if (*l_name == DELETED_FLAG)
511 		*l_name = '\0';
512 	else if (*l_name == aRING)
513 		*l_name = DELETED_FLAG;
514 	downcase(l_name);
515 
516 	/* Return the real directory entry */
517 	memcpy(retdent, realdent, sizeof(dir_entry));
518 
519 	return 0;
520 }
521 
522 /* Calculate short name checksum */
523 static __u8 mkcksum (const char *str)
524 {
525 	int i;
526 
527 	__u8 ret = 0;
528 
529 	for (i = 0; i < 11; i++) {
530 		ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + str[i];
531 	}
532 
533 	return ret;
534 }
535 #endif	/* CONFIG_SUPPORT_VFAT */
536 
537 /*
538  * Get the directory entry associated with 'filename' from the directory
539  * starting at 'startsect'
540  */
541 __attribute__ ((__aligned__ (__alignof__ (dir_entry))))
542 __u8 get_dentfromdir_block[MAX_CLUSTSIZE];
543 
544 static dir_entry *get_dentfromdir (fsdata *mydata, int startsect,
545 				   char *filename, dir_entry *retdent,
546 				   int dols)
547 {
548 	__u16 prevcksum = 0xffff;
549 	__u32 curclust = START(retdent);
550 	int files = 0, dirs = 0;
551 
552 	debug("get_dentfromdir: %s\n", filename);
553 
554 	while (1) {
555 		dir_entry *dentptr;
556 
557 		int i;
558 
559 		if (get_cluster(mydata, curclust, get_dentfromdir_block,
560 				mydata->clust_size * mydata->sect_size) != 0) {
561 			debug("Error: reading directory block\n");
562 			return NULL;
563 		}
564 
565 		dentptr = (dir_entry *)get_dentfromdir_block;
566 
567 		for (i = 0; i < DIRENTSPERCLUST; i++) {
568 			char s_name[14], l_name[VFAT_MAXLEN_BYTES];
569 
570 			l_name[0] = '\0';
571 			if (dentptr->name[0] == DELETED_FLAG) {
572 				dentptr++;
573 				continue;
574 			}
575 			if ((dentptr->attr & ATTR_VOLUME)) {
576 #ifdef CONFIG_SUPPORT_VFAT
577 				if ((dentptr->attr & ATTR_VFAT) &&
578 				    (dentptr-> name[0] & LAST_LONG_ENTRY_MASK)) {
579 					prevcksum = ((dir_slot *)dentptr)->alias_checksum;
580 					get_vfatname(mydata, curclust,
581 						     get_dentfromdir_block,
582 						     dentptr, l_name);
583 					if (dols) {
584 						int isdir;
585 						char dirc;
586 						int doit = 0;
587 
588 						isdir = (dentptr->attr & ATTR_DIR);
589 
590 						if (isdir) {
591 							dirs++;
592 							dirc = '/';
593 							doit = 1;
594 						} else {
595 							dirc = ' ';
596 							if (l_name[0] != 0) {
597 								files++;
598 								doit = 1;
599 							}
600 						}
601 						if (doit) {
602 							if (dirc == ' ') {
603 								printf(" %8ld   %s%c\n",
604 									(long)FAT2CPU32(dentptr->size),
605 									l_name,
606 									dirc);
607 							} else {
608 								printf("            %s%c\n",
609 									l_name,
610 									dirc);
611 							}
612 						}
613 						dentptr++;
614 						continue;
615 					}
616 					debug("vfatname: |%s|\n", l_name);
617 				} else
618 #endif
619 				{
620 					/* Volume label or VFAT entry */
621 					dentptr++;
622 					continue;
623 				}
624 			}
625 			if (dentptr->name[0] == 0) {
626 				if (dols) {
627 					printf("\n%d file(s), %d dir(s)\n\n",
628 						files, dirs);
629 				}
630 				debug("Dentname == NULL - %d\n", i);
631 				return NULL;
632 			}
633 #ifdef CONFIG_SUPPORT_VFAT
634 			if (dols && mkcksum(dentptr->name) == prevcksum) {
635 				dentptr++;
636 				continue;
637 			}
638 #endif
639 			get_name(dentptr, s_name);
640 			if (dols) {
641 				int isdir = (dentptr->attr & ATTR_DIR);
642 				char dirc;
643 				int doit = 0;
644 
645 				if (isdir) {
646 					dirs++;
647 					dirc = '/';
648 					doit = 1;
649 				} else {
650 					dirc = ' ';
651 					if (s_name[0] != 0) {
652 						files++;
653 						doit = 1;
654 					}
655 				}
656 
657 				if (doit) {
658 					if (dirc == ' ') {
659 						printf(" %8ld   %s%c\n",
660 							(long)FAT2CPU32(dentptr->size),
661 							s_name, dirc);
662 					} else {
663 						printf("            %s%c\n",
664 							s_name, dirc);
665 					}
666 				}
667 
668 				dentptr++;
669 				continue;
670 			}
671 
672 			if (strcmp(filename, s_name)
673 			    && strcmp(filename, l_name)) {
674 				debug("Mismatch: |%s|%s|\n", s_name, l_name);
675 				dentptr++;
676 				continue;
677 			}
678 
679 			memcpy(retdent, dentptr, sizeof(dir_entry));
680 
681 			debug("DentName: %s", s_name);
682 			debug(", start: 0x%x", START(dentptr));
683 			debug(", size:  0x%x %s\n",
684 			      FAT2CPU32(dentptr->size),
685 			      (dentptr->attr & ATTR_DIR) ? "(DIR)" : "");
686 
687 			return retdent;
688 		}
689 
690 		curclust = get_fatent(mydata, curclust);
691 		if (CHECK_CLUST(curclust, mydata->fatsize)) {
692 			debug("curclust: 0x%x\n", curclust);
693 			printf("Invalid FAT entry\n");
694 			return NULL;
695 		}
696 	}
697 
698 	return NULL;
699 }
700 
701 /*
702  * Read boot sector and volume info from a FAT filesystem
703  */
704 static int
705 read_bootsectandvi (boot_sector *bs, volume_info *volinfo, int *fatsize)
706 {
707 	__u8 *block;
708 	volume_info *vistart;
709 	int ret = 0;
710 
711 	if (cur_dev == NULL) {
712 		debug("Error: no device selected\n");
713 		return -1;
714 	}
715 
716 	block = malloc(cur_dev->blksz);
717 	if (block == NULL) {
718 		debug("Error: allocating block\n");
719 		return -1;
720 	}
721 
722 	if (disk_read (0, 1, block) < 0) {
723 		debug("Error: reading block\n");
724 		goto fail;
725 	}
726 
727 	memcpy(bs, block, sizeof(boot_sector));
728 	bs->reserved = FAT2CPU16(bs->reserved);
729 	bs->fat_length = FAT2CPU16(bs->fat_length);
730 	bs->secs_track = FAT2CPU16(bs->secs_track);
731 	bs->heads = FAT2CPU16(bs->heads);
732 	bs->total_sect = FAT2CPU32(bs->total_sect);
733 
734 	/* FAT32 entries */
735 	if (bs->fat_length == 0) {
736 		/* Assume FAT32 */
737 		bs->fat32_length = FAT2CPU32(bs->fat32_length);
738 		bs->flags = FAT2CPU16(bs->flags);
739 		bs->root_cluster = FAT2CPU32(bs->root_cluster);
740 		bs->info_sector = FAT2CPU16(bs->info_sector);
741 		bs->backup_boot = FAT2CPU16(bs->backup_boot);
742 		vistart = (volume_info *)(block + sizeof(boot_sector));
743 		*fatsize = 32;
744 	} else {
745 		vistart = (volume_info *)&(bs->fat32_length);
746 		*fatsize = 0;
747 	}
748 	memcpy(volinfo, vistart, sizeof(volume_info));
749 
750 	if (*fatsize == 32) {
751 		if (strncmp(FAT32_SIGN, vistart->fs_type, SIGNLEN) == 0)
752 			goto exit;
753 	} else {
754 		if (strncmp(FAT12_SIGN, vistart->fs_type, SIGNLEN) == 0) {
755 			*fatsize = 12;
756 			goto exit;
757 		}
758 		if (strncmp(FAT16_SIGN, vistart->fs_type, SIGNLEN) == 0) {
759 			*fatsize = 16;
760 			goto exit;
761 		}
762 	}
763 
764 	debug("Error: broken fs_type sign\n");
765 fail:
766 	ret = -1;
767 exit:
768 	free(block);
769 	return ret;
770 }
771 
772 __attribute__ ((__aligned__ (__alignof__ (dir_entry))))
773 __u8 do_fat_read_block[MAX_CLUSTSIZE];
774 
775 long
776 do_fat_read (const char *filename, void *buffer, unsigned long maxsize,
777 	     int dols)
778 {
779 	char fnamecopy[2048];
780 	boot_sector bs;
781 	volume_info volinfo;
782 	fsdata datablock;
783 	fsdata *mydata = &datablock;
784 	dir_entry *dentptr;
785 	__u16 prevcksum = 0xffff;
786 	char *subname = "";
787 	__u32 cursect;
788 	int idx, isdir = 0;
789 	int files = 0, dirs = 0;
790 	long ret = -1;
791 	int firsttime;
792 	__u32 root_cluster = 0;
793 	int rootdir_size = 0;
794 	int j;
795 
796 	if (read_bootsectandvi(&bs, &volinfo, &mydata->fatsize)) {
797 		debug("Error: reading boot sector\n");
798 		return -1;
799 	}
800 
801 	if (mydata->fatsize == 32) {
802 		root_cluster = bs.root_cluster;
803 		mydata->fatlength = bs.fat32_length;
804 	} else {
805 		mydata->fatlength = bs.fat_length;
806 	}
807 
808 	mydata->fat_sect = bs.reserved;
809 
810 	cursect = mydata->rootdir_sect
811 		= mydata->fat_sect + mydata->fatlength * bs.fats;
812 
813 	mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0];
814 	mydata->clust_size = bs.cluster_size;
815 
816 	if (mydata->fatsize == 32) {
817 		mydata->data_begin = mydata->rootdir_sect -
818 					(mydata->clust_size * 2);
819 	} else {
820 		rootdir_size = ((bs.dir_entries[1]  * (int)256 +
821 				 bs.dir_entries[0]) *
822 				 sizeof(dir_entry)) /
823 				 mydata->sect_size;
824 		mydata->data_begin = mydata->rootdir_sect +
825 					rootdir_size -
826 					(mydata->clust_size * 2);
827 	}
828 
829 	mydata->fatbufnum = -1;
830 	mydata->fatbuf = malloc(FATBUFSIZE);
831 	if (mydata->fatbuf == NULL) {
832 		debug("Error: allocating memory\n");
833 		return -1;
834 	}
835 
836 #ifdef CONFIG_SUPPORT_VFAT
837 	debug("VFAT Support enabled\n");
838 #endif
839 	debug("FAT%d, fat_sect: %d, fatlength: %d\n",
840 	       mydata->fatsize, mydata->fat_sect, mydata->fatlength);
841 	debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n"
842 	       "Data begins at: %d\n",
843 	       root_cluster,
844 	       mydata->rootdir_sect,
845 	       mydata->rootdir_sect * mydata->sect_size, mydata->data_begin);
846 	debug("Sector size: %d, cluster size: %d\n", mydata->sect_size,
847 	      mydata->clust_size);
848 
849 	/* "cwd" is always the root... */
850 	while (ISDIRDELIM(*filename))
851 		filename++;
852 
853 	/* Make a copy of the filename and convert it to lowercase */
854 	strcpy(fnamecopy, filename);
855 	downcase(fnamecopy);
856 
857 	if (*fnamecopy == '\0') {
858 		if (!dols)
859 			goto exit;
860 
861 		dols = LS_ROOT;
862 	} else if ((idx = dirdelim(fnamecopy)) >= 0) {
863 		isdir = 1;
864 		fnamecopy[idx] = '\0';
865 		subname = fnamecopy + idx + 1;
866 
867 		/* Handle multiple delimiters */
868 		while (ISDIRDELIM(*subname))
869 			subname++;
870 	} else if (dols) {
871 		isdir = 1;
872 	}
873 
874 	j = 0;
875 	while (1) {
876 		int i;
877 
878 		debug("FAT read sect=%d, clust_size=%d, DIRENTSPERBLOCK=%d\n",
879 			cursect, mydata->clust_size, DIRENTSPERBLOCK);
880 
881 		if (disk_read(cursect,
882 				(mydata->fatsize == 32) ?
883 				(mydata->clust_size) :
884 				PREFETCH_BLOCKS,
885 				do_fat_read_block) < 0) {
886 			debug("Error: reading rootdir block\n");
887 			goto exit;
888 		}
889 
890 		dentptr = (dir_entry *) do_fat_read_block;
891 
892 		for (i = 0; i < DIRENTSPERBLOCK; i++) {
893 			char s_name[14], l_name[VFAT_MAXLEN_BYTES];
894 
895 			l_name[0] = '\0';
896 			if (dentptr->name[0] == DELETED_FLAG) {
897 				dentptr++;
898 				continue;
899 			}
900 			if ((dentptr->attr & ATTR_VOLUME)) {
901 #ifdef CONFIG_SUPPORT_VFAT
902 				if ((dentptr->attr & ATTR_VFAT) &&
903 				    (dentptr->name[0] & LAST_LONG_ENTRY_MASK)) {
904 					prevcksum =
905 						((dir_slot *)dentptr)->alias_checksum;
906 
907 					get_vfatname(mydata,
908 						     root_cluster,
909 						     do_fat_read_block,
910 						     dentptr, l_name);
911 
912 					if (dols == LS_ROOT) {
913 						char dirc;
914 						int doit = 0;
915 						int isdir =
916 							(dentptr->attr & ATTR_DIR);
917 
918 						if (isdir) {
919 							dirs++;
920 							dirc = '/';
921 							doit = 1;
922 						} else {
923 							dirc = ' ';
924 							if (l_name[0] != 0) {
925 								files++;
926 								doit = 1;
927 							}
928 						}
929 						if (doit) {
930 							if (dirc == ' ') {
931 								printf(" %8ld   %s%c\n",
932 									(long)FAT2CPU32(dentptr->size),
933 									l_name,
934 									dirc);
935 							} else {
936 								printf("            %s%c\n",
937 									l_name,
938 									dirc);
939 							}
940 						}
941 						dentptr++;
942 						continue;
943 					}
944 					debug("Rootvfatname: |%s|\n",
945 					       l_name);
946 				} else
947 #endif
948 				{
949 					/* Volume label or VFAT entry */
950 					dentptr++;
951 					continue;
952 				}
953 			} else if (dentptr->name[0] == 0) {
954 				debug("RootDentname == NULL - %d\n", i);
955 				if (dols == LS_ROOT) {
956 					printf("\n%d file(s), %d dir(s)\n\n",
957 						files, dirs);
958 					ret = 0;
959 				}
960 				goto exit;
961 			}
962 #ifdef CONFIG_SUPPORT_VFAT
963 			else if (dols == LS_ROOT &&
964 				 mkcksum(dentptr->name) == prevcksum) {
965 				dentptr++;
966 				continue;
967 			}
968 #endif
969 			get_name(dentptr, s_name);
970 
971 			if (dols == LS_ROOT) {
972 				int isdir = (dentptr->attr & ATTR_DIR);
973 				char dirc;
974 				int doit = 0;
975 
976 				if (isdir) {
977 					dirc = '/';
978 					if (s_name[0] != 0) {
979 						dirs++;
980 						doit = 1;
981 					}
982 				} else {
983 					dirc = ' ';
984 					if (s_name[0] != 0) {
985 						files++;
986 						doit = 1;
987 					}
988 				}
989 				if (doit) {
990 					if (dirc == ' ') {
991 						printf(" %8ld   %s%c\n",
992 							(long)FAT2CPU32(dentptr->size),
993 							s_name, dirc);
994 					} else {
995 						printf("            %s%c\n",
996 							s_name, dirc);
997 					}
998 				}
999 				dentptr++;
1000 				continue;
1001 			}
1002 
1003 			if (strcmp(fnamecopy, s_name)
1004 			    && strcmp(fnamecopy, l_name)) {
1005 				debug("RootMismatch: |%s|%s|\n", s_name,
1006 				       l_name);
1007 				dentptr++;
1008 				continue;
1009 			}
1010 
1011 			if (isdir && !(dentptr->attr & ATTR_DIR))
1012 				goto exit;
1013 
1014 			debug("RootName: %s", s_name);
1015 			debug(", start: 0x%x", START(dentptr));
1016 			debug(", size:  0x%x %s\n",
1017 			       FAT2CPU32(dentptr->size),
1018 			       isdir ? "(DIR)" : "");
1019 
1020 			goto rootdir_done;	/* We got a match */
1021 		}
1022 		debug("END LOOP: j=%d   clust_size=%d\n", j,
1023 		       mydata->clust_size);
1024 
1025 		/*
1026 		 * On FAT32 we must fetch the FAT entries for the next
1027 		 * root directory clusters when a cluster has been
1028 		 * completely processed.
1029 		 */
1030 		++j;
1031 		int fat32_end = 0;
1032 		if ((mydata->fatsize == 32) && (j == mydata->clust_size)) {
1033 			int nxtsect = 0;
1034 			int nxt_clust = 0;
1035 
1036 			nxt_clust = get_fatent(mydata, root_cluster);
1037 			fat32_end = CHECK_CLUST(nxt_clust, 32);
1038 
1039 			nxtsect = mydata->data_begin +
1040 				(nxt_clust * mydata->clust_size);
1041 
1042 			root_cluster = nxt_clust;
1043 
1044 			cursect = nxtsect;
1045 			j = 0;
1046 		} else {
1047 			cursect++;
1048 		}
1049 
1050 		/* If end of rootdir reached */
1051 		if ((mydata->fatsize == 32 && fat32_end) ||
1052 		    (mydata->fatsize != 32 && j == rootdir_size)) {
1053 			if (dols == LS_ROOT) {
1054 				printf("\n%d file(s), %d dir(s)\n\n",
1055 				       files, dirs);
1056 				ret = 0;
1057 			}
1058 			goto exit;
1059 		}
1060 	}
1061 rootdir_done:
1062 
1063 	firsttime = 1;
1064 
1065 	while (isdir) {
1066 		int startsect = mydata->data_begin
1067 			+ START(dentptr) * mydata->clust_size;
1068 		dir_entry dent;
1069 		char *nextname = NULL;
1070 
1071 		dent = *dentptr;
1072 		dentptr = &dent;
1073 
1074 		idx = dirdelim(subname);
1075 
1076 		if (idx >= 0) {
1077 			subname[idx] = '\0';
1078 			nextname = subname + idx + 1;
1079 			/* Handle multiple delimiters */
1080 			while (ISDIRDELIM(*nextname))
1081 				nextname++;
1082 			if (dols && *nextname == '\0')
1083 				firsttime = 0;
1084 		} else {
1085 			if (dols && firsttime) {
1086 				firsttime = 0;
1087 			} else {
1088 				isdir = 0;
1089 			}
1090 		}
1091 
1092 		if (get_dentfromdir(mydata, startsect, subname, dentptr,
1093 				     isdir ? 0 : dols) == NULL) {
1094 			if (dols && !isdir)
1095 				ret = 0;
1096 			goto exit;
1097 		}
1098 
1099 		if (idx >= 0) {
1100 			if (!(dentptr->attr & ATTR_DIR))
1101 				goto exit;
1102 			subname = nextname;
1103 		}
1104 	}
1105 
1106 	ret = get_contents(mydata, dentptr, buffer, maxsize);
1107 	debug("Size: %d, got: %ld\n", FAT2CPU32(dentptr->size), ret);
1108 
1109 exit:
1110 	free(mydata->fatbuf);
1111 	return ret;
1112 }
1113 
1114 int file_fat_detectfs (void)
1115 {
1116 	boot_sector bs;
1117 	volume_info volinfo;
1118 	int fatsize;
1119 	char vol_label[12];
1120 
1121 	if (cur_dev == NULL) {
1122 		printf("No current device\n");
1123 		return 1;
1124 	}
1125 
1126 #if defined(CONFIG_CMD_IDE) || \
1127     defined(CONFIG_CMD_MG_DISK) || \
1128     defined(CONFIG_CMD_SATA) || \
1129     defined(CONFIG_CMD_SCSI) || \
1130     defined(CONFIG_CMD_USB) || \
1131     defined(CONFIG_MMC)
1132 	printf("Interface:  ");
1133 	switch (cur_dev->if_type) {
1134 	case IF_TYPE_IDE:
1135 		printf("IDE");
1136 		break;
1137 	case IF_TYPE_SATA:
1138 		printf("SATA");
1139 		break;
1140 	case IF_TYPE_SCSI:
1141 		printf("SCSI");
1142 		break;
1143 	case IF_TYPE_ATAPI:
1144 		printf("ATAPI");
1145 		break;
1146 	case IF_TYPE_USB:
1147 		printf("USB");
1148 		break;
1149 	case IF_TYPE_DOC:
1150 		printf("DOC");
1151 		break;
1152 	case IF_TYPE_MMC:
1153 		printf("MMC");
1154 		break;
1155 	default:
1156 		printf("Unknown");
1157 	}
1158 
1159 	printf("\n  Device %d: ", cur_dev->dev);
1160 	dev_print(cur_dev);
1161 #endif
1162 
1163 	if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
1164 		printf("\nNo valid FAT fs found\n");
1165 		return 1;
1166 	}
1167 
1168 	memcpy(vol_label, volinfo.volume_label, 11);
1169 	vol_label[11] = '\0';
1170 	volinfo.fs_type[5] = '\0';
1171 
1172 	printf("Partition %d: Filesystem: %s \"%s\"\n", cur_part,
1173 		volinfo.fs_type, vol_label);
1174 
1175 	return 0;
1176 }
1177 
1178 int file_fat_ls (const char *dir)
1179 {
1180 	return do_fat_read(dir, NULL, 0, LS_YES);
1181 }
1182 
1183 long file_fat_read (const char *filename, void *buffer, unsigned long maxsize)
1184 {
1185 	printf("reading %s\n", filename);
1186 	return do_fat_read(filename, buffer, maxsize, LS_NO);
1187 }
1188