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