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