xref: /rk3399_rockchip-uboot/fs/fat/fat.c (revision c3f9d4939af90eb8e30119601c86c05bde6c7345)
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)
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->attr & ATTR_VOLUME)) {
539 #ifdef CONFIG_SUPPORT_VFAT
540 		if ((dentptr->attr & ATTR_VFAT) &&
541 		    (dentptr->name[0] & LAST_LONG_ENTRY_MASK)) {
542 		    prevcksum = ((dir_slot *) dentptr)
543 			    ->alias_checksum;
544 		    get_vfatname (mydata, curclust, get_dentfromdir_block,
545 				  dentptr, l_name);
546 		    if (dols) {
547 			int isdir = (dentptr->attr & ATTR_DIR);
548 			char dirc;
549 			int doit = 0;
550 
551 			if (isdir) {
552 			    dirs++;
553 			    dirc = '/';
554 			    doit = 1;
555 			} else {
556 			    dirc = ' ';
557 			    if (l_name[0] != 0) {
558 				files++;
559 				doit = 1;
560 			    }
561 			}
562 			if (doit) {
563 			    if (dirc == ' ') {
564 				printf (" %8ld   %s%c\n",
565 					(long) FAT2CPU32 (dentptr->size),
566 					l_name, dirc);
567 			    } else {
568 				printf ("            %s%c\n", l_name, dirc);
569 			    }
570 			}
571 			dentptr++;
572 			continue;
573 		    }
574 		    FAT_DPRINT ("vfatname: |%s|\n", l_name);
575 		} else
576 #endif
577 		{
578 		    /* Volume label or VFAT entry */
579 		    dentptr++;
580 		    continue;
581 		}
582 	    }
583 	    if (dentptr->name[0] == 0) {
584 		if (dols) {
585 		    printf ("\n%d file(s), %d dir(s)\n\n", files, dirs);
586 		}
587 		FAT_DPRINT ("Dentname == NULL - %d\n", i);
588 		return NULL;
589 	    }
590 #ifdef CONFIG_SUPPORT_VFAT
591 	    if (dols && mkcksum (dentptr->name) == prevcksum) {
592 		dentptr++;
593 		continue;
594 	    }
595 #endif
596 	    get_name (dentptr, s_name);
597 	    if (dols) {
598 		int isdir = (dentptr->attr & ATTR_DIR);
599 		char dirc;
600 		int doit = 0;
601 
602 		if (isdir) {
603 		    dirs++;
604 		    dirc = '/';
605 		    doit = 1;
606 		} else {
607 		    dirc = ' ';
608 		    if (s_name[0] != 0) {
609 			files++;
610 			doit = 1;
611 		    }
612 		}
613 		if (doit) {
614 		    if (dirc == ' ') {
615 			printf (" %8ld   %s%c\n",
616 				(long) FAT2CPU32 (dentptr->size), s_name,
617 				dirc);
618 		    } else {
619 			printf ("            %s%c\n", s_name, dirc);
620 		    }
621 		}
622 		dentptr++;
623 		continue;
624 	    }
625 	    if (strcmp (filename, s_name) && strcmp (filename, l_name)) {
626 		FAT_DPRINT ("Mismatch: |%s|%s|\n", s_name, l_name);
627 		dentptr++;
628 		continue;
629 	    }
630 	    memcpy (retdent, dentptr, sizeof (dir_entry));
631 
632 	    FAT_DPRINT ("DentName: %s", s_name);
633 	    FAT_DPRINT (", start: 0x%x", START (dentptr));
634 	    FAT_DPRINT (", size:  0x%x %s\n",
635 			FAT2CPU32 (dentptr->size),
636 			(dentptr->attr & ATTR_DIR) ? "(DIR)" : "");
637 
638 	    return retdent;
639 	}
640 	curclust = get_fatent (mydata, curclust);
641 	if (curclust <= 0x0001 || curclust >= 0xfff0) {
642 	    FAT_DPRINT ("curclust: 0x%x\n", curclust);
643 	    FAT_ERROR ("Invalid FAT entry\n");
644 	    return NULL;
645 	}
646     }
647 
648     return NULL;
649 }
650 
651 
652 /*
653  * Read boot sector and volume info from a FAT filesystem
654  */
655 static int
656 read_bootsectandvi(boot_sector *bs, volume_info *volinfo, int *fatsize)
657 {
658 	__u8 block[FS_BLOCK_SIZE];
659 	volume_info *vistart;
660 
661 	if (disk_read(0, 1, block) < 0) {
662 		FAT_DPRINT("Error: reading block\n");
663 		return -1;
664 	}
665 
666 	memcpy(bs, block, sizeof(boot_sector));
667 	bs->reserved	= FAT2CPU16(bs->reserved);
668 	bs->fat_length	= FAT2CPU16(bs->fat_length);
669 	bs->secs_track	= FAT2CPU16(bs->secs_track);
670 	bs->heads	= FAT2CPU16(bs->heads);
671 #if 0 /* UNUSED */
672 	bs->hidden	= FAT2CPU32(bs->hidden);
673 #endif
674 	bs->total_sect	= FAT2CPU32(bs->total_sect);
675 
676 	/* FAT32 entries */
677 	if (bs->fat_length == 0) {
678 		/* Assume FAT32 */
679 		bs->fat32_length = FAT2CPU32(bs->fat32_length);
680 		bs->flags	 = FAT2CPU16(bs->flags);
681 		bs->root_cluster = FAT2CPU32(bs->root_cluster);
682 		bs->info_sector  = FAT2CPU16(bs->info_sector);
683 		bs->backup_boot  = FAT2CPU16(bs->backup_boot);
684 		vistart = (volume_info*) (block + sizeof(boot_sector));
685 		*fatsize = 32;
686 	} else {
687 		vistart = (volume_info*) &(bs->fat32_length);
688 		*fatsize = 0;
689 	}
690 	memcpy(volinfo, vistart, sizeof(volume_info));
691 
692 	/* Terminate fs_type string. Writing past the end of vistart
693 	   is ok - it's just the buffer. */
694 	vistart->fs_type[8] = '\0';
695 
696 	if (*fatsize == 32) {
697 		if (compare_sign(FAT32_SIGN, vistart->fs_type) == 0) {
698 			return 0;
699 		}
700 	} else {
701 		if (compare_sign(FAT12_SIGN, vistart->fs_type) == 0) {
702 			*fatsize = 12;
703 			return 0;
704 		}
705 		if (compare_sign(FAT16_SIGN, vistart->fs_type) == 0) {
706 			*fatsize = 16;
707 			return 0;
708 		}
709 	}
710 
711 	FAT_DPRINT("Error: broken fs_type sign\n");
712 	return -1;
713 }
714 
715 
716 __u8 do_fat_read_block[MAX_CLUSTSIZE];  /* Block buffer */
717 static long
718 do_fat_read (const char *filename, void *buffer, unsigned long maxsize,
719 	     int dols)
720 {
721     char fnamecopy[2048];
722     boot_sector bs;
723     volume_info volinfo;
724     fsdata datablock;
725     fsdata *mydata = &datablock;
726     dir_entry *dentptr;
727     __u16 prevcksum = 0xffff;
728     char *subname = "";
729     int rootdir_size, cursect;
730     int idx, isdir = 0;
731     int files = 0, dirs = 0;
732     long ret = 0;
733     int firsttime;
734 
735     if (read_bootsectandvi (&bs, &volinfo, &mydata->fatsize)) {
736 	FAT_DPRINT ("Error: reading boot sector\n");
737 	return -1;
738     }
739     if (mydata->fatsize == 32) {
740 	mydata->fatlength = bs.fat32_length;
741     } else {
742 	mydata->fatlength = bs.fat_length;
743     }
744     mydata->fat_sect = bs.reserved;
745     cursect = mydata->rootdir_sect
746 	    = mydata->fat_sect + mydata->fatlength * bs.fats;
747     mydata->clust_size = bs.cluster_size;
748     if (mydata->fatsize == 32) {
749 	rootdir_size = mydata->clust_size;
750 	mydata->data_begin = mydata->rootdir_sect   /* + rootdir_size */
751 		- (mydata->clust_size * 2);
752     } else {
753 	rootdir_size = ((bs.dir_entries[1] * (int) 256 + bs.dir_entries[0])
754 			* sizeof (dir_entry)) / SECTOR_SIZE;
755 	mydata->data_begin = mydata->rootdir_sect + rootdir_size
756 		- (mydata->clust_size * 2);
757     }
758     mydata->fatbufnum = -1;
759 
760     FAT_DPRINT ("FAT%d, fatlength: %d\n", mydata->fatsize,
761 		mydata->fatlength);
762     FAT_DPRINT ("Rootdir begins at sector: %d, offset: %x, size: %d\n"
763 		"Data begins at: %d\n",
764 		mydata->rootdir_sect, mydata->rootdir_sect * SECTOR_SIZE,
765 		rootdir_size, mydata->data_begin);
766     FAT_DPRINT ("Cluster size: %d\n", mydata->clust_size);
767 
768     /* "cwd" is always the root... */
769     while (ISDIRDELIM (*filename))
770 	filename++;
771     /* Make a copy of the filename and convert it to lowercase */
772     strcpy (fnamecopy, filename);
773     downcase (fnamecopy);
774     if (*fnamecopy == '\0') {
775 	if (!dols)
776 	    return -1;
777 	dols = LS_ROOT;
778     } else if ((idx = dirdelim (fnamecopy)) >= 0) {
779 	isdir = 1;
780 	fnamecopy[idx] = '\0';
781 	subname = fnamecopy + idx + 1;
782 	/* Handle multiple delimiters */
783 	while (ISDIRDELIM (*subname))
784 	    subname++;
785     } else if (dols) {
786 	isdir = 1;
787     }
788 
789     while (1) {
790 	int i;
791 
792 	if (disk_read (cursect, mydata->clust_size, do_fat_read_block) < 0) {
793 	    FAT_DPRINT ("Error: reading rootdir block\n");
794 	    return -1;
795 	}
796 	dentptr = (dir_entry *) do_fat_read_block;
797 	for (i = 0; i < DIRENTSPERBLOCK; i++) {
798 	    char s_name[14], l_name[256];
799 
800 	    l_name[0] = '\0';
801 	    if ((dentptr->attr & ATTR_VOLUME)) {
802 #ifdef CONFIG_SUPPORT_VFAT
803 		if ((dentptr->attr & ATTR_VFAT) &&
804 		    (dentptr->name[0] & LAST_LONG_ENTRY_MASK)) {
805 		    prevcksum = ((dir_slot *) dentptr)->alias_checksum;
806 		    get_vfatname (mydata, 0, do_fat_read_block, dentptr, l_name);
807 		    if (dols == LS_ROOT) {
808 			int isdir = (dentptr->attr & ATTR_DIR);
809 			char dirc;
810 			int doit = 0;
811 
812 			if (isdir) {
813 			    dirs++;
814 			    dirc = '/';
815 			    doit = 1;
816 			} else {
817 			    dirc = ' ';
818 			    if (l_name[0] != 0) {
819 				files++;
820 				doit = 1;
821 			    }
822 			}
823 			if (doit) {
824 			    if (dirc == ' ') {
825 				printf (" %8ld   %s%c\n",
826 					(long) FAT2CPU32 (dentptr->size),
827 					l_name, dirc);
828 			    } else {
829 				printf ("            %s%c\n", l_name, dirc);
830 			    }
831 			}
832 			dentptr++;
833 			continue;
834 		    }
835 		    FAT_DPRINT ("Rootvfatname: |%s|\n", l_name);
836 		} else
837 #endif
838 		{
839 		    /* Volume label or VFAT entry */
840 		    dentptr++;
841 		    continue;
842 		}
843 	    } else if (dentptr->name[0] == 0) {
844 		FAT_DPRINT ("RootDentname == NULL - %d\n", i);
845 		if (dols == LS_ROOT) {
846 		    printf ("\n%d file(s), %d dir(s)\n\n", files, dirs);
847 		    return 0;
848 		}
849 		return -1;
850 	    }
851 #ifdef CONFIG_SUPPORT_VFAT
852 	    else if (dols == LS_ROOT
853 		     && mkcksum (dentptr->name) == prevcksum) {
854 		dentptr++;
855 		continue;
856 	    }
857 #endif
858 	    get_name (dentptr, s_name);
859 	    if (dols == LS_ROOT) {
860 		int isdir = (dentptr->attr & ATTR_DIR);
861 		char dirc;
862 		int doit = 0;
863 
864 		if (isdir) {
865 		    dirc = '/';
866 		    if (s_name[0] != 0) {
867 			dirs++;
868 			doit = 1;
869 		    }
870 		} else {
871 		    dirc = ' ';
872 		    if (s_name[0] != 0) {
873 			files++;
874 			doit = 1;
875 		    }
876 		}
877 		if (doit) {
878 		    if (dirc == ' ') {
879 			printf (" %8ld   %s%c\n",
880 				(long) FAT2CPU32 (dentptr->size), s_name,
881 				dirc);
882 		    } else {
883 			printf ("            %s%c\n", s_name, dirc);
884 		    }
885 		}
886 		dentptr++;
887 		continue;
888 	    }
889 	    if (strcmp (fnamecopy, s_name) && strcmp (fnamecopy, l_name)) {
890 		FAT_DPRINT ("RootMismatch: |%s|%s|\n", s_name, l_name);
891 		dentptr++;
892 		continue;
893 	    }
894 	    if (isdir && !(dentptr->attr & ATTR_DIR))
895 		return -1;
896 
897 	    FAT_DPRINT ("RootName: %s", s_name);
898 	    FAT_DPRINT (", start: 0x%x", START (dentptr));
899 	    FAT_DPRINT (", size:  0x%x %s\n",
900 			FAT2CPU32 (dentptr->size), isdir ? "(DIR)" : "");
901 
902 	    goto rootdir_done;  /* We got a match */
903 	}
904 	cursect++;
905     }
906   rootdir_done:
907 
908     firsttime = 1;
909     while (isdir) {
910 	int startsect = mydata->data_begin
911 		+ START (dentptr) * mydata->clust_size;
912 	dir_entry dent;
913 	char *nextname = NULL;
914 
915 	dent = *dentptr;
916 	dentptr = &dent;
917 
918 	idx = dirdelim (subname);
919 	if (idx >= 0) {
920 	    subname[idx] = '\0';
921 	    nextname = subname + idx + 1;
922 	    /* Handle multiple delimiters */
923 	    while (ISDIRDELIM (*nextname))
924 		nextname++;
925 	    if (dols && *nextname == '\0')
926 		firsttime = 0;
927 	} else {
928 	    if (dols && firsttime) {
929 		firsttime = 0;
930 	    } else {
931 		isdir = 0;
932 	    }
933 	}
934 
935 	if (get_dentfromdir (mydata, startsect, subname, dentptr,
936 			     isdir ? 0 : dols) == NULL) {
937 	    if (dols && !isdir)
938 		return 0;
939 	    return -1;
940 	}
941 
942 	if (idx >= 0) {
943 	    if (!(dentptr->attr & ATTR_DIR))
944 		return -1;
945 	    subname = nextname;
946 	}
947     }
948     ret = get_contents (mydata, dentptr, buffer, maxsize);
949     FAT_DPRINT ("Size: %d, got: %ld\n", FAT2CPU32 (dentptr->size), ret);
950 
951     return ret;
952 }
953 
954 
955 int
956 file_fat_detectfs(void)
957 {
958 	boot_sector	bs;
959 	volume_info	volinfo;
960 	int		fatsize;
961 	char	vol_label[12];
962 
963 	if(cur_dev==NULL) {
964 		printf("No current device\n");
965 		return 1;
966 	}
967 #if (CONFIG_COMMANDS & CFG_CMD_IDE) || (CONFIG_COMMANDS & CFG_CMD_SCSI) || \
968     (CONFIG_COMMANDS & CFG_CMD_USB) || (CONFIG_MMC)
969 	printf("Interface:  ");
970 	switch(cur_dev->if_type) {
971 		case IF_TYPE_IDE :	printf("IDE"); break;
972 		case IF_TYPE_SCSI :	printf("SCSI"); break;
973 		case IF_TYPE_ATAPI :	printf("ATAPI"); break;
974 		case IF_TYPE_USB :	printf("USB"); break;
975 		case IF_TYPE_DOC :	printf("DOC"); break;
976 		case IF_TYPE_MMC :	printf("MMC"); break;
977 		default :		printf("Unknown");
978 	}
979 	printf("\n  Device %d: ",cur_dev->dev);
980 	dev_print(cur_dev);
981 #endif
982 	if(read_bootsectandvi(&bs, &volinfo, &fatsize)) {
983 		printf("\nNo valid FAT fs found\n");
984 		return 1;
985 	}
986 	memcpy (vol_label, volinfo.volume_label, 11);
987 	vol_label[11] = '\0';
988 	volinfo.fs_type[5]='\0';
989 	printf("Partition %d: Filesystem: %s \"%s\"\n",cur_part,volinfo.fs_type,vol_label);
990 	return 0;
991 }
992 
993 
994 int
995 file_fat_ls(const char *dir)
996 {
997 	return do_fat_read(dir, NULL, 0, LS_YES);
998 }
999 
1000 
1001 long
1002 file_fat_read(const char *filename, void *buffer, unsigned long maxsize)
1003 {
1004 	printf("reading %s\n",filename);
1005 	return do_fat_read(filename, buffer, maxsize, LS_NO);
1006 }
1007 
1008 #endif /* #if (CONFIG_COMMANDS & CFG_CMD_FAT) */
1009