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