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