fs/fat: Fix FAT detection to support non-DOS partition tables
[oweals/u-boot.git] / fs / fat / fat.c
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 <exports.h>
31 #include <fat.h>
32 #include <asm/byteorder.h>
33 #include <part.h>
34
35 /*
36  * Convert a string to lowercase.
37  */
38 static void downcase (char *str)
39 {
40         while (*str != '\0') {
41                 TOLOWER(*str);
42                 str++;
43         }
44 }
45
46 static block_dev_desc_t *cur_dev;
47 static unsigned int cur_part_nr;
48 static disk_partition_t cur_part_info;
49
50 #define DOS_BOOT_MAGIC_OFFSET   0x1fe
51 #define DOS_FS_TYPE_OFFSET      0x36
52 #define DOS_FS32_TYPE_OFFSET    0x52
53
54 static int disk_read(__u32 block, __u32 nr_blocks, void *buf)
55 {
56         if (!cur_dev || !cur_dev->block_read)
57                 return -1;
58
59         return cur_dev->block_read(cur_dev->dev,
60                         cur_part_info.start + block, nr_blocks, buf);
61 }
62
63 int fat_register_device (block_dev_desc_t * dev_desc, int part_no)
64 {
65         unsigned char buffer[dev_desc->blksz];
66
67         /* First close any currently found FAT filesystem */
68         cur_dev = NULL;
69
70 #if (defined(CONFIG_CMD_IDE) || \
71      defined(CONFIG_CMD_MG_DISK) || \
72      defined(CONFIG_CMD_SATA) || \
73      defined(CONFIG_CMD_SCSI) || \
74      defined(CONFIG_CMD_USB) || \
75      defined(CONFIG_MMC) || \
76      defined(CONFIG_SYSTEMACE) )
77
78         /* Read the partition table, if present */
79         if (!get_partition_info(dev_desc, part_no, &cur_part_info)) {
80                 cur_dev = dev_desc;
81                 cur_part_nr = part_no;
82         }
83 #endif
84
85         /* Otherwise it might be a superfloppy (whole-disk FAT filesystem) */
86         if (!cur_dev) {
87                 if (part_no != 1) {
88                         printf("** Partition %d not valid on device %d **\n",
89                                         part_no, dev_desc->dev);
90                         return -1;
91                 }
92
93                 cur_dev = dev_desc;
94                 cur_part_nr = 1;
95                 cur_part_info.start = 0;
96                 cur_part_info.size = dev_desc->lba;
97                 cur_part_info.blksz = dev_desc->blksz;
98                 memset(cur_part_info.name, 0, sizeof(cur_part_info.name));
99                 memset(cur_part_info.type, 0, sizeof(cur_part_info.type));
100         }
101
102         /* Make sure it has a valid FAT header */
103         if (disk_read(0, 1, buffer) != 1) {
104                 cur_dev = NULL;
105                 return -1;
106         }
107
108         /* Check if it's actually a DOS volume */
109         if (memcmp(buffer + DOS_BOOT_MAGIC_OFFSET, "\x55\xAA", 2)) {
110                 cur_dev = NULL;
111                 return -1;
112         }
113
114         /* Check for FAT12/FAT16/FAT32 filesystem */
115         if (!memcmp(buffer + DOS_FS_TYPE_OFFSET, "FAT", 3))
116                 return 0;
117         if (!memcmp(buffer + DOS_FS32_TYPE_OFFSET, "FAT32", 5))
118                 return 0;
119
120         cur_dev = NULL;
121         return -1;
122 }
123
124
125 /*
126  * Get the first occurence of a directory delimiter ('/' or '\') in a string.
127  * Return index into string if found, -1 otherwise.
128  */
129 static int dirdelim (char *str)
130 {
131         char *start = str;
132
133         while (*str != '\0') {
134                 if (ISDIRDELIM(*str))
135                         return str - start;
136                 str++;
137         }
138         return -1;
139 }
140
141 /*
142  * Extract zero terminated short name from a directory entry.
143  */
144 static void get_name (dir_entry *dirent, char *s_name)
145 {
146         char *ptr;
147
148         memcpy(s_name, dirent->name, 8);
149         s_name[8] = '\0';
150         ptr = s_name;
151         while (*ptr && *ptr != ' ')
152                 ptr++;
153         if (dirent->ext[0] && dirent->ext[0] != ' ') {
154                 *ptr = '.';
155                 ptr++;
156                 memcpy(ptr, dirent->ext, 3);
157                 ptr[3] = '\0';
158                 while (*ptr && *ptr != ' ')
159                         ptr++;
160         }
161         *ptr = '\0';
162         if (*s_name == DELETED_FLAG)
163                 *s_name = '\0';
164         else if (*s_name == aRING)
165                 *s_name = DELETED_FLAG;
166         downcase(s_name);
167 }
168
169 /*
170  * Get the entry at index 'entry' in a FAT (12/16/32) table.
171  * On failure 0x00 is returned.
172  */
173 static __u32 get_fatent (fsdata *mydata, __u32 entry)
174 {
175         __u32 bufnum;
176         __u32 off16, offset;
177         __u32 ret = 0x00;
178         __u16 val1, val2;
179
180         switch (mydata->fatsize) {
181         case 32:
182                 bufnum = entry / FAT32BUFSIZE;
183                 offset = entry - bufnum * FAT32BUFSIZE;
184                 break;
185         case 16:
186                 bufnum = entry / FAT16BUFSIZE;
187                 offset = entry - bufnum * FAT16BUFSIZE;
188                 break;
189         case 12:
190                 bufnum = entry / FAT12BUFSIZE;
191                 offset = entry - bufnum * FAT12BUFSIZE;
192                 break;
193
194         default:
195                 /* Unsupported FAT size */
196                 return ret;
197         }
198
199         debug("FAT%d: entry: 0x%04x = %d, offset: 0x%04x = %d\n",
200                mydata->fatsize, entry, entry, offset, offset);
201
202         /* Read a new block of FAT entries into the cache. */
203         if (bufnum != mydata->fatbufnum) {
204                 __u32 getsize = FATBUFBLOCKS;
205                 __u8 *bufptr = mydata->fatbuf;
206                 __u32 fatlength = mydata->fatlength;
207                 __u32 startblock = bufnum * FATBUFBLOCKS;
208
209                 if (getsize > fatlength)
210                         getsize = fatlength;
211
212                 fatlength *= mydata->sect_size; /* We want it in bytes now */
213                 startblock += mydata->fat_sect; /* Offset from start of disk */
214
215                 if (disk_read(startblock, getsize, bufptr) < 0) {
216                         debug("Error reading FAT blocks\n");
217                         return ret;
218                 }
219                 mydata->fatbufnum = bufnum;
220         }
221
222         /* Get the actual entry from the table */
223         switch (mydata->fatsize) {
224         case 32:
225                 ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]);
226                 break;
227         case 16:
228                 ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]);
229                 break;
230         case 12:
231                 off16 = (offset * 3) / 4;
232
233                 switch (offset & 0x3) {
234                 case 0:
235                         ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[off16]);
236                         ret &= 0xfff;
237                         break;
238                 case 1:
239                         val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
240                         val1 &= 0xf000;
241                         val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]);
242                         val2 &= 0x00ff;
243                         ret = (val2 << 4) | (val1 >> 12);
244                         break;
245                 case 2:
246                         val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
247                         val1 &= 0xff00;
248                         val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]);
249                         val2 &= 0x000f;
250                         ret = (val2 << 8) | (val1 >> 8);
251                         break;
252                 case 3:
253                         ret = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
254                         ret = (ret & 0xfff0) >> 4;
255                         break;
256                 default:
257                         break;
258                 }
259                 break;
260         }
261         debug("FAT%d: ret: %08x, offset: %04x\n",
262                mydata->fatsize, ret, offset);
263
264         return ret;
265 }
266
267 /*
268  * Read at most 'size' bytes from the specified cluster into 'buffer'.
269  * Return 0 on success, -1 otherwise.
270  */
271 static int
272 get_cluster (fsdata *mydata, __u32 clustnum, __u8 *buffer,
273              unsigned long size)
274 {
275         __u32 idx = 0;
276         __u32 startsect;
277
278         if (clustnum > 0) {
279                 startsect = mydata->data_begin +
280                                 clustnum * mydata->clust_size;
281         } else {
282                 startsect = mydata->rootdir_sect;
283         }
284
285         debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect);
286
287         if (disk_read(startsect, size / mydata->sect_size, buffer) < 0) {
288                 debug("Error reading data\n");
289                 return -1;
290         }
291         if (size % mydata->sect_size) {
292                 __u8 tmpbuf[mydata->sect_size];
293
294                 idx = size / mydata->sect_size;
295                 if (disk_read(startsect + idx, 1, tmpbuf) < 0) {
296                         debug("Error reading data\n");
297                         return -1;
298                 }
299                 buffer += idx * mydata->sect_size;
300
301                 memcpy(buffer, tmpbuf, size % mydata->sect_size);
302                 return 0;
303         }
304
305         return 0;
306 }
307
308 /*
309  * Read at most 'maxsize' bytes from the file associated with 'dentptr'
310  * into 'buffer'.
311  * Return the number of bytes read or -1 on fatal errors.
312  */
313 static long
314 get_contents (fsdata *mydata, dir_entry *dentptr, __u8 *buffer,
315               unsigned long maxsize)
316 {
317         unsigned long filesize = FAT2CPU32(dentptr->size), gotsize = 0;
318         unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
319         __u32 curclust = START(dentptr);
320         __u32 endclust, newclust;
321         unsigned long actsize;
322
323         debug("Filesize: %ld bytes\n", filesize);
324
325         if (maxsize > 0 && filesize > maxsize)
326                 filesize = maxsize;
327
328         debug("%ld bytes\n", filesize);
329
330         actsize = bytesperclust;
331         endclust = curclust;
332
333         do {
334                 /* search for consecutive clusters */
335                 while (actsize < filesize) {
336                         newclust = get_fatent(mydata, endclust);
337                         if ((newclust - 1) != endclust)
338                                 goto getit;
339                         if (CHECK_CLUST(newclust, mydata->fatsize)) {
340                                 debug("curclust: 0x%x\n", newclust);
341                                 debug("Invalid FAT entry\n");
342                                 return gotsize;
343                         }
344                         endclust = newclust;
345                         actsize += bytesperclust;
346                 }
347
348                 /* actsize >= file size */
349                 actsize -= bytesperclust;
350
351                 /* get remaining clusters */
352                 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
353                         printf("Error reading cluster\n");
354                         return -1;
355                 }
356
357                 /* get remaining bytes */
358                 gotsize += (int)actsize;
359                 filesize -= actsize;
360                 buffer += actsize;
361                 actsize = filesize;
362                 if (get_cluster(mydata, endclust, buffer, (int)actsize) != 0) {
363                         printf("Error reading cluster\n");
364                         return -1;
365                 }
366                 gotsize += actsize;
367                 return gotsize;
368 getit:
369                 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
370                         printf("Error reading cluster\n");
371                         return -1;
372                 }
373                 gotsize += (int)actsize;
374                 filesize -= actsize;
375                 buffer += actsize;
376
377                 curclust = get_fatent(mydata, endclust);
378                 if (CHECK_CLUST(curclust, mydata->fatsize)) {
379                         debug("curclust: 0x%x\n", curclust);
380                         printf("Invalid FAT entry\n");
381                         return gotsize;
382                 }
383                 actsize = bytesperclust;
384                 endclust = curclust;
385         } while (1);
386 }
387
388 #ifdef CONFIG_SUPPORT_VFAT
389 /*
390  * Extract the file name information from 'slotptr' into 'l_name',
391  * starting at l_name[*idx].
392  * Return 1 if terminator (zero byte) is found, 0 otherwise.
393  */
394 static int slot2str (dir_slot *slotptr, char *l_name, int *idx)
395 {
396         int j;
397
398         for (j = 0; j <= 8; j += 2) {
399                 l_name[*idx] = slotptr->name0_4[j];
400                 if (l_name[*idx] == 0x00)
401                         return 1;
402                 (*idx)++;
403         }
404         for (j = 0; j <= 10; j += 2) {
405                 l_name[*idx] = slotptr->name5_10[j];
406                 if (l_name[*idx] == 0x00)
407                         return 1;
408                 (*idx)++;
409         }
410         for (j = 0; j <= 2; j += 2) {
411                 l_name[*idx] = slotptr->name11_12[j];
412                 if (l_name[*idx] == 0x00)
413                         return 1;
414                 (*idx)++;
415         }
416
417         return 0;
418 }
419
420 /*
421  * Extract the full long filename starting at 'retdent' (which is really
422  * a slot) into 'l_name'. If successful also copy the real directory entry
423  * into 'retdent'
424  * Return 0 on success, -1 otherwise.
425  */
426 __attribute__ ((__aligned__ (__alignof__ (dir_entry))))
427 __u8 get_vfatname_block[MAX_CLUSTSIZE];
428
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 *buflimit = cluster + mydata->sect_size * ((curclust == 0) ?
436                                                         PREFETCH_BLOCKS :
437                                                         mydata->clust_size);
438         __u8 counter = (slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff;
439         int idx = 0;
440
441         if (counter > VFAT_MAXSEQ) {
442                 debug("Error: VFAT name is too long\n");
443                 return -1;
444         }
445
446         while ((__u8 *)slotptr < buflimit) {
447                 if (counter == 0)
448                         break;
449                 if (((slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff) != counter)
450                         return -1;
451                 slotptr++;
452                 counter--;
453         }
454
455         if ((__u8 *)slotptr >= buflimit) {
456                 dir_slot *slotptr2;
457
458                 if (curclust == 0)
459                         return -1;
460                 curclust = get_fatent(mydata, curclust);
461                 if (CHECK_CLUST(curclust, mydata->fatsize)) {
462                         debug("curclust: 0x%x\n", curclust);
463                         printf("Invalid FAT entry\n");
464                         return -1;
465                 }
466
467                 if (get_cluster(mydata, curclust, get_vfatname_block,
468                                 mydata->clust_size * mydata->sect_size) != 0) {
469                         debug("Error: reading directory block\n");
470                         return -1;
471                 }
472
473                 slotptr2 = (dir_slot *)get_vfatname_block;
474                 while (counter > 0) {
475                         if (((slotptr2->id & ~LAST_LONG_ENTRY_MASK)
476                             & 0xff) != counter)
477                                 return -1;
478                         slotptr2++;
479                         counter--;
480                 }
481
482                 /* Save the real directory entry */
483                 realdent = (dir_entry *)slotptr2;
484                 while ((__u8 *)slotptr2 > get_vfatname_block) {
485                         slotptr2--;
486                         slot2str(slotptr2, l_name, &idx);
487                 }
488         } else {
489                 /* Save the real directory entry */
490                 realdent = (dir_entry *)slotptr;
491         }
492
493         do {
494                 slotptr--;
495                 if (slot2str(slotptr, l_name, &idx))
496                         break;
497         } while (!(slotptr->id & LAST_LONG_ENTRY_MASK));
498
499         l_name[idx] = '\0';
500         if (*l_name == DELETED_FLAG)
501                 *l_name = '\0';
502         else if (*l_name == aRING)
503                 *l_name = DELETED_FLAG;
504         downcase(l_name);
505
506         /* Return the real directory entry */
507         memcpy(retdent, realdent, sizeof(dir_entry));
508
509         return 0;
510 }
511
512 /* Calculate short name checksum */
513 static __u8 mkcksum (const char *str)
514 {
515         int i;
516
517         __u8 ret = 0;
518
519         for (i = 0; i < 11; i++) {
520                 ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + str[i];
521         }
522
523         return ret;
524 }
525 #endif  /* CONFIG_SUPPORT_VFAT */
526
527 /*
528  * Get the directory entry associated with 'filename' from the directory
529  * starting at 'startsect'
530  */
531 __attribute__ ((__aligned__ (__alignof__ (dir_entry))))
532 __u8 get_dentfromdir_block[MAX_CLUSTSIZE];
533
534 static dir_entry *get_dentfromdir (fsdata *mydata, int startsect,
535                                    char *filename, dir_entry *retdent,
536                                    int dols)
537 {
538         __u16 prevcksum = 0xffff;
539         __u32 curclust = START(retdent);
540         int files = 0, dirs = 0;
541
542         debug("get_dentfromdir: %s\n", filename);
543
544         while (1) {
545                 dir_entry *dentptr;
546
547                 int i;
548
549                 if (get_cluster(mydata, curclust, get_dentfromdir_block,
550                                 mydata->clust_size * mydata->sect_size) != 0) {
551                         debug("Error: reading directory block\n");
552                         return NULL;
553                 }
554
555                 dentptr = (dir_entry *)get_dentfromdir_block;
556
557                 for (i = 0; i < DIRENTSPERCLUST; i++) {
558                         char s_name[14], l_name[VFAT_MAXLEN_BYTES];
559
560                         l_name[0] = '\0';
561                         if (dentptr->name[0] == DELETED_FLAG) {
562                                 dentptr++;
563                                 continue;
564                         }
565                         if ((dentptr->attr & ATTR_VOLUME)) {
566 #ifdef CONFIG_SUPPORT_VFAT
567                                 if ((dentptr->attr & ATTR_VFAT) == ATTR_VFAT &&
568                                     (dentptr->name[0] & LAST_LONG_ENTRY_MASK)) {
569                                         prevcksum = ((dir_slot *)dentptr)->alias_checksum;
570                                         get_vfatname(mydata, curclust,
571                                                      get_dentfromdir_block,
572                                                      dentptr, l_name);
573                                         if (dols) {
574                                                 int isdir;
575                                                 char dirc;
576                                                 int doit = 0;
577
578                                                 isdir = (dentptr->attr & ATTR_DIR);
579
580                                                 if (isdir) {
581                                                         dirs++;
582                                                         dirc = '/';
583                                                         doit = 1;
584                                                 } else {
585                                                         dirc = ' ';
586                                                         if (l_name[0] != 0) {
587                                                                 files++;
588                                                                 doit = 1;
589                                                         }
590                                                 }
591                                                 if (doit) {
592                                                         if (dirc == ' ') {
593                                                                 printf(" %8ld   %s%c\n",
594                                                                         (long)FAT2CPU32(dentptr->size),
595                                                                         l_name,
596                                                                         dirc);
597                                                         } else {
598                                                                 printf("            %s%c\n",
599                                                                         l_name,
600                                                                         dirc);
601                                                         }
602                                                 }
603                                                 dentptr++;
604                                                 continue;
605                                         }
606                                         debug("vfatname: |%s|\n", l_name);
607                                 } else
608 #endif
609                                 {
610                                         /* Volume label or VFAT entry */
611                                         dentptr++;
612                                         continue;
613                                 }
614                         }
615                         if (dentptr->name[0] == 0) {
616                                 if (dols) {
617                                         printf("\n%d file(s), %d dir(s)\n\n",
618                                                 files, dirs);
619                                 }
620                                 debug("Dentname == NULL - %d\n", i);
621                                 return NULL;
622                         }
623 #ifdef CONFIG_SUPPORT_VFAT
624                         if (dols && mkcksum(dentptr->name) == prevcksum) {
625                                 prevcksum = 0xffff;
626                                 dentptr++;
627                                 continue;
628                         }
629 #endif
630                         get_name(dentptr, s_name);
631                         if (dols) {
632                                 int isdir = (dentptr->attr & ATTR_DIR);
633                                 char dirc;
634                                 int doit = 0;
635
636                                 if (isdir) {
637                                         dirs++;
638                                         dirc = '/';
639                                         doit = 1;
640                                 } else {
641                                         dirc = ' ';
642                                         if (s_name[0] != 0) {
643                                                 files++;
644                                                 doit = 1;
645                                         }
646                                 }
647
648                                 if (doit) {
649                                         if (dirc == ' ') {
650                                                 printf(" %8ld   %s%c\n",
651                                                         (long)FAT2CPU32(dentptr->size),
652                                                         s_name, dirc);
653                                         } else {
654                                                 printf("            %s%c\n",
655                                                         s_name, dirc);
656                                         }
657                                 }
658
659                                 dentptr++;
660                                 continue;
661                         }
662
663                         if (strcmp(filename, s_name)
664                             && strcmp(filename, l_name)) {
665                                 debug("Mismatch: |%s|%s|\n", s_name, l_name);
666                                 dentptr++;
667                                 continue;
668                         }
669
670                         memcpy(retdent, dentptr, sizeof(dir_entry));
671
672                         debug("DentName: %s", s_name);
673                         debug(", start: 0x%x", START(dentptr));
674                         debug(", size:  0x%x %s\n",
675                               FAT2CPU32(dentptr->size),
676                               (dentptr->attr & ATTR_DIR) ? "(DIR)" : "");
677
678                         return retdent;
679                 }
680
681                 curclust = get_fatent(mydata, curclust);
682                 if (CHECK_CLUST(curclust, mydata->fatsize)) {
683                         debug("curclust: 0x%x\n", curclust);
684                         printf("Invalid FAT entry\n");
685                         return NULL;
686                 }
687         }
688
689         return NULL;
690 }
691
692 /*
693  * Read boot sector and volume info from a FAT filesystem
694  */
695 static int
696 read_bootsectandvi (boot_sector *bs, volume_info *volinfo, int *fatsize)
697 {
698         __u8 *block;
699         volume_info *vistart;
700         int ret = 0;
701
702         if (cur_dev == NULL) {
703                 debug("Error: no device selected\n");
704                 return -1;
705         }
706
707         block = malloc(cur_dev->blksz);
708         if (block == NULL) {
709                 debug("Error: allocating block\n");
710                 return -1;
711         }
712
713         if (disk_read (0, 1, block) < 0) {
714                 debug("Error: reading block\n");
715                 goto fail;
716         }
717
718         memcpy(bs, block, sizeof(boot_sector));
719         bs->reserved = FAT2CPU16(bs->reserved);
720         bs->fat_length = FAT2CPU16(bs->fat_length);
721         bs->secs_track = FAT2CPU16(bs->secs_track);
722         bs->heads = FAT2CPU16(bs->heads);
723         bs->total_sect = FAT2CPU32(bs->total_sect);
724
725         /* FAT32 entries */
726         if (bs->fat_length == 0) {
727                 /* Assume FAT32 */
728                 bs->fat32_length = FAT2CPU32(bs->fat32_length);
729                 bs->flags = FAT2CPU16(bs->flags);
730                 bs->root_cluster = FAT2CPU32(bs->root_cluster);
731                 bs->info_sector = FAT2CPU16(bs->info_sector);
732                 bs->backup_boot = FAT2CPU16(bs->backup_boot);
733                 vistart = (volume_info *)(block + sizeof(boot_sector));
734                 *fatsize = 32;
735         } else {
736                 vistart = (volume_info *)&(bs->fat32_length);
737                 *fatsize = 0;
738         }
739         memcpy(volinfo, vistart, sizeof(volume_info));
740
741         if (*fatsize == 32) {
742                 if (strncmp(FAT32_SIGN, vistart->fs_type, SIGNLEN) == 0)
743                         goto exit;
744         } else {
745                 if (strncmp(FAT12_SIGN, vistart->fs_type, SIGNLEN) == 0) {
746                         *fatsize = 12;
747                         goto exit;
748                 }
749                 if (strncmp(FAT16_SIGN, vistart->fs_type, SIGNLEN) == 0) {
750                         *fatsize = 16;
751                         goto exit;
752                 }
753         }
754
755         debug("Error: broken fs_type sign\n");
756 fail:
757         ret = -1;
758 exit:
759         free(block);
760         return ret;
761 }
762
763 __attribute__ ((__aligned__ (__alignof__ (dir_entry))))
764 __u8 do_fat_read_block[MAX_CLUSTSIZE];
765
766 long
767 do_fat_read (const char *filename, void *buffer, unsigned long maxsize,
768              int dols)
769 {
770         char fnamecopy[2048];
771         boot_sector bs;
772         volume_info volinfo;
773         fsdata datablock;
774         fsdata *mydata = &datablock;
775         dir_entry *dentptr;
776         __u16 prevcksum = 0xffff;
777         char *subname = "";
778         __u32 cursect;
779         int idx, isdir = 0;
780         int files = 0, dirs = 0;
781         long ret = -1;
782         int firsttime;
783         __u32 root_cluster = 0;
784         int rootdir_size = 0;
785         int j;
786
787         if (read_bootsectandvi(&bs, &volinfo, &mydata->fatsize)) {
788                 debug("Error: reading boot sector\n");
789                 return -1;
790         }
791
792         if (mydata->fatsize == 32) {
793                 root_cluster = bs.root_cluster;
794                 mydata->fatlength = bs.fat32_length;
795         } else {
796                 mydata->fatlength = bs.fat_length;
797         }
798
799         mydata->fat_sect = bs.reserved;
800
801         cursect = mydata->rootdir_sect
802                 = mydata->fat_sect + mydata->fatlength * bs.fats;
803
804         mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0];
805         mydata->clust_size = bs.cluster_size;
806
807         if (mydata->fatsize == 32) {
808                 mydata->data_begin = mydata->rootdir_sect -
809                                         (mydata->clust_size * 2);
810         } else {
811                 rootdir_size = ((bs.dir_entries[1]  * (int)256 +
812                                  bs.dir_entries[0]) *
813                                  sizeof(dir_entry)) /
814                                  mydata->sect_size;
815                 mydata->data_begin = mydata->rootdir_sect +
816                                         rootdir_size -
817                                         (mydata->clust_size * 2);
818         }
819
820         mydata->fatbufnum = -1;
821         mydata->fatbuf = malloc(FATBUFSIZE);
822         if (mydata->fatbuf == NULL) {
823                 debug("Error: allocating memory\n");
824                 return -1;
825         }
826
827 #ifdef CONFIG_SUPPORT_VFAT
828         debug("VFAT Support enabled\n");
829 #endif
830         debug("FAT%d, fat_sect: %d, fatlength: %d\n",
831                mydata->fatsize, mydata->fat_sect, mydata->fatlength);
832         debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n"
833                "Data begins at: %d\n",
834                root_cluster,
835                mydata->rootdir_sect,
836                mydata->rootdir_sect * mydata->sect_size, mydata->data_begin);
837         debug("Sector size: %d, cluster size: %d\n", mydata->sect_size,
838               mydata->clust_size);
839
840         /* "cwd" is always the root... */
841         while (ISDIRDELIM(*filename))
842                 filename++;
843
844         /* Make a copy of the filename and convert it to lowercase */
845         strcpy(fnamecopy, filename);
846         downcase(fnamecopy);
847
848         if (*fnamecopy == '\0') {
849                 if (!dols)
850                         goto exit;
851
852                 dols = LS_ROOT;
853         } else if ((idx = dirdelim(fnamecopy)) >= 0) {
854                 isdir = 1;
855                 fnamecopy[idx] = '\0';
856                 subname = fnamecopy + idx + 1;
857
858                 /* Handle multiple delimiters */
859                 while (ISDIRDELIM(*subname))
860                         subname++;
861         } else if (dols) {
862                 isdir = 1;
863         }
864
865         j = 0;
866         while (1) {
867                 int i;
868
869                 debug("FAT read sect=%d, clust_size=%d, DIRENTSPERBLOCK=%zd\n",
870                         cursect, mydata->clust_size, DIRENTSPERBLOCK);
871
872                 if (disk_read(cursect,
873                                 (mydata->fatsize == 32) ?
874                                 (mydata->clust_size) :
875                                 PREFETCH_BLOCKS,
876                                 do_fat_read_block) < 0) {
877                         debug("Error: reading rootdir block\n");
878                         goto exit;
879                 }
880
881                 dentptr = (dir_entry *) do_fat_read_block;
882
883                 for (i = 0; i < DIRENTSPERBLOCK; i++) {
884                         char s_name[14], l_name[VFAT_MAXLEN_BYTES];
885
886                         l_name[0] = '\0';
887                         if (dentptr->name[0] == DELETED_FLAG) {
888                                 dentptr++;
889                                 continue;
890                         }
891                         if ((dentptr->attr & ATTR_VOLUME)) {
892 #ifdef CONFIG_SUPPORT_VFAT
893                                 if ((dentptr->attr & ATTR_VFAT) == ATTR_VFAT &&
894                                     (dentptr->name[0] & LAST_LONG_ENTRY_MASK)) {
895                                         prevcksum =
896                                                 ((dir_slot *)dentptr)->alias_checksum;
897
898                                         get_vfatname(mydata,
899                                                      root_cluster,
900                                                      do_fat_read_block,
901                                                      dentptr, l_name);
902
903                                         if (dols == LS_ROOT) {
904                                                 char dirc;
905                                                 int doit = 0;
906                                                 int isdir =
907                                                         (dentptr->attr & ATTR_DIR);
908
909                                                 if (isdir) {
910                                                         dirs++;
911                                                         dirc = '/';
912                                                         doit = 1;
913                                                 } else {
914                                                         dirc = ' ';
915                                                         if (l_name[0] != 0) {
916                                                                 files++;
917                                                                 doit = 1;
918                                                         }
919                                                 }
920                                                 if (doit) {
921                                                         if (dirc == ' ') {
922                                                                 printf(" %8ld   %s%c\n",
923                                                                         (long)FAT2CPU32(dentptr->size),
924                                                                         l_name,
925                                                                         dirc);
926                                                         } else {
927                                                                 printf("            %s%c\n",
928                                                                         l_name,
929                                                                         dirc);
930                                                         }
931                                                 }
932                                                 dentptr++;
933                                                 continue;
934                                         }
935                                         debug("Rootvfatname: |%s|\n",
936                                                l_name);
937                                 } else
938 #endif
939                                 {
940                                         /* Volume label or VFAT entry */
941                                         dentptr++;
942                                         continue;
943                                 }
944                         } else if (dentptr->name[0] == 0) {
945                                 debug("RootDentname == NULL - %d\n", i);
946                                 if (dols == LS_ROOT) {
947                                         printf("\n%d file(s), %d dir(s)\n\n",
948                                                 files, dirs);
949                                         ret = 0;
950                                 }
951                                 goto exit;
952                         }
953 #ifdef CONFIG_SUPPORT_VFAT
954                         else if (dols == LS_ROOT &&
955                                  mkcksum(dentptr->name) == prevcksum) {
956                                 prevcksum = 0xffff;
957                                 dentptr++;
958                                 continue;
959                         }
960 #endif
961                         get_name(dentptr, s_name);
962
963                         if (dols == LS_ROOT) {
964                                 int isdir = (dentptr->attr & ATTR_DIR);
965                                 char dirc;
966                                 int doit = 0;
967
968                                 if (isdir) {
969                                         dirc = '/';
970                                         if (s_name[0] != 0) {
971                                                 dirs++;
972                                                 doit = 1;
973                                         }
974                                 } else {
975                                         dirc = ' ';
976                                         if (s_name[0] != 0) {
977                                                 files++;
978                                                 doit = 1;
979                                         }
980                                 }
981                                 if (doit) {
982                                         if (dirc == ' ') {
983                                                 printf(" %8ld   %s%c\n",
984                                                         (long)FAT2CPU32(dentptr->size),
985                                                         s_name, dirc);
986                                         } else {
987                                                 printf("            %s%c\n",
988                                                         s_name, dirc);
989                                         }
990                                 }
991                                 dentptr++;
992                                 continue;
993                         }
994
995                         if (strcmp(fnamecopy, s_name)
996                             && strcmp(fnamecopy, l_name)) {
997                                 debug("RootMismatch: |%s|%s|\n", s_name,
998                                        l_name);
999                                 dentptr++;
1000                                 continue;
1001                         }
1002
1003                         if (isdir && !(dentptr->attr & ATTR_DIR))
1004                                 goto exit;
1005
1006                         debug("RootName: %s", s_name);
1007                         debug(", start: 0x%x", START(dentptr));
1008                         debug(", size:  0x%x %s\n",
1009                                FAT2CPU32(dentptr->size),
1010                                isdir ? "(DIR)" : "");
1011
1012                         goto rootdir_done;      /* We got a match */
1013                 }
1014                 debug("END LOOP: j=%d   clust_size=%d\n", j,
1015                        mydata->clust_size);
1016
1017                 /*
1018                  * On FAT32 we must fetch the FAT entries for the next
1019                  * root directory clusters when a cluster has been
1020                  * completely processed.
1021                  */
1022                 ++j;
1023                 int fat32_end = 0;
1024                 if ((mydata->fatsize == 32) && (j == mydata->clust_size)) {
1025                         int nxtsect = 0;
1026                         int nxt_clust = 0;
1027
1028                         nxt_clust = get_fatent(mydata, root_cluster);
1029                         fat32_end = CHECK_CLUST(nxt_clust, 32);
1030
1031                         nxtsect = mydata->data_begin +
1032                                 (nxt_clust * mydata->clust_size);
1033
1034                         root_cluster = nxt_clust;
1035
1036                         cursect = nxtsect;
1037                         j = 0;
1038                 } else {
1039                         cursect++;
1040                 }
1041
1042                 /* If end of rootdir reached */
1043                 if ((mydata->fatsize == 32 && fat32_end) ||
1044                     (mydata->fatsize != 32 && j == rootdir_size)) {
1045                         if (dols == LS_ROOT) {
1046                                 printf("\n%d file(s), %d dir(s)\n\n",
1047                                        files, dirs);
1048                                 ret = 0;
1049                         }
1050                         goto exit;
1051                 }
1052         }
1053 rootdir_done:
1054
1055         firsttime = 1;
1056
1057         while (isdir) {
1058                 int startsect = mydata->data_begin
1059                         + START(dentptr) * mydata->clust_size;
1060                 dir_entry dent;
1061                 char *nextname = NULL;
1062
1063                 dent = *dentptr;
1064                 dentptr = &dent;
1065
1066                 idx = dirdelim(subname);
1067
1068                 if (idx >= 0) {
1069                         subname[idx] = '\0';
1070                         nextname = subname + idx + 1;
1071                         /* Handle multiple delimiters */
1072                         while (ISDIRDELIM(*nextname))
1073                                 nextname++;
1074                         if (dols && *nextname == '\0')
1075                                 firsttime = 0;
1076                 } else {
1077                         if (dols && firsttime) {
1078                                 firsttime = 0;
1079                         } else {
1080                                 isdir = 0;
1081                         }
1082                 }
1083
1084                 if (get_dentfromdir(mydata, startsect, subname, dentptr,
1085                                      isdir ? 0 : dols) == NULL) {
1086                         if (dols && !isdir)
1087                                 ret = 0;
1088                         goto exit;
1089                 }
1090
1091                 if (idx >= 0) {
1092                         if (!(dentptr->attr & ATTR_DIR))
1093                                 goto exit;
1094                         subname = nextname;
1095                 }
1096         }
1097
1098         ret = get_contents(mydata, dentptr, buffer, maxsize);
1099         debug("Size: %d, got: %ld\n", FAT2CPU32(dentptr->size), ret);
1100
1101 exit:
1102         free(mydata->fatbuf);
1103         return ret;
1104 }
1105
1106 int file_fat_detectfs (void)
1107 {
1108         boot_sector bs;
1109         volume_info volinfo;
1110         int fatsize;
1111         char vol_label[12];
1112
1113         if (cur_dev == NULL) {
1114                 printf("No current device\n");
1115                 return 1;
1116         }
1117
1118 #if defined(CONFIG_CMD_IDE) || \
1119     defined(CONFIG_CMD_MG_DISK) || \
1120     defined(CONFIG_CMD_SATA) || \
1121     defined(CONFIG_CMD_SCSI) || \
1122     defined(CONFIG_CMD_USB) || \
1123     defined(CONFIG_MMC)
1124         printf("Interface:  ");
1125         switch (cur_dev->if_type) {
1126         case IF_TYPE_IDE:
1127                 printf("IDE");
1128                 break;
1129         case IF_TYPE_SATA:
1130                 printf("SATA");
1131                 break;
1132         case IF_TYPE_SCSI:
1133                 printf("SCSI");
1134                 break;
1135         case IF_TYPE_ATAPI:
1136                 printf("ATAPI");
1137                 break;
1138         case IF_TYPE_USB:
1139                 printf("USB");
1140                 break;
1141         case IF_TYPE_DOC:
1142                 printf("DOC");
1143                 break;
1144         case IF_TYPE_MMC:
1145                 printf("MMC");
1146                 break;
1147         default:
1148                 printf("Unknown");
1149         }
1150
1151         printf("\n  Device %d: ", cur_dev->dev);
1152         dev_print(cur_dev);
1153 #endif
1154
1155         if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
1156                 printf("\nNo valid FAT fs found\n");
1157                 return 1;
1158         }
1159
1160         memcpy(vol_label, volinfo.volume_label, 11);
1161         vol_label[11] = '\0';
1162         volinfo.fs_type[5] = '\0';
1163
1164         printf("Partition %d: Filesystem: %s \"%s\"\n", cur_part_nr,
1165                 volinfo.fs_type, vol_label);
1166
1167         return 0;
1168 }
1169
1170 int file_fat_ls (const char *dir)
1171 {
1172         return do_fat_read(dir, NULL, 0, LS_YES);
1173 }
1174
1175 long file_fat_read (const char *filename, void *buffer, unsigned long maxsize)
1176 {
1177         printf("reading %s\n", filename);
1178         return do_fat_read(filename, buffer, maxsize, LS_NO);
1179 }