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