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