common: Drop net.h from common header
[oweals/u-boot.git] / fs / fat / fat.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * fat.c
4  *
5  * R/O (V)FAT 12/16/32 filesystem implementation by Marcus Sundberg
6  *
7  * 2002-07-28 - rjones@nexus-tech.net - ported to ppcboot v1.1.6
8  * 2003-03-10 - kharris@nexus-tech.net - ported to uboot
9  */
10
11 #include <common.h>
12 #include <blk.h>
13 #include <config.h>
14 #include <exports.h>
15 #include <fat.h>
16 #include <fs.h>
17 #include <asm/byteorder.h>
18 #include <part.h>
19 #include <malloc.h>
20 #include <memalign.h>
21 #include <asm/cache.h>
22 #include <linux/compiler.h>
23 #include <linux/ctype.h>
24
25 /*
26  * Convert a string to lowercase.  Converts at most 'len' characters,
27  * 'len' may be larger than the length of 'str' if 'str' is NULL
28  * terminated.
29  */
30 static void downcase(char *str, size_t len)
31 {
32         while (*str != '\0' && len--) {
33                 *str = tolower(*str);
34                 str++;
35         }
36 }
37
38 static struct blk_desc *cur_dev;
39 static disk_partition_t cur_part_info;
40
41 #define DOS_BOOT_MAGIC_OFFSET   0x1fe
42 #define DOS_FS_TYPE_OFFSET      0x36
43 #define DOS_FS32_TYPE_OFFSET    0x52
44
45 static int disk_read(__u32 block, __u32 nr_blocks, void *buf)
46 {
47         ulong ret;
48
49         if (!cur_dev)
50                 return -1;
51
52         ret = blk_dread(cur_dev, cur_part_info.start + block, nr_blocks, buf);
53
54         if (ret != nr_blocks)
55                 return -1;
56
57         return ret;
58 }
59
60 int fat_set_blk_dev(struct blk_desc *dev_desc, disk_partition_t *info)
61 {
62         ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, dev_desc->blksz);
63
64         cur_dev = dev_desc;
65         cur_part_info = *info;
66
67         /* Make sure it has a valid FAT header */
68         if (disk_read(0, 1, buffer) != 1) {
69                 cur_dev = NULL;
70                 return -1;
71         }
72
73         /* Check if it's actually a DOS volume */
74         if (memcmp(buffer + DOS_BOOT_MAGIC_OFFSET, "\x55\xAA", 2)) {
75                 cur_dev = NULL;
76                 return -1;
77         }
78
79         /* Check for FAT12/FAT16/FAT32 filesystem */
80         if (!memcmp(buffer + DOS_FS_TYPE_OFFSET, "FAT", 3))
81                 return 0;
82         if (!memcmp(buffer + DOS_FS32_TYPE_OFFSET, "FAT32", 5))
83                 return 0;
84
85         cur_dev = NULL;
86         return -1;
87 }
88
89 int fat_register_device(struct blk_desc *dev_desc, int part_no)
90 {
91         disk_partition_t info;
92
93         /* First close any currently found FAT filesystem */
94         cur_dev = NULL;
95
96         /* Read the partition table, if present */
97         if (part_get_info(dev_desc, part_no, &info)) {
98                 if (part_no != 0) {
99                         printf("** Partition %d not valid on device %d **\n",
100                                         part_no, dev_desc->devnum);
101                         return -1;
102                 }
103
104                 info.start = 0;
105                 info.size = dev_desc->lba;
106                 info.blksz = dev_desc->blksz;
107                 info.name[0] = 0;
108                 info.type[0] = 0;
109                 info.bootable = 0;
110 #if CONFIG_IS_ENABLED(PARTITION_UUIDS)
111                 info.uuid[0] = 0;
112 #endif
113         }
114
115         return fat_set_blk_dev(dev_desc, &info);
116 }
117
118 /*
119  * Extract zero terminated short name from a directory entry.
120  */
121 static void get_name(dir_entry *dirent, char *s_name)
122 {
123         char *ptr;
124
125         memcpy(s_name, dirent->name, 8);
126         s_name[8] = '\0';
127         ptr = s_name;
128         while (*ptr && *ptr != ' ')
129                 ptr++;
130         if (dirent->lcase & CASE_LOWER_BASE)
131                 downcase(s_name, (unsigned)(ptr - s_name));
132         if (dirent->ext[0] && dirent->ext[0] != ' ') {
133                 *ptr++ = '.';
134                 memcpy(ptr, dirent->ext, 3);
135                 if (dirent->lcase & CASE_LOWER_EXT)
136                         downcase(ptr, 3);
137                 ptr[3] = '\0';
138                 while (*ptr && *ptr != ' ')
139                         ptr++;
140         }
141         *ptr = '\0';
142         if (*s_name == DELETED_FLAG)
143                 *s_name = '\0';
144         else if (*s_name == aRING)
145                 *s_name = DELETED_FLAG;
146 }
147
148 static int flush_dirty_fat_buffer(fsdata *mydata);
149
150 #if !CONFIG_IS_ENABLED(FAT_WRITE)
151 /* Stub for read only operation */
152 int flush_dirty_fat_buffer(fsdata *mydata)
153 {
154         (void)(mydata);
155         return 0;
156 }
157 #endif
158
159 /*
160  * Get the entry at index 'entry' in a FAT (12/16/32) table.
161  * On failure 0x00 is returned.
162  */
163 static __u32 get_fatent(fsdata *mydata, __u32 entry)
164 {
165         __u32 bufnum;
166         __u32 offset, off8;
167         __u32 ret = 0x00;
168
169         if (CHECK_CLUST(entry, mydata->fatsize)) {
170                 printf("Error: Invalid FAT entry: 0x%08x\n", entry);
171                 return ret;
172         }
173
174         switch (mydata->fatsize) {
175         case 32:
176                 bufnum = entry / FAT32BUFSIZE;
177                 offset = entry - bufnum * FAT32BUFSIZE;
178                 break;
179         case 16:
180                 bufnum = entry / FAT16BUFSIZE;
181                 offset = entry - bufnum * FAT16BUFSIZE;
182                 break;
183         case 12:
184                 bufnum = entry / FAT12BUFSIZE;
185                 offset = entry - bufnum * FAT12BUFSIZE;
186                 break;
187
188         default:
189                 /* Unsupported FAT size */
190                 return ret;
191         }
192
193         debug("FAT%d: entry: 0x%08x = %d, offset: 0x%04x = %d\n",
194                mydata->fatsize, entry, entry, offset, offset);
195
196         /* Read a new block of FAT entries into the cache. */
197         if (bufnum != mydata->fatbufnum) {
198                 __u32 getsize = FATBUFBLOCKS;
199                 __u8 *bufptr = mydata->fatbuf;
200                 __u32 fatlength = mydata->fatlength;
201                 __u32 startblock = bufnum * FATBUFBLOCKS;
202
203                 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
204                 if (startblock + getsize > fatlength)
205                         getsize = fatlength - startblock;
206
207                 startblock += mydata->fat_sect; /* Offset from start of disk */
208
209                 /* Write back the fatbuf to the disk */
210                 if (flush_dirty_fat_buffer(mydata) < 0)
211                         return -1;
212
213                 if (disk_read(startblock, getsize, bufptr) < 0) {
214                         debug("Error reading FAT blocks\n");
215                         return ret;
216                 }
217                 mydata->fatbufnum = bufnum;
218         }
219
220         /* Get the actual entry from the table */
221         switch (mydata->fatsize) {
222         case 32:
223                 ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]);
224                 break;
225         case 16:
226                 ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]);
227                 break;
228         case 12:
229                 off8 = (offset * 3) / 2;
230                 /* fatbut + off8 may be unaligned, read in byte granularity */
231                 ret = mydata->fatbuf[off8] + (mydata->fatbuf[off8 + 1] << 8);
232
233                 if (offset & 0x1)
234                         ret >>= 4;
235                 ret &= 0xfff;
236         }
237         debug("FAT%d: ret: 0x%08x, entry: 0x%08x, offset: 0x%04x\n",
238                mydata->fatsize, ret, entry, offset);
239
240         return ret;
241 }
242
243 /*
244  * Read at most 'size' bytes from the specified cluster into 'buffer'.
245  * Return 0 on success, -1 otherwise.
246  */
247 static int
248 get_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer, unsigned long size)
249 {
250         __u32 idx = 0;
251         __u32 startsect;
252         int ret;
253
254         if (clustnum > 0) {
255                 startsect = clust_to_sect(mydata, clustnum);
256         } else {
257                 startsect = mydata->rootdir_sect;
258         }
259
260         debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect);
261
262         if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
263                 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
264
265                 debug("FAT: Misaligned buffer address (%p)\n", buffer);
266
267                 while (size >= mydata->sect_size) {
268                         ret = disk_read(startsect++, 1, tmpbuf);
269                         if (ret != 1) {
270                                 debug("Error reading data (got %d)\n", ret);
271                                 return -1;
272                         }
273
274                         memcpy(buffer, tmpbuf, mydata->sect_size);
275                         buffer += mydata->sect_size;
276                         size -= mydata->sect_size;
277                 }
278         } else {
279                 idx = size / mydata->sect_size;
280                 ret = disk_read(startsect, idx, buffer);
281                 if (ret != idx) {
282                         debug("Error reading data (got %d)\n", ret);
283                         return -1;
284                 }
285                 startsect += idx;
286                 idx *= mydata->sect_size;
287                 buffer += idx;
288                 size -= idx;
289         }
290         if (size) {
291                 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
292
293                 ret = disk_read(startsect, 1, tmpbuf);
294                 if (ret != 1) {
295                         debug("Error reading data (got %d)\n", ret);
296                         return -1;
297                 }
298
299                 memcpy(buffer, tmpbuf, size);
300         }
301
302         return 0;
303 }
304
305 /**
306  * get_contents() - read from file
307  *
308  * Read at most 'maxsize' bytes from 'pos' in the file associated with 'dentptr'
309  * into 'buffer'. Update the number of bytes read in *gotsize or return -1 on
310  * fatal errors.
311  *
312  * @mydata:     file system description
313  * @dentprt:    directory entry pointer
314  * @pos:        position from where to read
315  * @buffer:     buffer into which to read
316  * @maxsize:    maximum number of bytes to read
317  * @gotsize:    number of bytes actually read
318  * Return:      -1 on error, otherwise 0
319  */
320 static int get_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos,
321                         __u8 *buffer, loff_t maxsize, loff_t *gotsize)
322 {
323         loff_t filesize = FAT2CPU32(dentptr->size);
324         unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
325         __u32 curclust = START(dentptr);
326         __u32 endclust, newclust;
327         loff_t actsize;
328
329         *gotsize = 0;
330         debug("Filesize: %llu bytes\n", filesize);
331
332         if (pos >= filesize) {
333                 debug("Read position past EOF: %llu\n", pos);
334                 return 0;
335         }
336
337         if (maxsize > 0 && filesize > pos + maxsize)
338                 filesize = pos + maxsize;
339
340         debug("%llu bytes\n", filesize);
341
342         actsize = bytesperclust;
343
344         /* go to cluster at pos */
345         while (actsize <= pos) {
346                 curclust = get_fatent(mydata, curclust);
347                 if (CHECK_CLUST(curclust, mydata->fatsize)) {
348                         debug("curclust: 0x%x\n", curclust);
349                         printf("Invalid FAT entry\n");
350                         return -1;
351                 }
352                 actsize += bytesperclust;
353         }
354
355         /* actsize > pos */
356         actsize -= bytesperclust;
357         filesize -= actsize;
358         pos -= actsize;
359
360         /* align to beginning of next cluster if any */
361         if (pos) {
362                 __u8 *tmp_buffer;
363
364                 actsize = min(filesize, (loff_t)bytesperclust);
365                 tmp_buffer = malloc_cache_aligned(actsize);
366                 if (!tmp_buffer) {
367                         debug("Error: allocating buffer\n");
368                         return -1;
369                 }
370
371                 if (get_cluster(mydata, curclust, tmp_buffer, actsize) != 0) {
372                         printf("Error reading cluster\n");
373                         free(tmp_buffer);
374                         return -1;
375                 }
376                 filesize -= actsize;
377                 actsize -= pos;
378                 memcpy(buffer, tmp_buffer + pos, actsize);
379                 free(tmp_buffer);
380                 *gotsize += actsize;
381                 if (!filesize)
382                         return 0;
383                 buffer += actsize;
384
385                 curclust = get_fatent(mydata, curclust);
386                 if (CHECK_CLUST(curclust, mydata->fatsize)) {
387                         debug("curclust: 0x%x\n", curclust);
388                         printf("Invalid FAT entry\n");
389                         return -1;
390                 }
391         }
392
393         actsize = bytesperclust;
394         endclust = curclust;
395
396         do {
397                 /* search for consecutive clusters */
398                 while (actsize < filesize) {
399                         newclust = get_fatent(mydata, endclust);
400                         if ((newclust - 1) != endclust)
401                                 goto getit;
402                         if (CHECK_CLUST(newclust, mydata->fatsize)) {
403                                 debug("curclust: 0x%x\n", newclust);
404                                 printf("Invalid FAT entry\n");
405                                 return -1;
406                         }
407                         endclust = newclust;
408                         actsize += bytesperclust;
409                 }
410
411                 /* get remaining bytes */
412                 actsize = filesize;
413                 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
414                         printf("Error reading cluster\n");
415                         return -1;
416                 }
417                 *gotsize += actsize;
418                 return 0;
419 getit:
420                 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
421                         printf("Error reading cluster\n");
422                         return -1;
423                 }
424                 *gotsize += (int)actsize;
425                 filesize -= actsize;
426                 buffer += actsize;
427
428                 curclust = get_fatent(mydata, endclust);
429                 if (CHECK_CLUST(curclust, mydata->fatsize)) {
430                         debug("curclust: 0x%x\n", curclust);
431                         printf("Invalid FAT entry\n");
432                         return -1;
433                 }
434                 actsize = bytesperclust;
435                 endclust = curclust;
436         } while (1);
437 }
438
439 /*
440  * Extract the file name information from 'slotptr' into 'l_name',
441  * starting at l_name[*idx].
442  * Return 1 if terminator (zero byte) is found, 0 otherwise.
443  */
444 static int slot2str(dir_slot *slotptr, char *l_name, int *idx)
445 {
446         int j;
447
448         for (j = 0; j <= 8; j += 2) {
449                 l_name[*idx] = slotptr->name0_4[j];
450                 if (l_name[*idx] == 0x00)
451                         return 1;
452                 (*idx)++;
453         }
454         for (j = 0; j <= 10; j += 2) {
455                 l_name[*idx] = slotptr->name5_10[j];
456                 if (l_name[*idx] == 0x00)
457                         return 1;
458                 (*idx)++;
459         }
460         for (j = 0; j <= 2; j += 2) {
461                 l_name[*idx] = slotptr->name11_12[j];
462                 if (l_name[*idx] == 0x00)
463                         return 1;
464                 (*idx)++;
465         }
466
467         return 0;
468 }
469
470 /* Calculate short name checksum */
471 static __u8 mkcksum(const char name[8], const char ext[3])
472 {
473         int i;
474
475         __u8 ret = 0;
476
477         for (i = 0; i < 8; i++)
478                 ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + name[i];
479         for (i = 0; i < 3; i++)
480                 ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + ext[i];
481
482         return ret;
483 }
484
485 /*
486  * Read boot sector and volume info from a FAT filesystem
487  */
488 static int
489 read_bootsectandvi(boot_sector *bs, volume_info *volinfo, int *fatsize)
490 {
491         __u8 *block;
492         volume_info *vistart;
493         int ret = 0;
494
495         if (cur_dev == NULL) {
496                 debug("Error: no device selected\n");
497                 return -1;
498         }
499
500         block = malloc_cache_aligned(cur_dev->blksz);
501         if (block == NULL) {
502                 debug("Error: allocating block\n");
503                 return -1;
504         }
505
506         if (disk_read(0, 1, block) < 0) {
507                 debug("Error: reading block\n");
508                 goto fail;
509         }
510
511         memcpy(bs, block, sizeof(boot_sector));
512         bs->reserved = FAT2CPU16(bs->reserved);
513         bs->fat_length = FAT2CPU16(bs->fat_length);
514         bs->secs_track = FAT2CPU16(bs->secs_track);
515         bs->heads = FAT2CPU16(bs->heads);
516         bs->total_sect = FAT2CPU32(bs->total_sect);
517
518         /* FAT32 entries */
519         if (bs->fat_length == 0) {
520                 /* Assume FAT32 */
521                 bs->fat32_length = FAT2CPU32(bs->fat32_length);
522                 bs->flags = FAT2CPU16(bs->flags);
523                 bs->root_cluster = FAT2CPU32(bs->root_cluster);
524                 bs->info_sector = FAT2CPU16(bs->info_sector);
525                 bs->backup_boot = FAT2CPU16(bs->backup_boot);
526                 vistart = (volume_info *)(block + sizeof(boot_sector));
527                 *fatsize = 32;
528         } else {
529                 vistart = (volume_info *)&(bs->fat32_length);
530                 *fatsize = 0;
531         }
532         memcpy(volinfo, vistart, sizeof(volume_info));
533
534         if (*fatsize == 32) {
535                 if (strncmp(FAT32_SIGN, vistart->fs_type, SIGNLEN) == 0)
536                         goto exit;
537         } else {
538                 if (strncmp(FAT12_SIGN, vistart->fs_type, SIGNLEN) == 0) {
539                         *fatsize = 12;
540                         goto exit;
541                 }
542                 if (strncmp(FAT16_SIGN, vistart->fs_type, SIGNLEN) == 0) {
543                         *fatsize = 16;
544                         goto exit;
545                 }
546         }
547
548         debug("Error: broken fs_type sign\n");
549 fail:
550         ret = -1;
551 exit:
552         free(block);
553         return ret;
554 }
555
556 static int get_fs_info(fsdata *mydata)
557 {
558         boot_sector bs;
559         volume_info volinfo;
560         int ret;
561
562         ret = read_bootsectandvi(&bs, &volinfo, &mydata->fatsize);
563         if (ret) {
564                 debug("Error: reading boot sector\n");
565                 return ret;
566         }
567
568         if (mydata->fatsize == 32) {
569                 mydata->fatlength = bs.fat32_length;
570                 mydata->total_sect = bs.total_sect;
571         } else {
572                 mydata->fatlength = bs.fat_length;
573                 mydata->total_sect = (bs.sectors[1] << 8) + bs.sectors[0];
574                 if (!mydata->total_sect)
575                         mydata->total_sect = bs.total_sect;
576         }
577         if (!mydata->total_sect) /* unlikely */
578                 mydata->total_sect = (u32)cur_part_info.size;
579
580         mydata->fats = bs.fats;
581         mydata->fat_sect = bs.reserved;
582
583         mydata->rootdir_sect = mydata->fat_sect + mydata->fatlength * bs.fats;
584
585         mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0];
586         mydata->clust_size = bs.cluster_size;
587         if (mydata->sect_size != cur_part_info.blksz) {
588                 printf("Error: FAT sector size mismatch (fs=%hu, dev=%lu)\n",
589                                 mydata->sect_size, cur_part_info.blksz);
590                 return -1;
591         }
592         if (mydata->clust_size == 0) {
593                 printf("Error: FAT cluster size not set\n");
594                 return -1;
595         }
596         if ((unsigned int)mydata->clust_size * mydata->sect_size >
597             MAX_CLUSTSIZE) {
598                 printf("Error: FAT cluster size too big (cs=%u, max=%u)\n",
599                        (unsigned int)mydata->clust_size * mydata->sect_size,
600                        MAX_CLUSTSIZE);
601                 return -1;
602         }
603
604         if (mydata->fatsize == 32) {
605                 mydata->data_begin = mydata->rootdir_sect -
606                                         (mydata->clust_size * 2);
607                 mydata->root_cluster = bs.root_cluster;
608         } else {
609                 mydata->rootdir_size = ((bs.dir_entries[1]  * (int)256 +
610                                          bs.dir_entries[0]) *
611                                          sizeof(dir_entry)) /
612                                          mydata->sect_size;
613                 mydata->data_begin = mydata->rootdir_sect +
614                                         mydata->rootdir_size -
615                                         (mydata->clust_size * 2);
616
617                 /*
618                  * The root directory is not cluster-aligned and may be on a
619                  * "negative" cluster, this will be handled specially in
620                  * next_cluster().
621                  */
622                 mydata->root_cluster = 0;
623         }
624
625         mydata->fatbufnum = -1;
626         mydata->fat_dirty = 0;
627         mydata->fatbuf = malloc_cache_aligned(FATBUFSIZE);
628         if (mydata->fatbuf == NULL) {
629                 debug("Error: allocating memory\n");
630                 return -1;
631         }
632
633         debug("FAT%d, fat_sect: %d, fatlength: %d\n",
634                mydata->fatsize, mydata->fat_sect, mydata->fatlength);
635         debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n"
636                "Data begins at: %d\n",
637                mydata->root_cluster,
638                mydata->rootdir_sect,
639                mydata->rootdir_sect * mydata->sect_size, mydata->data_begin);
640         debug("Sector size: %d, cluster size: %d\n", mydata->sect_size,
641               mydata->clust_size);
642
643         return 0;
644 }
645
646
647 /*
648  * Directory iterator, to simplify filesystem traversal
649  *
650  * Implements an iterator pattern to traverse directory tables,
651  * transparently handling directory tables split across multiple
652  * clusters, and the difference between FAT12/FAT16 root directory
653  * (contiguous) and subdirectories + FAT32 root (chained).
654  *
655  * Rough usage:
656  *
657  *   for (fat_itr_root(&itr, fsdata); fat_itr_next(&itr); ) {
658  *      // to traverse down to a subdirectory pointed to by
659  *      // current iterator position:
660  *      fat_itr_child(&itr, &itr);
661  *   }
662  *
663  * For more complete example, see fat_itr_resolve()
664  */
665
666 typedef struct {
667         fsdata    *fsdata;        /* filesystem parameters */
668         unsigned   start_clust;   /* first cluster */
669         unsigned   clust;         /* current cluster */
670         unsigned   next_clust;    /* next cluster if remaining == 0 */
671         int        last_cluster;  /* set once we've read last cluster */
672         int        is_root;       /* is iterator at root directory */
673         int        remaining;     /* remaining dent's in current cluster */
674
675         /* current iterator position values: */
676         dir_entry *dent;          /* current directory entry */
677         char       l_name[VFAT_MAXLEN_BYTES];    /* long (vfat) name */
678         char       s_name[14];    /* short 8.3 name */
679         char      *name;          /* l_name if there is one, else s_name */
680
681         /* storage for current cluster in memory: */
682         u8         block[MAX_CLUSTSIZE] __aligned(ARCH_DMA_MINALIGN);
683 } fat_itr;
684
685 static int fat_itr_isdir(fat_itr *itr);
686
687 /**
688  * fat_itr_root() - initialize an iterator to start at the root
689  * directory
690  *
691  * @itr: iterator to initialize
692  * @fsdata: filesystem data for the partition
693  * @return 0 on success, else -errno
694  */
695 static int fat_itr_root(fat_itr *itr, fsdata *fsdata)
696 {
697         if (get_fs_info(fsdata))
698                 return -ENXIO;
699
700         itr->fsdata = fsdata;
701         itr->start_clust = 0;
702         itr->clust = fsdata->root_cluster;
703         itr->next_clust = fsdata->root_cluster;
704         itr->dent = NULL;
705         itr->remaining = 0;
706         itr->last_cluster = 0;
707         itr->is_root = 1;
708
709         return 0;
710 }
711
712 /**
713  * fat_itr_child() - initialize an iterator to descend into a sub-
714  * directory
715  *
716  * Initializes 'itr' to iterate the contents of the directory at
717  * the current cursor position of 'parent'.  It is an error to
718  * call this if the current cursor of 'parent' is pointing at a
719  * regular file.
720  *
721  * Note that 'itr' and 'parent' can be the same pointer if you do
722  * not need to preserve 'parent' after this call, which is useful
723  * for traversing directory structure to resolve a file/directory.
724  *
725  * @itr: iterator to initialize
726  * @parent: the iterator pointing at a directory entry in the
727  *    parent directory of the directory to iterate
728  */
729 static void fat_itr_child(fat_itr *itr, fat_itr *parent)
730 {
731         fsdata *mydata = parent->fsdata;  /* for silly macros */
732         unsigned clustnum = START(parent->dent);
733
734         assert(fat_itr_isdir(parent));
735
736         itr->fsdata = parent->fsdata;
737         itr->start_clust = clustnum;
738         if (clustnum > 0) {
739                 itr->clust = clustnum;
740                 itr->next_clust = clustnum;
741                 itr->is_root = 0;
742         } else {
743                 itr->clust = parent->fsdata->root_cluster;
744                 itr->next_clust = parent->fsdata->root_cluster;
745                 itr->is_root = 1;
746         }
747         itr->dent = NULL;
748         itr->remaining = 0;
749         itr->last_cluster = 0;
750 }
751
752 static void *next_cluster(fat_itr *itr, unsigned *nbytes)
753 {
754         fsdata *mydata = itr->fsdata;  /* for silly macros */
755         int ret;
756         u32 sect;
757         u32 read_size;
758
759         /* have we reached the end? */
760         if (itr->last_cluster)
761                 return NULL;
762
763         if (itr->is_root && itr->fsdata->fatsize != 32) {
764                 /*
765                  * The root directory is located before the data area and
766                  * cannot be indexed using the regular unsigned cluster
767                  * numbers (it may start at a "negative" cluster or not at a
768                  * cluster boundary at all), so consider itr->next_clust to be
769                  * a offset in cluster-sized units from the start of rootdir.
770                  */
771                 unsigned sect_offset = itr->next_clust * itr->fsdata->clust_size;
772                 unsigned remaining_sects = itr->fsdata->rootdir_size - sect_offset;
773                 sect = itr->fsdata->rootdir_sect + sect_offset;
774                 /* do not read past the end of rootdir */
775                 read_size = min_t(u32, itr->fsdata->clust_size,
776                                   remaining_sects);
777         } else {
778                 sect = clust_to_sect(itr->fsdata, itr->next_clust);
779                 read_size = itr->fsdata->clust_size;
780         }
781
782         debug("FAT read(sect=%d), clust_size=%d, read_size=%u, DIRENTSPERBLOCK=%zd\n",
783               sect, itr->fsdata->clust_size, read_size, DIRENTSPERBLOCK);
784
785         /*
786          * NOTE: do_fat_read_at() had complicated logic to deal w/
787          * vfat names that span multiple clusters in the fat16 case,
788          * which get_dentfromdir() probably also needed (and was
789          * missing).  And not entirely sure what fat32 didn't have
790          * the same issue..  We solve that by only caring about one
791          * dent at a time and iteratively constructing the vfat long
792          * name.
793          */
794         ret = disk_read(sect, read_size, itr->block);
795         if (ret < 0) {
796                 debug("Error: reading block\n");
797                 return NULL;
798         }
799
800         *nbytes = read_size * itr->fsdata->sect_size;
801         itr->clust = itr->next_clust;
802         if (itr->is_root && itr->fsdata->fatsize != 32) {
803                 itr->next_clust++;
804                 if (itr->next_clust * itr->fsdata->clust_size >=
805                     itr->fsdata->rootdir_size) {
806                         debug("nextclust: 0x%x\n", itr->next_clust);
807                         itr->last_cluster = 1;
808                 }
809         } else {
810                 itr->next_clust = get_fatent(itr->fsdata, itr->next_clust);
811                 if (CHECK_CLUST(itr->next_clust, itr->fsdata->fatsize)) {
812                         debug("nextclust: 0x%x\n", itr->next_clust);
813                         itr->last_cluster = 1;
814                 }
815         }
816
817         return itr->block;
818 }
819
820 static dir_entry *next_dent(fat_itr *itr)
821 {
822         if (itr->remaining == 0) {
823                 unsigned nbytes;
824                 struct dir_entry *dent = next_cluster(itr, &nbytes);
825
826                 /* have we reached the last cluster? */
827                 if (!dent) {
828                         /* a sign for no more entries left */
829                         itr->dent = NULL;
830                         return NULL;
831                 }
832
833                 itr->remaining = nbytes / sizeof(dir_entry) - 1;
834                 itr->dent = dent;
835         } else {
836                 itr->remaining--;
837                 itr->dent++;
838         }
839
840         /* have we reached the last valid entry? */
841         if (itr->dent->name[0] == 0)
842                 return NULL;
843
844         return itr->dent;
845 }
846
847 static dir_entry *extract_vfat_name(fat_itr *itr)
848 {
849         struct dir_entry *dent = itr->dent;
850         int seqn = itr->dent->name[0] & ~LAST_LONG_ENTRY_MASK;
851         u8 chksum, alias_checksum = ((dir_slot *)dent)->alias_checksum;
852         int n = 0;
853
854         while (seqn--) {
855                 char buf[13];
856                 int idx = 0;
857
858                 slot2str((dir_slot *)dent, buf, &idx);
859
860                 if (n + idx >= sizeof(itr->l_name))
861                         return NULL;
862
863                 /* shift accumulated long-name up and copy new part in: */
864                 memmove(itr->l_name + idx, itr->l_name, n);
865                 memcpy(itr->l_name, buf, idx);
866                 n += idx;
867
868                 dent = next_dent(itr);
869                 if (!dent)
870                         return NULL;
871         }
872
873         /*
874          * We are now at the short file name entry.
875          * If it is marked as deleted, just skip it.
876          */
877         if (dent->name[0] == DELETED_FLAG ||
878             dent->name[0] == aRING)
879                 return NULL;
880
881         itr->l_name[n] = '\0';
882
883         chksum = mkcksum(dent->name, dent->ext);
884
885         /* checksum mismatch could mean deleted file, etc.. skip it: */
886         if (chksum != alias_checksum) {
887                 debug("** chksum=%x, alias_checksum=%x, l_name=%s, s_name=%8s.%3s\n",
888                       chksum, alias_checksum, itr->l_name, dent->name, dent->ext);
889                 return NULL;
890         }
891
892         return dent;
893 }
894
895 /**
896  * fat_itr_next() - step to the next entry in a directory
897  *
898  * Must be called once on a new iterator before the cursor is valid.
899  *
900  * @itr: the iterator to iterate
901  * @return boolean, 1 if success or 0 if no more entries in the
902  *    current directory
903  */
904 static int fat_itr_next(fat_itr *itr)
905 {
906         dir_entry *dent;
907
908         itr->name = NULL;
909
910         /*
911          * One logical directory entry consist of following slots:
912          *                              name[0] Attributes
913          *   dent[N - N]: LFN[N - 1]    N|0x40  ATTR_VFAT
914          *   ...
915          *   dent[N - 2]: LFN[1]        2       ATTR_VFAT
916          *   dent[N - 1]: LFN[0]        1       ATTR_VFAT
917          *   dent[N]:     SFN                   ATTR_ARCH
918          */
919
920         while (1) {
921                 dent = next_dent(itr);
922                 if (!dent)
923                         return 0;
924
925                 if (dent->name[0] == DELETED_FLAG ||
926                     dent->name[0] == aRING)
927                         continue;
928
929                 if (dent->attr & ATTR_VOLUME) {
930                         if ((dent->attr & ATTR_VFAT) == ATTR_VFAT &&
931                             (dent->name[0] & LAST_LONG_ENTRY_MASK)) {
932                                 /* long file name */
933                                 dent = extract_vfat_name(itr);
934                                 /*
935                                  * If succeeded, dent has a valid short file
936                                  * name entry for the current entry.
937                                  * If failed, itr points to a current bogus
938                                  * entry. So after fetching a next one,
939                                  * it may have a short file name entry
940                                  * for this bogus entry so that we can still
941                                  * check for a short name.
942                                  */
943                                 if (!dent)
944                                         continue;
945                                 itr->name = itr->l_name;
946                                 break;
947                         } else {
948                                 /* Volume label or VFAT entry, skip */
949                                 continue;
950                         }
951                 } else if (!(dent->attr & ATTR_ARCH) &&
952                            !(dent->attr & ATTR_DIR))
953                         continue;
954
955                 /* short file name */
956                 break;
957         }
958
959         get_name(dent, itr->s_name);
960         if (!itr->name)
961                 itr->name = itr->s_name;
962
963         return 1;
964 }
965
966 /**
967  * fat_itr_isdir() - is current cursor position pointing to a directory
968  *
969  * @itr: the iterator
970  * @return true if cursor is at a directory
971  */
972 static int fat_itr_isdir(fat_itr *itr)
973 {
974         return !!(itr->dent->attr & ATTR_DIR);
975 }
976
977 /*
978  * Helpers:
979  */
980
981 #define TYPE_FILE 0x1
982 #define TYPE_DIR  0x2
983 #define TYPE_ANY  (TYPE_FILE | TYPE_DIR)
984
985 /**
986  * fat_itr_resolve() - traverse directory structure to resolve the
987  * requested path.
988  *
989  * Traverse directory structure to the requested path.  If the specified
990  * path is to a directory, this will descend into the directory and
991  * leave it iterator at the start of the directory.  If the path is to a
992  * file, it will leave the iterator in the parent directory with current
993  * cursor at file's entry in the directory.
994  *
995  * @itr: iterator initialized to root
996  * @path: the requested path
997  * @type: bitmask of allowable file types
998  * @return 0 on success or -errno
999  */
1000 static int fat_itr_resolve(fat_itr *itr, const char *path, unsigned type)
1001 {
1002         const char *next;
1003
1004         /* chomp any extra leading slashes: */
1005         while (path[0] && ISDIRDELIM(path[0]))
1006                 path++;
1007
1008         /* are we at the end? */
1009         if (strlen(path) == 0) {
1010                 if (!(type & TYPE_DIR))
1011                         return -ENOENT;
1012                 return 0;
1013         }
1014
1015         /* find length of next path entry: */
1016         next = path;
1017         while (next[0] && !ISDIRDELIM(next[0]))
1018                 next++;
1019
1020         if (itr->is_root) {
1021                 /* root dir doesn't have "." nor ".." */
1022                 if ((((next - path) == 1) && !strncmp(path, ".", 1)) ||
1023                     (((next - path) == 2) && !strncmp(path, "..", 2))) {
1024                         /* point back to itself */
1025                         itr->clust = itr->fsdata->root_cluster;
1026                         itr->next_clust = itr->fsdata->root_cluster;
1027                         itr->dent = NULL;
1028                         itr->remaining = 0;
1029                         itr->last_cluster = 0;
1030
1031                         if (next[0] == 0) {
1032                                 if (type & TYPE_DIR)
1033                                         return 0;
1034                                 else
1035                                         return -ENOENT;
1036                         }
1037
1038                         return fat_itr_resolve(itr, next, type);
1039                 }
1040         }
1041
1042         while (fat_itr_next(itr)) {
1043                 int match = 0;
1044                 unsigned n = max(strlen(itr->name), (size_t)(next - path));
1045
1046                 /* check both long and short name: */
1047                 if (!strncasecmp(path, itr->name, n))
1048                         match = 1;
1049                 else if (itr->name != itr->s_name &&
1050                          !strncasecmp(path, itr->s_name, n))
1051                         match = 1;
1052
1053                 if (!match)
1054                         continue;
1055
1056                 if (fat_itr_isdir(itr)) {
1057                         /* recurse into directory: */
1058                         fat_itr_child(itr, itr);
1059                         return fat_itr_resolve(itr, next, type);
1060                 } else if (next[0]) {
1061                         /*
1062                          * If next is not empty then we have a case
1063                          * like: /path/to/realfile/nonsense
1064                          */
1065                         debug("bad trailing path: %s\n", next);
1066                         return -ENOENT;
1067                 } else if (!(type & TYPE_FILE)) {
1068                         return -ENOTDIR;
1069                 } else {
1070                         return 0;
1071                 }
1072         }
1073
1074         return -ENOENT;
1075 }
1076
1077 int file_fat_detectfs(void)
1078 {
1079         boot_sector bs;
1080         volume_info volinfo;
1081         int fatsize;
1082         char vol_label[12];
1083
1084         if (cur_dev == NULL) {
1085                 printf("No current device\n");
1086                 return 1;
1087         }
1088
1089 #if defined(CONFIG_IDE) || \
1090     defined(CONFIG_SATA) || \
1091     defined(CONFIG_SCSI) || \
1092     defined(CONFIG_CMD_USB) || \
1093     defined(CONFIG_MMC)
1094         printf("Interface:  ");
1095         switch (cur_dev->if_type) {
1096         case IF_TYPE_IDE:
1097                 printf("IDE");
1098                 break;
1099         case IF_TYPE_SATA:
1100                 printf("SATA");
1101                 break;
1102         case IF_TYPE_SCSI:
1103                 printf("SCSI");
1104                 break;
1105         case IF_TYPE_ATAPI:
1106                 printf("ATAPI");
1107                 break;
1108         case IF_TYPE_USB:
1109                 printf("USB");
1110                 break;
1111         case IF_TYPE_DOC:
1112                 printf("DOC");
1113                 break;
1114         case IF_TYPE_MMC:
1115                 printf("MMC");
1116                 break;
1117         default:
1118                 printf("Unknown");
1119         }
1120
1121         printf("\n  Device %d: ", cur_dev->devnum);
1122         dev_print(cur_dev);
1123 #endif
1124
1125         if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
1126                 printf("\nNo valid FAT fs found\n");
1127                 return 1;
1128         }
1129
1130         memcpy(vol_label, volinfo.volume_label, 11);
1131         vol_label[11] = '\0';
1132         volinfo.fs_type[5] = '\0';
1133
1134         printf("Filesystem: %s \"%s\"\n", volinfo.fs_type, vol_label);
1135
1136         return 0;
1137 }
1138
1139 int fat_exists(const char *filename)
1140 {
1141         fsdata fsdata;
1142         fat_itr *itr;
1143         int ret;
1144
1145         itr = malloc_cache_aligned(sizeof(fat_itr));
1146         if (!itr)
1147                 return 0;
1148         ret = fat_itr_root(itr, &fsdata);
1149         if (ret)
1150                 goto out;
1151
1152         ret = fat_itr_resolve(itr, filename, TYPE_ANY);
1153         free(fsdata.fatbuf);
1154 out:
1155         free(itr);
1156         return ret == 0;
1157 }
1158
1159 int fat_size(const char *filename, loff_t *size)
1160 {
1161         fsdata fsdata;
1162         fat_itr *itr;
1163         int ret;
1164
1165         itr = malloc_cache_aligned(sizeof(fat_itr));
1166         if (!itr)
1167                 return -ENOMEM;
1168         ret = fat_itr_root(itr, &fsdata);
1169         if (ret)
1170                 goto out_free_itr;
1171
1172         ret = fat_itr_resolve(itr, filename, TYPE_FILE);
1173         if (ret) {
1174                 /*
1175                  * Directories don't have size, but fs_size() is not
1176                  * expected to fail if passed a directory path:
1177                  */
1178                 free(fsdata.fatbuf);
1179                 ret = fat_itr_root(itr, &fsdata);
1180                 if (ret)
1181                         goto out_free_itr;
1182                 ret = fat_itr_resolve(itr, filename, TYPE_DIR);
1183                 if (!ret)
1184                         *size = 0;
1185                 goto out_free_both;
1186         }
1187
1188         *size = FAT2CPU32(itr->dent->size);
1189 out_free_both:
1190         free(fsdata.fatbuf);
1191 out_free_itr:
1192         free(itr);
1193         return ret;
1194 }
1195
1196 int file_fat_read_at(const char *filename, loff_t pos, void *buffer,
1197                      loff_t maxsize, loff_t *actread)
1198 {
1199         fsdata fsdata;
1200         fat_itr *itr;
1201         int ret;
1202
1203         itr = malloc_cache_aligned(sizeof(fat_itr));
1204         if (!itr)
1205                 return -ENOMEM;
1206         ret = fat_itr_root(itr, &fsdata);
1207         if (ret)
1208                 goto out_free_itr;
1209
1210         ret = fat_itr_resolve(itr, filename, TYPE_FILE);
1211         if (ret)
1212                 goto out_free_both;
1213
1214         debug("reading %s at pos %llu\n", filename, pos);
1215
1216         /* For saving default max clustersize memory allocated to malloc pool */
1217         dir_entry *dentptr = itr->dent;
1218
1219         ret = get_contents(&fsdata, dentptr, pos, buffer, maxsize, actread);
1220
1221 out_free_both:
1222         free(fsdata.fatbuf);
1223 out_free_itr:
1224         free(itr);
1225         return ret;
1226 }
1227
1228 int file_fat_read(const char *filename, void *buffer, int maxsize)
1229 {
1230         loff_t actread;
1231         int ret;
1232
1233         ret =  file_fat_read_at(filename, 0, buffer, maxsize, &actread);
1234         if (ret)
1235                 return ret;
1236         else
1237                 return actread;
1238 }
1239
1240 int fat_read_file(const char *filename, void *buf, loff_t offset, loff_t len,
1241                   loff_t *actread)
1242 {
1243         int ret;
1244
1245         ret = file_fat_read_at(filename, offset, buf, len, actread);
1246         if (ret)
1247                 printf("** Unable to read file %s **\n", filename);
1248
1249         return ret;
1250 }
1251
1252 typedef struct {
1253         struct fs_dir_stream parent;
1254         struct fs_dirent dirent;
1255         fsdata fsdata;
1256         fat_itr itr;
1257 } fat_dir;
1258
1259 int fat_opendir(const char *filename, struct fs_dir_stream **dirsp)
1260 {
1261         fat_dir *dir;
1262         int ret;
1263
1264         dir = malloc_cache_aligned(sizeof(*dir));
1265         if (!dir)
1266                 return -ENOMEM;
1267         memset(dir, 0, sizeof(*dir));
1268
1269         ret = fat_itr_root(&dir->itr, &dir->fsdata);
1270         if (ret)
1271                 goto fail_free_dir;
1272
1273         ret = fat_itr_resolve(&dir->itr, filename, TYPE_DIR);
1274         if (ret)
1275                 goto fail_free_both;
1276
1277         *dirsp = (struct fs_dir_stream *)dir;
1278         return 0;
1279
1280 fail_free_both:
1281         free(dir->fsdata.fatbuf);
1282 fail_free_dir:
1283         free(dir);
1284         return ret;
1285 }
1286
1287 int fat_readdir(struct fs_dir_stream *dirs, struct fs_dirent **dentp)
1288 {
1289         fat_dir *dir = (fat_dir *)dirs;
1290         struct fs_dirent *dent = &dir->dirent;
1291
1292         if (!fat_itr_next(&dir->itr))
1293                 return -ENOENT;
1294
1295         memset(dent, 0, sizeof(*dent));
1296         strcpy(dent->name, dir->itr.name);
1297
1298         if (fat_itr_isdir(&dir->itr)) {
1299                 dent->type = FS_DT_DIR;
1300         } else {
1301                 dent->type = FS_DT_REG;
1302                 dent->size = FAT2CPU32(dir->itr.dent->size);
1303         }
1304
1305         *dentp = dent;
1306
1307         return 0;
1308 }
1309
1310 void fat_closedir(struct fs_dir_stream *dirs)
1311 {
1312         fat_dir *dir = (fat_dir *)dirs;
1313         free(dir->fsdata.fatbuf);
1314         free(dir);
1315 }
1316
1317 void fat_close(void)
1318 {
1319 }