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