1 // SPDX-License-Identifier: GPL-2.0+
5 * R/O (V)FAT 12/16/32 filesystem implementation by Marcus Sundberg
11 #define LOG_CATEGORY LOGC_FS
20 #include <asm/byteorder.h>
21 #include <asm/unaligned.h>
25 #include <asm/cache.h>
26 #include <linux/compiler.h>
27 #include <linux/ctype.h>
28 #include <linux/log2.h>
30 /* maximum number of clusters for FAT12 */
31 #define MAX_FAT12 0xFF4
34 * Convert a string to lowercase. Converts at most 'len' characters,
35 * 'len' may be larger than the length of 'str' if 'str' is NULL
38 static void downcase(char *str, size_t len)
40 while (*str != '\0' && len--) {
46 static struct blk_desc *cur_dev;
47 static struct disk_partition cur_part_info;
49 #define DOS_BOOT_MAGIC_OFFSET 0x1fe
50 #define DOS_FS_TYPE_OFFSET 0x36
51 #define DOS_FS32_TYPE_OFFSET 0x52
53 static int disk_read(__u32 block, __u32 nr_blocks, void *buf)
60 ret = blk_dread(cur_dev, cur_part_info.start + block, nr_blocks, buf);
68 int fat_set_blk_dev(struct blk_desc *dev_desc, struct disk_partition *info)
70 ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, dev_desc->blksz);
73 cur_part_info = *info;
75 /* Make sure it has a valid FAT header */
76 if (disk_read(0, 1, buffer) != 1) {
81 /* Check if it's actually a DOS volume */
82 if (memcmp(buffer + DOS_BOOT_MAGIC_OFFSET, "\x55\xAA", 2)) {
87 /* Check for FAT12/FAT16/FAT32 filesystem */
88 if (!memcmp(buffer + DOS_FS_TYPE_OFFSET, "FAT", 3))
90 if (!memcmp(buffer + DOS_FS32_TYPE_OFFSET, "FAT32", 5))
97 int fat_register_device(struct blk_desc *dev_desc, int part_no)
99 struct disk_partition info;
101 /* First close any currently found FAT filesystem */
104 /* Read the partition table, if present */
105 if (part_get_info(dev_desc, part_no, &info)) {
107 log_err("Partition %d invalid on device %d\n", part_no,
113 info.size = dev_desc->lba;
114 info.blksz = dev_desc->blksz;
118 disk_partition_clr_uuid(&info);
121 return fat_set_blk_dev(dev_desc, &info);
125 * Extract zero terminated short name from a directory entry.
127 static void get_name(dir_entry *dirent, char *s_name)
131 memcpy(s_name, dirent->nameext.name, 8);
134 while (*ptr && *ptr != ' ')
136 if (dirent->lcase & CASE_LOWER_BASE)
137 downcase(s_name, (unsigned)(ptr - s_name));
138 if (dirent->nameext.ext[0] && dirent->nameext.ext[0] != ' ') {
140 memcpy(ptr, dirent->nameext.ext, 3);
141 if (dirent->lcase & CASE_LOWER_EXT)
144 while (*ptr && *ptr != ' ')
148 if (*s_name == DELETED_FLAG)
150 else if (*s_name == aRING)
151 *s_name = DELETED_FLAG;
154 static int flush_dirty_fat_buffer(fsdata *mydata);
156 #if !CONFIG_IS_ENABLED(FAT_WRITE)
157 /* Stub for read only operation */
158 int flush_dirty_fat_buffer(fsdata *mydata)
166 * Get the entry at index 'entry' in a FAT (12/16/32) table.
167 * On failure 0x00 is returned.
169 static __u32 get_fatent(fsdata *mydata, __u32 entry)
175 if (CHECK_CLUST(entry, mydata->fatsize)) {
176 log_err("Invalid FAT entry: %#08x\n", entry);
180 switch (mydata->fatsize) {
182 bufnum = entry / FAT32BUFSIZE;
183 offset = entry - bufnum * FAT32BUFSIZE;
186 bufnum = entry / FAT16BUFSIZE;
187 offset = entry - bufnum * FAT16BUFSIZE;
190 bufnum = entry / FAT12BUFSIZE;
191 offset = entry - bufnum * FAT12BUFSIZE;
195 /* Unsupported FAT size */
199 debug("FAT%d: entry: 0x%08x = %d, offset: 0x%04x = %d\n",
200 mydata->fatsize, entry, entry, offset, offset);
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;
209 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
210 if (startblock + getsize > fatlength)
211 getsize = fatlength - startblock;
213 startblock += mydata->fat_sect; /* Offset from start of disk */
215 /* Write back the fatbuf to the disk */
216 if (flush_dirty_fat_buffer(mydata) < 0)
219 if (disk_read(startblock, getsize, bufptr) < 0) {
220 debug("Error reading FAT blocks\n");
223 mydata->fatbufnum = bufnum;
226 /* Get the actual entry from the table */
227 switch (mydata->fatsize) {
229 ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]);
232 ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]);
235 off8 = (offset * 3) / 2;
236 /* fatbut + off8 may be unaligned, read in byte granularity */
237 ret = mydata->fatbuf[off8] + (mydata->fatbuf[off8 + 1] << 8);
243 debug("FAT%d: ret: 0x%08x, entry: 0x%08x, offset: 0x%04x\n",
244 mydata->fatsize, ret, entry, offset);
250 * Read at most 'size' bytes from the specified cluster into 'buffer'.
251 * Return 0 on success, -1 otherwise.
254 get_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer, unsigned long size)
260 startsect = clust_to_sect(mydata, clustnum);
262 startsect = mydata->rootdir_sect;
265 debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect);
267 if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
268 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
270 debug("FAT: Misaligned buffer address (%p)\n", buffer);
272 while (size >= mydata->sect_size) {
273 ret = disk_read(startsect++, 1, tmpbuf);
275 debug("Error reading data (got %d)\n", ret);
279 memcpy(buffer, tmpbuf, mydata->sect_size);
280 buffer += mydata->sect_size;
281 size -= mydata->sect_size;
283 } else if (size >= mydata->sect_size) {
285 __u32 sect_count = size / mydata->sect_size;
287 ret = disk_read(startsect, sect_count, buffer);
288 if (ret != sect_count) {
289 debug("Error reading data (got %d)\n", ret);
292 bytes_read = sect_count * mydata->sect_size;
293 startsect += sect_count;
294 buffer += bytes_read;
298 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
300 ret = disk_read(startsect, 1, tmpbuf);
302 debug("Error reading data (got %d)\n", ret);
306 memcpy(buffer, tmpbuf, size);
313 * get_contents() - read from file
315 * Read at most 'maxsize' bytes from 'pos' in the file associated with 'dentptr'
316 * into 'buffer'. Update the number of bytes read in *gotsize or return -1 on
319 * @mydata: file system description
320 * @dentprt: directory entry pointer
321 * @pos: position from where to read
322 * @buffer: buffer into which to read
323 * @maxsize: maximum number of bytes to read
324 * @gotsize: number of bytes actually read
325 * Return: -1 on error, otherwise 0
327 static int get_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos,
328 __u8 *buffer, loff_t maxsize, loff_t *gotsize)
330 loff_t filesize = FAT2CPU32(dentptr->size);
331 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
332 __u32 curclust = START(dentptr);
333 __u32 endclust, newclust;
337 debug("Filesize: %llu bytes\n", filesize);
339 if (pos >= filesize) {
340 debug("Read position past EOF: %llu\n", pos);
344 if (maxsize > 0 && filesize > pos + maxsize)
345 filesize = pos + maxsize;
347 debug("%llu bytes\n", filesize);
349 actsize = bytesperclust;
351 /* go to cluster at pos */
352 while (actsize <= pos) {
353 curclust = get_fatent(mydata, curclust);
354 if (CHECK_CLUST(curclust, mydata->fatsize)) {
355 debug("curclust: 0x%x\n", curclust);
356 printf("Invalid FAT entry\n");
359 actsize += bytesperclust;
363 actsize -= bytesperclust;
367 /* align to beginning of next cluster if any */
371 actsize = min(filesize, (loff_t)bytesperclust);
372 tmp_buffer = malloc_cache_aligned(actsize);
374 debug("Error: allocating buffer\n");
378 if (get_cluster(mydata, curclust, tmp_buffer, actsize) != 0) {
379 printf("Error reading cluster\n");
385 memcpy(buffer, tmp_buffer + pos, actsize);
392 curclust = get_fatent(mydata, curclust);
393 if (CHECK_CLUST(curclust, mydata->fatsize)) {
394 debug("curclust: 0x%x\n", curclust);
395 printf("Invalid FAT entry\n");
400 actsize = bytesperclust;
404 /* search for consecutive clusters */
405 while (actsize < filesize) {
406 newclust = get_fatent(mydata, endclust);
407 if ((newclust - 1) != endclust)
409 if (CHECK_CLUST(newclust, mydata->fatsize)) {
410 debug("curclust: 0x%x\n", newclust);
411 printf("Invalid FAT entry\n");
415 actsize += bytesperclust;
418 /* get remaining bytes */
420 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
421 printf("Error reading cluster\n");
427 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
428 printf("Error reading cluster\n");
431 *gotsize += (int)actsize;
435 curclust = get_fatent(mydata, endclust);
436 if (CHECK_CLUST(curclust, mydata->fatsize)) {
437 debug("curclust: 0x%x\n", curclust);
438 printf("Invalid FAT entry\n");
441 actsize = bytesperclust;
447 * Extract the file name information from 'slotptr' into 'l_name',
448 * starting at l_name[*idx].
449 * Return 1 if terminator (zero byte) is found, 0 otherwise.
451 static int slot2str(dir_slot *slotptr, char *l_name, int *idx)
455 for (j = 0; j <= 8; j += 2) {
456 l_name[*idx] = slotptr->name0_4[j];
457 if (l_name[*idx] == 0x00)
461 for (j = 0; j <= 10; j += 2) {
462 l_name[*idx] = slotptr->name5_10[j];
463 if (l_name[*idx] == 0x00)
467 for (j = 0; j <= 2; j += 2) {
468 l_name[*idx] = slotptr->name11_12[j];
469 if (l_name[*idx] == 0x00)
477 /* Calculate short name checksum */
478 static __u8 mkcksum(struct nameext *nameext)
481 u8 *pos = (void *)nameext;
485 for (i = 0; i < 11; i++)
486 ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + pos[i];
492 * Determine if the FAT type is FAT12 or FAT16
494 * Based on fat_fill_super() from the Linux kernel's fs/fat/inode.c
496 static int determine_legacy_fat_bits(const boot_sector *bs)
498 u16 fat_start = bs->reserved;
499 u32 dir_start = fat_start + bs->fats * bs->fat_length;
500 u32 rootdir_sectors = get_unaligned_le16(bs->dir_entries) *
502 get_unaligned_le16(bs->sector_size);
503 u32 data_start = dir_start + rootdir_sectors;
504 u16 sectors = get_unaligned_le16(bs->sectors);
505 u32 total_sectors = sectors ? sectors : bs->total_sect;
506 u32 total_clusters = (total_sectors - data_start) /
509 return (total_clusters > MAX_FAT12) ? 16 : 12;
513 * Determines if the boot sector's media field is valid
515 * Based on fat_valid_media() from Linux kernel's include/linux/msdos_fs.h
517 static int fat_valid_media(u8 media)
519 return media >= 0xf8 || media == 0xf0;
523 * Determines if the given boot sector is valid
525 * Based on fat_read_bpb() from the Linux kernel's fs/fat/inode.c
527 static int is_bootsector_valid(const boot_sector *bs)
529 u16 sector_size = get_unaligned_le16(bs->sector_size);
530 u16 dir_per_block = sector_size / sizeof(dir_entry);
538 if (!fat_valid_media(bs->media))
541 if (!is_power_of_2(sector_size) ||
546 if (!is_power_of_2(bs->cluster_size))
549 if (!bs->fat_length && !bs->fat32_length)
552 if (get_unaligned_le16(bs->dir_entries) & (dir_per_block - 1))
559 * Read boot sector and volume info from a FAT filesystem
562 read_bootsectandvi(boot_sector *bs, volume_info *volinfo, int *fatsize)
565 volume_info *vistart;
568 if (cur_dev == NULL) {
569 debug("Error: no device selected\n");
573 block = malloc_cache_aligned(cur_dev->blksz);
575 debug("Error: allocating block\n");
579 if (disk_read(0, 1, block) < 0) {
580 debug("Error: reading block\n");
585 memcpy(bs, block, sizeof(boot_sector));
586 bs->reserved = FAT2CPU16(bs->reserved);
587 bs->fat_length = FAT2CPU16(bs->fat_length);
588 bs->secs_track = FAT2CPU16(bs->secs_track);
589 bs->heads = FAT2CPU16(bs->heads);
590 bs->total_sect = FAT2CPU32(bs->total_sect);
592 if (!is_bootsector_valid(bs)) {
593 debug("Error: bootsector is invalid\n");
599 if (!bs->fat_length && bs->fat32_length) {
601 bs->fat32_length = FAT2CPU32(bs->fat32_length);
602 bs->flags = FAT2CPU16(bs->flags);
603 bs->root_cluster = FAT2CPU32(bs->root_cluster);
604 bs->info_sector = FAT2CPU16(bs->info_sector);
605 bs->backup_boot = FAT2CPU16(bs->backup_boot);
606 vistart = (volume_info *)(block + sizeof(boot_sector));
609 vistart = (volume_info *)&(bs->fat32_length);
610 *fatsize = determine_legacy_fat_bits(bs);
612 memcpy(volinfo, vistart, sizeof(volume_info));
619 static int get_fs_info(fsdata *mydata)
625 ret = read_bootsectandvi(&bs, &volinfo, &mydata->fatsize);
627 debug("Error: reading boot sector\n");
631 if (mydata->fatsize == 32) {
632 mydata->fatlength = bs.fat32_length;
633 mydata->total_sect = bs.total_sect;
635 mydata->fatlength = bs.fat_length;
636 mydata->total_sect = get_unaligned_le16(bs.sectors);
637 if (!mydata->total_sect)
638 mydata->total_sect = bs.total_sect;
640 if (!mydata->total_sect) /* unlikely */
641 mydata->total_sect = (u32)cur_part_info.size;
643 mydata->fats = bs.fats;
644 mydata->fat_sect = bs.reserved;
646 mydata->rootdir_sect = mydata->fat_sect + mydata->fatlength * bs.fats;
648 mydata->sect_size = get_unaligned_le16(bs.sector_size);
649 mydata->clust_size = bs.cluster_size;
650 if (mydata->sect_size != cur_part_info.blksz) {
651 log_err("FAT sector size mismatch (fs=%u, dev=%lu)\n",
652 mydata->sect_size, cur_part_info.blksz);
655 if (mydata->clust_size == 0) {
656 log_err("FAT cluster size not set\n");
659 if ((unsigned int)mydata->clust_size * mydata->sect_size >
661 log_err("FAT cluster size too big (cs=%u, max=%u)\n",
662 (uint)mydata->clust_size * mydata->sect_size,
667 if (mydata->fatsize == 32) {
668 mydata->data_begin = mydata->rootdir_sect -
669 (mydata->clust_size * 2);
670 mydata->root_cluster = bs.root_cluster;
672 mydata->rootdir_size = (get_unaligned_le16(bs.dir_entries) *
675 mydata->data_begin = mydata->rootdir_sect +
676 mydata->rootdir_size -
677 (mydata->clust_size * 2);
680 * The root directory is not cluster-aligned and may be on a
681 * "negative" cluster, this will be handled specially in
682 * fat_next_cluster().
684 mydata->root_cluster = 0;
687 mydata->fatbufnum = -1;
688 mydata->fat_dirty = 0;
689 mydata->fatbuf = malloc_cache_aligned(FATBUFSIZE);
690 if (mydata->fatbuf == NULL) {
691 debug("Error: allocating memory\n");
695 debug("FAT%d, fat_sect: %d, fatlength: %d\n",
696 mydata->fatsize, mydata->fat_sect, mydata->fatlength);
697 debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n"
698 "Data begins at: %d\n",
699 mydata->root_cluster,
700 mydata->rootdir_sect,
701 mydata->rootdir_sect * mydata->sect_size, mydata->data_begin);
702 debug("Sector size: %d, cluster size: %d\n", mydata->sect_size,
709 * struct fat_itr - directory iterator, to simplify filesystem traversal
711 * Implements an iterator pattern to traverse directory tables,
712 * transparently handling directory tables split across multiple
713 * clusters, and the difference between FAT12/FAT16 root directory
714 * (contiguous) and subdirectories + FAT32 root (chained).
720 * for (fat_itr_root(&itr, fsdata); fat_itr_next(&itr); ) {
721 * // to traverse down to a subdirectory pointed to by
722 * // current iterator position:
723 * fat_itr_child(&itr, &itr);
726 * For a more complete example, see fat_itr_resolve().
730 * @fsdata: filesystem parameters
734 * @start_clust: first cluster
736 unsigned int start_clust;
738 * @clust: current cluster
742 * @next_clust: next cluster if remaining == 0
744 unsigned int next_clust;
746 * @last_cluster: set if last cluster of directory reached
750 * @is_root: is iterator at root directory
754 * @remaining: remaining directory entries in current cluster
758 * @dent: current directory entry
762 * @dent_rem: remaining entries after long name start
766 * @dent_clust: cluster of long name start
768 unsigned int dent_clust;
770 * @dent_start: first directory entry for long name
772 dir_entry *dent_start;
774 * @l_name: long name of current directory entry
776 char l_name[VFAT_MAXLEN_BYTES];
778 * @s_name: short 8.3 name of current directory entry
782 * @name: l_name if there is one, else s_name
786 * @block: buffer for current cluster
788 u8 block[MAX_CLUSTSIZE] __aligned(ARCH_DMA_MINALIGN);
791 static int fat_itr_isdir(fat_itr *itr);
794 * fat_itr_root() - initialize an iterator to start at the root
797 * @itr: iterator to initialize
798 * @fsdata: filesystem data for the partition
799 * Return: 0 on success, else -errno
801 static int fat_itr_root(fat_itr *itr, fsdata *fsdata)
803 if (get_fs_info(fsdata))
806 itr->fsdata = fsdata;
807 itr->start_clust = fsdata->root_cluster;
808 itr->clust = fsdata->root_cluster;
809 itr->next_clust = fsdata->root_cluster;
812 itr->last_cluster = 0;
819 * fat_itr_child() - initialize an iterator to descend into a sub-
822 * Initializes 'itr' to iterate the contents of the directory at
823 * the current cursor position of 'parent'. It is an error to
824 * call this if the current cursor of 'parent' is pointing at a
827 * Note that 'itr' and 'parent' can be the same pointer if you do
828 * not need to preserve 'parent' after this call, which is useful
829 * for traversing directory structure to resolve a file/directory.
831 * @itr: iterator to initialize
832 * @parent: the iterator pointing at a directory entry in the
833 * parent directory of the directory to iterate
835 static void fat_itr_child(fat_itr *itr, fat_itr *parent)
837 fsdata *mydata = parent->fsdata; /* for silly macros */
838 unsigned clustnum = START(parent->dent);
840 assert(fat_itr_isdir(parent));
842 itr->fsdata = parent->fsdata;
843 itr->start_clust = clustnum;
845 itr->clust = clustnum;
846 itr->next_clust = clustnum;
849 itr->clust = parent->fsdata->root_cluster;
850 itr->next_clust = parent->fsdata->root_cluster;
851 itr->start_clust = parent->fsdata->root_cluster;
856 itr->last_cluster = 0;
860 * fat_next_cluster() - load next FAT cluster
862 * The function is used when iterating through directories. It loads the
863 * next cluster with directory entries
865 * @itr: directory iterator
866 * @nbytes: number of bytes read, 0 on error
867 * Return: first directory entry, NULL on error
869 void *fat_next_cluster(fat_itr *itr, unsigned int *nbytes)
875 /* have we reached the end? */
876 if (itr->last_cluster)
879 if (itr->is_root && itr->fsdata->fatsize != 32) {
881 * The root directory is located before the data area and
882 * cannot be indexed using the regular unsigned cluster
883 * numbers (it may start at a "negative" cluster or not at a
884 * cluster boundary at all), so consider itr->next_clust to be
885 * a offset in cluster-sized units from the start of rootdir.
887 unsigned sect_offset = itr->next_clust * itr->fsdata->clust_size;
888 unsigned remaining_sects = itr->fsdata->rootdir_size - sect_offset;
889 sect = itr->fsdata->rootdir_sect + sect_offset;
890 /* do not read past the end of rootdir */
891 read_size = min_t(u32, itr->fsdata->clust_size,
894 sect = clust_to_sect(itr->fsdata, itr->next_clust);
895 read_size = itr->fsdata->clust_size;
898 log_debug("FAT read(sect=%d), clust_size=%d, read_size=%u\n",
899 sect, itr->fsdata->clust_size, read_size);
902 * NOTE: do_fat_read_at() had complicated logic to deal w/
903 * vfat names that span multiple clusters in the fat16 case,
904 * which get_dentfromdir() probably also needed (and was
905 * missing). And not entirely sure what fat32 didn't have
906 * the same issue.. We solve that by only caring about one
907 * dent at a time and iteratively constructing the vfat long
910 ret = disk_read(sect, read_size, itr->block);
912 debug("Error: reading block\n");
916 *nbytes = read_size * itr->fsdata->sect_size;
917 itr->clust = itr->next_clust;
918 if (itr->is_root && itr->fsdata->fatsize != 32) {
920 if (itr->next_clust * itr->fsdata->clust_size >=
921 itr->fsdata->rootdir_size) {
922 debug("nextclust: 0x%x\n", itr->next_clust);
923 itr->last_cluster = 1;
926 itr->next_clust = get_fatent(itr->fsdata, itr->next_clust);
927 if (CHECK_CLUST(itr->next_clust, itr->fsdata->fatsize)) {
928 debug("nextclust: 0x%x\n", itr->next_clust);
929 itr->last_cluster = 1;
936 static dir_entry *next_dent(fat_itr *itr)
938 if (itr->remaining == 0) {
940 struct dir_entry *dent = fat_next_cluster(itr, &nbytes);
942 /* have we reached the last cluster? */
944 /* a sign for no more entries left */
949 itr->remaining = nbytes / sizeof(dir_entry) - 1;
956 /* have we reached the last valid entry? */
957 if (itr->dent->nameext.name[0] == 0)
963 static dir_entry *extract_vfat_name(fat_itr *itr)
965 struct dir_entry *dent = itr->dent;
966 int seqn = itr->dent->nameext.name[0] & ~LAST_LONG_ENTRY_MASK;
967 u8 chksum, alias_checksum = ((dir_slot *)dent)->alias_checksum;
974 slot2str((dir_slot *)dent, buf, &idx);
976 if (n + idx >= sizeof(itr->l_name))
979 /* shift accumulated long-name up and copy new part in: */
980 memmove(itr->l_name + idx, itr->l_name, n);
981 memcpy(itr->l_name, buf, idx);
984 dent = next_dent(itr);
990 * We are now at the short file name entry.
991 * If it is marked as deleted, just skip it.
993 if (dent->nameext.name[0] == DELETED_FLAG ||
994 dent->nameext.name[0] == aRING)
997 itr->l_name[n] = '\0';
999 chksum = mkcksum(&dent->nameext);
1001 /* checksum mismatch could mean deleted file, etc.. skip it: */
1002 if (chksum != alias_checksum) {
1003 debug("** chksum=%x, alias_checksum=%x, l_name=%s, s_name=%8s.%3s\n",
1004 chksum, alias_checksum, itr->l_name, dent->nameext.name,
1013 * fat_itr_next() - step to the next entry in a directory
1015 * Must be called once on a new iterator before the cursor is valid.
1017 * @itr: the iterator to iterate
1018 * Return: boolean, 1 if success or 0 if no more entries in the
1021 static int fat_itr_next(fat_itr *itr)
1028 * One logical directory entry consist of following slots:
1029 * name[0] Attributes
1030 * dent[N - N]: LFN[N - 1] N|0x40 ATTR_VFAT
1032 * dent[N - 2]: LFN[1] 2 ATTR_VFAT
1033 * dent[N - 1]: LFN[0] 1 ATTR_VFAT
1034 * dent[N]: SFN ATTR_ARCH
1038 dent = next_dent(itr);
1040 itr->dent_start = NULL;
1043 itr->dent_rem = itr->remaining;
1044 itr->dent_start = itr->dent;
1045 itr->dent_clust = itr->clust;
1046 if (dent->nameext.name[0] == DELETED_FLAG)
1049 if (dent->attr & ATTR_VOLUME) {
1050 if ((dent->attr & ATTR_VFAT) == ATTR_VFAT &&
1051 (dent->nameext.name[0] & LAST_LONG_ENTRY_MASK)) {
1052 /* long file name */
1053 dent = extract_vfat_name(itr);
1055 * If succeeded, dent has a valid short file
1056 * name entry for the current entry.
1057 * If failed, itr points to a current bogus
1058 * entry. So after fetching a next one,
1059 * it may have a short file name entry
1060 * for this bogus entry so that we can still
1061 * check for a short name.
1065 itr->name = itr->l_name;
1068 /* Volume label or VFAT entry, skip */
1073 /* short file name */
1077 get_name(dent, itr->s_name);
1079 itr->name = itr->s_name;
1085 * fat_itr_isdir() - is current cursor position pointing to a directory
1087 * @itr: the iterator
1088 * Return: true if cursor is at a directory
1090 static int fat_itr_isdir(fat_itr *itr)
1092 return !!(itr->dent->attr & ATTR_DIR);
1099 #define TYPE_FILE 0x1
1100 #define TYPE_DIR 0x2
1101 #define TYPE_ANY (TYPE_FILE | TYPE_DIR)
1104 * fat_itr_resolve() - traverse directory structure to resolve the
1107 * Traverse directory structure to the requested path. If the specified
1108 * path is to a directory, this will descend into the directory and
1109 * leave it iterator at the start of the directory. If the path is to a
1110 * file, it will leave the iterator in the parent directory with current
1111 * cursor at file's entry in the directory.
1113 * @itr: iterator initialized to root
1114 * @path: the requested path
1115 * @type: bitmask of allowable file types
1116 * Return: 0 on success or -errno
1118 static int fat_itr_resolve(fat_itr *itr, const char *path, unsigned type)
1122 /* chomp any extra leading slashes: */
1123 while (path[0] && ISDIRDELIM(path[0]))
1126 /* are we at the end? */
1127 if (strlen(path) == 0) {
1128 if (!(type & TYPE_DIR))
1133 /* find length of next path entry: */
1135 while (next[0] && !ISDIRDELIM(next[0]))
1139 /* root dir doesn't have "." nor ".." */
1140 if ((((next - path) == 1) && !strncmp(path, ".", 1)) ||
1141 (((next - path) == 2) && !strncmp(path, "..", 2))) {
1142 /* point back to itself */
1143 itr->clust = itr->fsdata->root_cluster;
1144 itr->next_clust = itr->fsdata->root_cluster;
1145 itr->start_clust = itr->fsdata->root_cluster;
1148 itr->last_cluster = 0;
1151 if (type & TYPE_DIR)
1157 return fat_itr_resolve(itr, next, type);
1161 while (fat_itr_next(itr)) {
1163 unsigned n = max(strlen(itr->name), (size_t)(next - path));
1165 /* check both long and short name: */
1166 if (!strncasecmp(path, itr->name, n))
1168 else if (itr->name != itr->s_name &&
1169 !strncasecmp(path, itr->s_name, n))
1175 if (fat_itr_isdir(itr)) {
1176 /* recurse into directory: */
1177 fat_itr_child(itr, itr);
1178 return fat_itr_resolve(itr, next, type);
1179 } else if (next[0]) {
1181 * If next is not empty then we have a case
1182 * like: /path/to/realfile/nonsense
1184 debug("bad trailing path: %s\n", next);
1186 } else if (!(type & TYPE_FILE)) {
1196 int file_fat_detectfs(void)
1199 volume_info volinfo;
1203 if (cur_dev == NULL) {
1204 printf("No current device\n");
1208 if (blk_enabled()) {
1209 printf("Interface: %s\n", blk_get_uclass_name(cur_dev->uclass_id));
1210 printf(" Device %d: ", cur_dev->devnum);
1214 if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
1215 printf("\nNo valid FAT fs found\n");
1219 memcpy(vol_label, volinfo.volume_label, 11);
1220 vol_label[11] = '\0';
1222 printf("Filesystem: FAT%d \"%s\"\n", fatsize, vol_label);
1227 int fat_exists(const char *filename)
1233 itr = malloc_cache_aligned(sizeof(fat_itr));
1236 ret = fat_itr_root(itr, &fsdata);
1240 ret = fat_itr_resolve(itr, filename, TYPE_ANY);
1241 free(fsdata.fatbuf);
1248 * fat2rtc() - convert FAT time stamp to RTC file stamp
1252 * @tm: RTC time stamp
1254 static void __maybe_unused fat2rtc(u16 date, u16 time, struct rtc_time *tm)
1256 tm->tm_mday = date & 0x1f;
1257 tm->tm_mon = (date & 0x1e0) >> 4;
1258 tm->tm_year = (date >> 9) + 1980;
1260 tm->tm_sec = (time & 0x1f) << 1;
1261 tm->tm_min = (time & 0x7e0) >> 5;
1262 tm->tm_hour = time >> 11;
1264 rtc_calc_weekday(tm);
1269 int fat_size(const char *filename, loff_t *size)
1275 itr = malloc_cache_aligned(sizeof(fat_itr));
1278 ret = fat_itr_root(itr, &fsdata);
1282 ret = fat_itr_resolve(itr, filename, TYPE_FILE);
1285 * Directories don't have size, but fs_size() is not
1286 * expected to fail if passed a directory path:
1288 free(fsdata.fatbuf);
1289 ret = fat_itr_root(itr, &fsdata);
1292 ret = fat_itr_resolve(itr, filename, TYPE_DIR);
1298 *size = FAT2CPU32(itr->dent->size);
1300 free(fsdata.fatbuf);
1306 int fat_read_file(const char *filename, void *buf, loff_t offset, loff_t len,
1313 itr = malloc_cache_aligned(sizeof(fat_itr));
1316 ret = fat_itr_root(itr, &fsdata);
1320 ret = fat_itr_resolve(itr, filename, TYPE_FILE);
1324 debug("reading %s at pos %llu\n", filename, offset);
1326 /* For saving default max clustersize memory allocated to malloc pool */
1327 dir_entry *dentptr = itr->dent;
1329 ret = get_contents(&fsdata, dentptr, offset, buf, len, actread);
1332 free(fsdata.fatbuf);
1338 int file_fat_read(const char *filename, void *buffer, int maxsize)
1343 ret = fat_read_file(filename, buffer, 0, maxsize, &actread);
1351 struct fs_dir_stream parent;
1352 struct fs_dirent dirent;
1357 int fat_opendir(const char *filename, struct fs_dir_stream **dirsp)
1362 dir = malloc_cache_aligned(sizeof(*dir));
1365 memset(dir, 0, sizeof(*dir));
1367 ret = fat_itr_root(&dir->itr, &dir->fsdata);
1371 ret = fat_itr_resolve(&dir->itr, filename, TYPE_DIR);
1373 goto fail_free_both;
1375 *dirsp = (struct fs_dir_stream *)dir;
1379 free(dir->fsdata.fatbuf);
1385 int fat_readdir(struct fs_dir_stream *dirs, struct fs_dirent **dentp)
1387 fat_dir *dir = (fat_dir *)dirs;
1388 struct fs_dirent *dent = &dir->dirent;
1390 if (!fat_itr_next(&dir->itr))
1393 memset(dent, 0, sizeof(*dent));
1394 strcpy(dent->name, dir->itr.name);
1395 if (CONFIG_IS_ENABLED(EFI_LOADER)) {
1396 dent->attr = dir->itr.dent->attr;
1397 fat2rtc(le16_to_cpu(dir->itr.dent->cdate),
1398 le16_to_cpu(dir->itr.dent->ctime), &dent->create_time);
1399 fat2rtc(le16_to_cpu(dir->itr.dent->date),
1400 le16_to_cpu(dir->itr.dent->time), &dent->change_time);
1401 fat2rtc(le16_to_cpu(dir->itr.dent->adate),
1402 0, &dent->access_time);
1404 if (fat_itr_isdir(&dir->itr)) {
1405 dent->type = FS_DT_DIR;
1407 dent->type = FS_DT_REG;
1408 dent->size = FAT2CPU32(dir->itr.dent->size);
1416 void fat_closedir(struct fs_dir_stream *dirs)
1418 fat_dir *dir = (fat_dir *)dirs;
1419 free(dir->fsdata.fatbuf);
1423 void fat_close(void)
1427 int fat_uuid(char *uuid_str)
1430 volume_info volinfo;
1435 ret = read_bootsectandvi(&bs, &volinfo, &fatsize);
1439 id = volinfo.volume_id;
1440 sprintf(uuid_str, "%02X%02X-%02X%02X", id[3], id[2], id[1], id[0]);