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
19 #include <asm/byteorder.h>
20 #include <asm/unaligned.h>
24 #include <asm/cache.h>
25 #include <linux/compiler.h>
26 #include <linux/ctype.h>
27 #include <linux/log2.h>
29 /* maximum number of clusters for FAT12 */
30 #define MAX_FAT12 0xFF4
33 * Convert a string to lowercase. Converts at most 'len' characters,
34 * 'len' may be larger than the length of 'str' if 'str' is NULL
37 static void downcase(char *str, size_t len)
39 while (*str != '\0' && len--) {
45 static struct blk_desc *cur_dev;
46 static struct disk_partition cur_part_info;
48 #define DOS_BOOT_MAGIC_OFFSET 0x1fe
49 #define DOS_FS_TYPE_OFFSET 0x36
50 #define DOS_FS32_TYPE_OFFSET 0x52
52 static int disk_read(__u32 block, __u32 nr_blocks, void *buf)
59 ret = blk_dread(cur_dev, cur_part_info.start + block, nr_blocks, buf);
67 int fat_set_blk_dev(struct blk_desc *dev_desc, struct disk_partition *info)
69 ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, dev_desc->blksz);
72 cur_part_info = *info;
74 /* Make sure it has a valid FAT header */
75 if (disk_read(0, 1, buffer) != 1) {
80 /* Check if it's actually a DOS volume */
81 if (memcmp(buffer + DOS_BOOT_MAGIC_OFFSET, "\x55\xAA", 2)) {
86 /* Check for FAT12/FAT16/FAT32 filesystem */
87 if (!memcmp(buffer + DOS_FS_TYPE_OFFSET, "FAT", 3))
89 if (!memcmp(buffer + DOS_FS32_TYPE_OFFSET, "FAT32", 5))
96 int fat_register_device(struct blk_desc *dev_desc, int part_no)
98 struct disk_partition info;
100 /* First close any currently found FAT filesystem */
103 /* Read the partition table, if present */
104 if (part_get_info(dev_desc, part_no, &info)) {
106 log_err("Partition %d invalid on device %d\n", part_no,
112 info.size = dev_desc->lba;
113 info.blksz = dev_desc->blksz;
117 disk_partition_clr_uuid(&info);
120 return fat_set_blk_dev(dev_desc, &info);
124 * Extract zero terminated short name from a directory entry.
126 static void get_name(dir_entry *dirent, char *s_name)
130 memcpy(s_name, dirent->nameext.name, 8);
133 while (*ptr && *ptr != ' ')
135 if (dirent->lcase & CASE_LOWER_BASE)
136 downcase(s_name, (unsigned)(ptr - s_name));
137 if (dirent->nameext.ext[0] && dirent->nameext.ext[0] != ' ') {
139 memcpy(ptr, dirent->nameext.ext, 3);
140 if (dirent->lcase & CASE_LOWER_EXT)
143 while (*ptr && *ptr != ' ')
147 if (*s_name == DELETED_FLAG)
149 else if (*s_name == aRING)
150 *s_name = DELETED_FLAG;
153 static int flush_dirty_fat_buffer(fsdata *mydata);
155 #if !CONFIG_IS_ENABLED(FAT_WRITE)
156 /* Stub for read only operation */
157 int flush_dirty_fat_buffer(fsdata *mydata)
165 * Get the entry at index 'entry' in a FAT (12/16/32) table.
166 * On failure 0x00 is returned.
168 static __u32 get_fatent(fsdata *mydata, __u32 entry)
174 if (CHECK_CLUST(entry, mydata->fatsize)) {
175 log_err("Invalid FAT entry: %#08x\n", entry);
179 switch (mydata->fatsize) {
181 bufnum = entry / FAT32BUFSIZE;
182 offset = entry - bufnum * FAT32BUFSIZE;
185 bufnum = entry / FAT16BUFSIZE;
186 offset = entry - bufnum * FAT16BUFSIZE;
189 bufnum = entry / FAT12BUFSIZE;
190 offset = entry - bufnum * FAT12BUFSIZE;
194 /* Unsupported FAT size */
198 debug("FAT%d: entry: 0x%08x = %d, offset: 0x%04x = %d\n",
199 mydata->fatsize, entry, entry, offset, offset);
201 /* Read a new block of FAT entries into the cache. */
202 if (bufnum != mydata->fatbufnum) {
203 __u32 getsize = FATBUFBLOCKS;
204 __u8 *bufptr = mydata->fatbuf;
205 __u32 fatlength = mydata->fatlength;
206 __u32 startblock = bufnum * FATBUFBLOCKS;
208 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
209 if (startblock + getsize > fatlength)
210 getsize = fatlength - startblock;
212 startblock += mydata->fat_sect; /* Offset from start of disk */
214 /* Write back the fatbuf to the disk */
215 if (flush_dirty_fat_buffer(mydata) < 0)
218 if (disk_read(startblock, getsize, bufptr) < 0) {
219 debug("Error reading FAT blocks\n");
222 mydata->fatbufnum = bufnum;
225 /* Get the actual entry from the table */
226 switch (mydata->fatsize) {
228 ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]);
231 ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]);
234 off8 = (offset * 3) / 2;
235 /* fatbut + off8 may be unaligned, read in byte granularity */
236 ret = mydata->fatbuf[off8] + (mydata->fatbuf[off8 + 1] << 8);
242 debug("FAT%d: ret: 0x%08x, entry: 0x%08x, offset: 0x%04x\n",
243 mydata->fatsize, ret, entry, offset);
249 * Read at most 'size' bytes from the specified cluster into 'buffer'.
250 * Return 0 on success, -1 otherwise.
253 get_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer, unsigned long size)
259 startsect = clust_to_sect(mydata, clustnum);
261 startsect = mydata->rootdir_sect;
264 debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect);
266 if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
267 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
269 debug("FAT: Misaligned buffer address (%p)\n", buffer);
271 while (size >= mydata->sect_size) {
272 ret = disk_read(startsect++, 1, tmpbuf);
274 debug("Error reading data (got %d)\n", ret);
278 memcpy(buffer, tmpbuf, mydata->sect_size);
279 buffer += mydata->sect_size;
280 size -= mydata->sect_size;
282 } else if (size >= mydata->sect_size) {
284 __u32 sect_count = size / mydata->sect_size;
286 ret = disk_read(startsect, sect_count, buffer);
287 if (ret != sect_count) {
288 debug("Error reading data (got %d)\n", ret);
291 bytes_read = sect_count * mydata->sect_size;
292 startsect += sect_count;
293 buffer += bytes_read;
297 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
299 ret = disk_read(startsect, 1, tmpbuf);
301 debug("Error reading data (got %d)\n", ret);
305 memcpy(buffer, tmpbuf, size);
312 * get_contents() - read from file
314 * Read at most 'maxsize' bytes from 'pos' in the file associated with 'dentptr'
315 * into 'buffer'. Update the number of bytes read in *gotsize or return -1 on
318 * @mydata: file system description
319 * @dentprt: directory entry pointer
320 * @pos: position from where to read
321 * @buffer: buffer into which to read
322 * @maxsize: maximum number of bytes to read
323 * @gotsize: number of bytes actually read
324 * Return: -1 on error, otherwise 0
326 static int get_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos,
327 __u8 *buffer, loff_t maxsize, loff_t *gotsize)
329 loff_t filesize = FAT2CPU32(dentptr->size);
330 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
331 __u32 curclust = START(dentptr);
332 __u32 endclust, newclust;
336 debug("Filesize: %llu bytes\n", filesize);
338 if (pos >= filesize) {
339 debug("Read position past EOF: %llu\n", pos);
343 if (maxsize > 0 && filesize > pos + maxsize)
344 filesize = pos + maxsize;
346 debug("%llu bytes\n", filesize);
348 actsize = bytesperclust;
350 /* go to cluster at pos */
351 while (actsize <= pos) {
352 curclust = get_fatent(mydata, curclust);
353 if (CHECK_CLUST(curclust, mydata->fatsize)) {
354 debug("curclust: 0x%x\n", curclust);
355 printf("Invalid FAT entry\n");
358 actsize += bytesperclust;
362 actsize -= bytesperclust;
366 /* align to beginning of next cluster if any */
370 actsize = min(filesize, (loff_t)bytesperclust);
371 tmp_buffer = malloc_cache_aligned(actsize);
373 debug("Error: allocating buffer\n");
377 if (get_cluster(mydata, curclust, tmp_buffer, actsize) != 0) {
378 printf("Error reading cluster\n");
384 memcpy(buffer, tmp_buffer + pos, actsize);
391 curclust = get_fatent(mydata, curclust);
392 if (CHECK_CLUST(curclust, mydata->fatsize)) {
393 debug("curclust: 0x%x\n", curclust);
394 printf("Invalid FAT entry\n");
399 actsize = bytesperclust;
403 /* search for consecutive clusters */
404 while (actsize < filesize) {
405 newclust = get_fatent(mydata, endclust);
406 if ((newclust - 1) != endclust)
408 if (CHECK_CLUST(newclust, mydata->fatsize)) {
409 debug("curclust: 0x%x\n", newclust);
410 printf("Invalid FAT entry\n");
414 actsize += bytesperclust;
417 /* get remaining bytes */
419 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
420 printf("Error reading cluster\n");
426 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
427 printf("Error reading cluster\n");
430 *gotsize += (int)actsize;
434 curclust = get_fatent(mydata, endclust);
435 if (CHECK_CLUST(curclust, mydata->fatsize)) {
436 debug("curclust: 0x%x\n", curclust);
437 printf("Invalid FAT entry\n");
440 actsize = bytesperclust;
446 * Extract the file name information from 'slotptr' into 'l_name',
447 * starting at l_name[*idx].
448 * Return 1 if terminator (zero byte) is found, 0 otherwise.
450 static int slot2str(dir_slot *slotptr, char *l_name, int *idx)
454 for (j = 0; j <= 8; j += 2) {
455 l_name[*idx] = slotptr->name0_4[j];
456 if (l_name[*idx] == 0x00)
460 for (j = 0; j <= 10; j += 2) {
461 l_name[*idx] = slotptr->name5_10[j];
462 if (l_name[*idx] == 0x00)
466 for (j = 0; j <= 2; j += 2) {
467 l_name[*idx] = slotptr->name11_12[j];
468 if (l_name[*idx] == 0x00)
476 /* Calculate short name checksum */
477 static __u8 mkcksum(struct nameext *nameext)
480 u8 *pos = (void *)nameext;
484 for (i = 0; i < 11; i++)
485 ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + pos[i];
491 * Determine if the FAT type is FAT12 or FAT16
493 * Based on fat_fill_super() from the Linux kernel's fs/fat/inode.c
495 static int determine_legacy_fat_bits(const boot_sector *bs)
497 u16 fat_start = bs->reserved;
498 u32 dir_start = fat_start + bs->fats * bs->fat_length;
499 u32 rootdir_sectors = get_unaligned_le16(bs->dir_entries) *
501 get_unaligned_le16(bs->sector_size);
502 u32 data_start = dir_start + rootdir_sectors;
503 u16 sectors = get_unaligned_le16(bs->sectors);
504 u32 total_sectors = sectors ? sectors : bs->total_sect;
505 u32 total_clusters = (total_sectors - data_start) /
508 return (total_clusters > MAX_FAT12) ? 16 : 12;
512 * Determines if the boot sector's media field is valid
514 * Based on fat_valid_media() from Linux kernel's include/linux/msdos_fs.h
516 static int fat_valid_media(u8 media)
518 return media >= 0xf8 || media == 0xf0;
522 * Determines if the given boot sector is valid
524 * Based on fat_read_bpb() from the Linux kernel's fs/fat/inode.c
526 static int is_bootsector_valid(const boot_sector *bs)
528 u16 sector_size = get_unaligned_le16(bs->sector_size);
529 u16 dir_per_block = sector_size / sizeof(dir_entry);
537 if (!fat_valid_media(bs->media))
540 if (!is_power_of_2(sector_size) ||
545 if (!is_power_of_2(bs->cluster_size))
548 if (!bs->fat_length && !bs->fat32_length)
551 if (get_unaligned_le16(bs->dir_entries) & (dir_per_block - 1))
558 * Read boot sector and volume info from a FAT filesystem
561 read_bootsectandvi(boot_sector *bs, volume_info *volinfo, int *fatsize)
564 volume_info *vistart;
567 if (cur_dev == NULL) {
568 debug("Error: no device selected\n");
572 block = malloc_cache_aligned(cur_dev->blksz);
574 debug("Error: allocating block\n");
578 if (disk_read(0, 1, block) < 0) {
579 debug("Error: reading block\n");
584 memcpy(bs, block, sizeof(boot_sector));
585 bs->reserved = FAT2CPU16(bs->reserved);
586 bs->fat_length = FAT2CPU16(bs->fat_length);
587 bs->secs_track = FAT2CPU16(bs->secs_track);
588 bs->heads = FAT2CPU16(bs->heads);
589 bs->total_sect = FAT2CPU32(bs->total_sect);
591 if (!is_bootsector_valid(bs)) {
592 debug("Error: bootsector is invalid\n");
598 if (!bs->fat_length && bs->fat32_length) {
600 bs->fat32_length = FAT2CPU32(bs->fat32_length);
601 bs->flags = FAT2CPU16(bs->flags);
602 bs->root_cluster = FAT2CPU32(bs->root_cluster);
603 bs->info_sector = FAT2CPU16(bs->info_sector);
604 bs->backup_boot = FAT2CPU16(bs->backup_boot);
605 vistart = (volume_info *)(block + sizeof(boot_sector));
608 vistart = (volume_info *)&(bs->fat32_length);
609 *fatsize = determine_legacy_fat_bits(bs);
611 memcpy(volinfo, vistart, sizeof(volume_info));
618 static int get_fs_info(fsdata *mydata)
624 ret = read_bootsectandvi(&bs, &volinfo, &mydata->fatsize);
626 debug("Error: reading boot sector\n");
630 if (mydata->fatsize == 32) {
631 mydata->fatlength = bs.fat32_length;
632 mydata->total_sect = bs.total_sect;
634 mydata->fatlength = bs.fat_length;
635 mydata->total_sect = get_unaligned_le16(bs.sectors);
636 if (!mydata->total_sect)
637 mydata->total_sect = bs.total_sect;
639 if (!mydata->total_sect) /* unlikely */
640 mydata->total_sect = (u32)cur_part_info.size;
642 mydata->fats = bs.fats;
643 mydata->fat_sect = bs.reserved;
645 mydata->rootdir_sect = mydata->fat_sect + mydata->fatlength * bs.fats;
647 mydata->sect_size = get_unaligned_le16(bs.sector_size);
648 mydata->clust_size = bs.cluster_size;
649 if (mydata->sect_size != cur_part_info.blksz) {
650 log_err("FAT sector size mismatch (fs=%u, dev=%lu)\n",
651 mydata->sect_size, cur_part_info.blksz);
654 if (mydata->clust_size == 0) {
655 log_err("FAT cluster size not set\n");
658 if ((unsigned int)mydata->clust_size * mydata->sect_size >
660 log_err("FAT cluster size too big (cs=%u, max=%u)\n",
661 (uint)mydata->clust_size * mydata->sect_size,
666 if (mydata->fatsize == 32) {
667 mydata->data_begin = mydata->rootdir_sect -
668 (mydata->clust_size * 2);
669 mydata->root_cluster = bs.root_cluster;
671 mydata->rootdir_size = (get_unaligned_le16(bs.dir_entries) *
674 mydata->data_begin = mydata->rootdir_sect +
675 mydata->rootdir_size -
676 (mydata->clust_size * 2);
679 * The root directory is not cluster-aligned and may be on a
680 * "negative" cluster, this will be handled specially in
681 * fat_next_cluster().
683 mydata->root_cluster = 0;
686 mydata->fatbufnum = -1;
687 mydata->fat_dirty = 0;
688 mydata->fatbuf = malloc_cache_aligned(FATBUFSIZE);
689 if (mydata->fatbuf == NULL) {
690 debug("Error: allocating memory\n");
694 debug("FAT%d, fat_sect: %d, fatlength: %d\n",
695 mydata->fatsize, mydata->fat_sect, mydata->fatlength);
696 debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n"
697 "Data begins at: %d\n",
698 mydata->root_cluster,
699 mydata->rootdir_sect,
700 mydata->rootdir_sect * mydata->sect_size, mydata->data_begin);
701 debug("Sector size: %d, cluster size: %d\n", mydata->sect_size,
708 * struct fat_itr - directory iterator, to simplify filesystem traversal
710 * Implements an iterator pattern to traverse directory tables,
711 * transparently handling directory tables split across multiple
712 * clusters, and the difference between FAT12/FAT16 root directory
713 * (contiguous) and subdirectories + FAT32 root (chained).
719 * for (fat_itr_root(&itr, fsdata); fat_itr_next(&itr); ) {
720 * // to traverse down to a subdirectory pointed to by
721 * // current iterator position:
722 * fat_itr_child(&itr, &itr);
725 * For a more complete example, see fat_itr_resolve().
729 * @fsdata: filesystem parameters
733 * @start_clust: first cluster
735 unsigned int start_clust;
737 * @clust: current cluster
741 * @next_clust: next cluster if remaining == 0
743 unsigned int next_clust;
745 * @last_cluster: set if last cluster of directory reached
749 * @is_root: is iterator at root directory
753 * @remaining: remaining directory entries in current cluster
757 * @dent: current directory entry
761 * @dent_rem: remaining entries after long name start
765 * @dent_clust: cluster of long name start
767 unsigned int dent_clust;
769 * @dent_start: first directory entry for long name
771 dir_entry *dent_start;
773 * @l_name: long name of current directory entry
775 char l_name[VFAT_MAXLEN_BYTES];
777 * @s_name: short 8.3 name of current directory entry
781 * @name: l_name if there is one, else s_name
785 * @block: buffer for current cluster
787 u8 block[MAX_CLUSTSIZE] __aligned(ARCH_DMA_MINALIGN);
790 static int fat_itr_isdir(fat_itr *itr);
793 * fat_itr_root() - initialize an iterator to start at the root
796 * @itr: iterator to initialize
797 * @fsdata: filesystem data for the partition
798 * Return: 0 on success, else -errno
800 static int fat_itr_root(fat_itr *itr, fsdata *fsdata)
802 if (get_fs_info(fsdata))
805 itr->fsdata = fsdata;
806 itr->start_clust = fsdata->root_cluster;
807 itr->clust = fsdata->root_cluster;
808 itr->next_clust = fsdata->root_cluster;
811 itr->last_cluster = 0;
818 * fat_itr_child() - initialize an iterator to descend into a sub-
821 * Initializes 'itr' to iterate the contents of the directory at
822 * the current cursor position of 'parent'. It is an error to
823 * call this if the current cursor of 'parent' is pointing at a
826 * Note that 'itr' and 'parent' can be the same pointer if you do
827 * not need to preserve 'parent' after this call, which is useful
828 * for traversing directory structure to resolve a file/directory.
830 * @itr: iterator to initialize
831 * @parent: the iterator pointing at a directory entry in the
832 * parent directory of the directory to iterate
834 static void fat_itr_child(fat_itr *itr, fat_itr *parent)
836 fsdata *mydata = parent->fsdata; /* for silly macros */
837 unsigned clustnum = START(parent->dent);
839 assert(fat_itr_isdir(parent));
841 itr->fsdata = parent->fsdata;
842 itr->start_clust = clustnum;
844 itr->clust = clustnum;
845 itr->next_clust = clustnum;
848 itr->clust = parent->fsdata->root_cluster;
849 itr->next_clust = parent->fsdata->root_cluster;
850 itr->start_clust = parent->fsdata->root_cluster;
855 itr->last_cluster = 0;
859 * fat_next_cluster() - load next FAT cluster
861 * The function is used when iterating through directories. It loads the
862 * next cluster with directory entries
864 * @itr: directory iterator
865 * @nbytes: number of bytes read, 0 on error
866 * Return: first directory entry, NULL on error
868 void *fat_next_cluster(fat_itr *itr, unsigned int *nbytes)
874 /* have we reached the end? */
875 if (itr->last_cluster)
878 if (itr->is_root && itr->fsdata->fatsize != 32) {
880 * The root directory is located before the data area and
881 * cannot be indexed using the regular unsigned cluster
882 * numbers (it may start at a "negative" cluster or not at a
883 * cluster boundary at all), so consider itr->next_clust to be
884 * a offset in cluster-sized units from the start of rootdir.
886 unsigned sect_offset = itr->next_clust * itr->fsdata->clust_size;
887 unsigned remaining_sects = itr->fsdata->rootdir_size - sect_offset;
888 sect = itr->fsdata->rootdir_sect + sect_offset;
889 /* do not read past the end of rootdir */
890 read_size = min_t(u32, itr->fsdata->clust_size,
893 sect = clust_to_sect(itr->fsdata, itr->next_clust);
894 read_size = itr->fsdata->clust_size;
897 log_debug("FAT read(sect=%d), clust_size=%d, read_size=%u\n",
898 sect, itr->fsdata->clust_size, read_size);
901 * NOTE: do_fat_read_at() had complicated logic to deal w/
902 * vfat names that span multiple clusters in the fat16 case,
903 * which get_dentfromdir() probably also needed (and was
904 * missing). And not entirely sure what fat32 didn't have
905 * the same issue.. We solve that by only caring about one
906 * dent at a time and iteratively constructing the vfat long
909 ret = disk_read(sect, read_size, itr->block);
911 debug("Error: reading block\n");
915 *nbytes = read_size * itr->fsdata->sect_size;
916 itr->clust = itr->next_clust;
917 if (itr->is_root && itr->fsdata->fatsize != 32) {
919 if (itr->next_clust * itr->fsdata->clust_size >=
920 itr->fsdata->rootdir_size) {
921 debug("nextclust: 0x%x\n", itr->next_clust);
922 itr->last_cluster = 1;
925 itr->next_clust = get_fatent(itr->fsdata, itr->next_clust);
926 if (CHECK_CLUST(itr->next_clust, itr->fsdata->fatsize)) {
927 debug("nextclust: 0x%x\n", itr->next_clust);
928 itr->last_cluster = 1;
935 static dir_entry *next_dent(fat_itr *itr)
937 if (itr->remaining == 0) {
939 struct dir_entry *dent = fat_next_cluster(itr, &nbytes);
941 /* have we reached the last cluster? */
943 /* a sign for no more entries left */
948 itr->remaining = nbytes / sizeof(dir_entry) - 1;
955 /* have we reached the last valid entry? */
956 if (itr->dent->nameext.name[0] == 0)
962 static dir_entry *extract_vfat_name(fat_itr *itr)
964 struct dir_entry *dent = itr->dent;
965 int seqn = itr->dent->nameext.name[0] & ~LAST_LONG_ENTRY_MASK;
966 u8 chksum, alias_checksum = ((dir_slot *)dent)->alias_checksum;
973 slot2str((dir_slot *)dent, buf, &idx);
975 if (n + idx >= sizeof(itr->l_name))
978 /* shift accumulated long-name up and copy new part in: */
979 memmove(itr->l_name + idx, itr->l_name, n);
980 memcpy(itr->l_name, buf, idx);
983 dent = next_dent(itr);
989 * We are now at the short file name entry.
990 * If it is marked as deleted, just skip it.
992 if (dent->nameext.name[0] == DELETED_FLAG ||
993 dent->nameext.name[0] == aRING)
996 itr->l_name[n] = '\0';
998 chksum = mkcksum(&dent->nameext);
1000 /* checksum mismatch could mean deleted file, etc.. skip it: */
1001 if (chksum != alias_checksum) {
1002 debug("** chksum=%x, alias_checksum=%x, l_name=%s, s_name=%8s.%3s\n",
1003 chksum, alias_checksum, itr->l_name, dent->nameext.name,
1012 * fat_itr_next() - step to the next entry in a directory
1014 * Must be called once on a new iterator before the cursor is valid.
1016 * @itr: the iterator to iterate
1017 * Return: boolean, 1 if success or 0 if no more entries in the
1020 static int fat_itr_next(fat_itr *itr)
1027 * One logical directory entry consist of following slots:
1028 * name[0] Attributes
1029 * dent[N - N]: LFN[N - 1] N|0x40 ATTR_VFAT
1031 * dent[N - 2]: LFN[1] 2 ATTR_VFAT
1032 * dent[N - 1]: LFN[0] 1 ATTR_VFAT
1033 * dent[N]: SFN ATTR_ARCH
1037 dent = next_dent(itr);
1039 itr->dent_start = NULL;
1042 itr->dent_rem = itr->remaining;
1043 itr->dent_start = itr->dent;
1044 itr->dent_clust = itr->clust;
1045 if (dent->nameext.name[0] == DELETED_FLAG)
1048 if (dent->attr & ATTR_VOLUME) {
1049 if ((dent->attr & ATTR_VFAT) == ATTR_VFAT &&
1050 (dent->nameext.name[0] & LAST_LONG_ENTRY_MASK)) {
1051 /* long file name */
1052 dent = extract_vfat_name(itr);
1054 * If succeeded, dent has a valid short file
1055 * name entry for the current entry.
1056 * If failed, itr points to a current bogus
1057 * entry. So after fetching a next one,
1058 * it may have a short file name entry
1059 * for this bogus entry so that we can still
1060 * check for a short name.
1064 itr->name = itr->l_name;
1067 /* Volume label or VFAT entry, skip */
1072 /* short file name */
1076 get_name(dent, itr->s_name);
1078 itr->name = itr->s_name;
1084 * fat_itr_isdir() - is current cursor position pointing to a directory
1086 * @itr: the iterator
1087 * Return: true if cursor is at a directory
1089 static int fat_itr_isdir(fat_itr *itr)
1091 return !!(itr->dent->attr & ATTR_DIR);
1098 #define TYPE_FILE 0x1
1099 #define TYPE_DIR 0x2
1100 #define TYPE_ANY (TYPE_FILE | TYPE_DIR)
1103 * fat_itr_resolve() - traverse directory structure to resolve the
1106 * Traverse directory structure to the requested path. If the specified
1107 * path is to a directory, this will descend into the directory and
1108 * leave it iterator at the start of the directory. If the path is to a
1109 * file, it will leave the iterator in the parent directory with current
1110 * cursor at file's entry in the directory.
1112 * @itr: iterator initialized to root
1113 * @path: the requested path
1114 * @type: bitmask of allowable file types
1115 * Return: 0 on success or -errno
1117 static int fat_itr_resolve(fat_itr *itr, const char *path, unsigned type)
1121 /* chomp any extra leading slashes: */
1122 while (path[0] && ISDIRDELIM(path[0]))
1125 /* are we at the end? */
1126 if (strlen(path) == 0) {
1127 if (!(type & TYPE_DIR))
1132 /* find length of next path entry: */
1134 while (next[0] && !ISDIRDELIM(next[0]))
1138 /* root dir doesn't have "." nor ".." */
1139 if ((((next - path) == 1) && !strncmp(path, ".", 1)) ||
1140 (((next - path) == 2) && !strncmp(path, "..", 2))) {
1141 /* point back to itself */
1142 itr->clust = itr->fsdata->root_cluster;
1143 itr->next_clust = itr->fsdata->root_cluster;
1144 itr->start_clust = itr->fsdata->root_cluster;
1147 itr->last_cluster = 0;
1150 if (type & TYPE_DIR)
1156 return fat_itr_resolve(itr, next, type);
1160 while (fat_itr_next(itr)) {
1162 unsigned n = max(strlen(itr->name), (size_t)(next - path));
1164 /* check both long and short name: */
1165 if (!strncasecmp(path, itr->name, n))
1167 else if (itr->name != itr->s_name &&
1168 !strncasecmp(path, itr->s_name, n))
1174 if (fat_itr_isdir(itr)) {
1175 /* recurse into directory: */
1176 fat_itr_child(itr, itr);
1177 return fat_itr_resolve(itr, next, type);
1178 } else if (next[0]) {
1180 * If next is not empty then we have a case
1181 * like: /path/to/realfile/nonsense
1183 debug("bad trailing path: %s\n", next);
1185 } else if (!(type & TYPE_FILE)) {
1195 int file_fat_detectfs(void)
1198 volume_info volinfo;
1202 if (cur_dev == NULL) {
1203 printf("No current device\n");
1207 if (blk_enabled()) {
1208 printf("Interface: %s\n", blk_get_uclass_name(cur_dev->uclass_id));
1209 printf(" Device %d: ", cur_dev->devnum);
1213 if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
1214 printf("\nNo valid FAT fs found\n");
1218 memcpy(vol_label, volinfo.volume_label, 11);
1219 vol_label[11] = '\0';
1221 printf("Filesystem: FAT%d \"%s\"\n", fatsize, vol_label);
1226 int fat_exists(const char *filename)
1232 itr = malloc_cache_aligned(sizeof(fat_itr));
1235 ret = fat_itr_root(itr, &fsdata);
1239 ret = fat_itr_resolve(itr, filename, TYPE_ANY);
1240 free(fsdata.fatbuf);
1247 * fat2rtc() - convert FAT time stamp to RTC file stamp
1251 * @tm: RTC time stamp
1253 static void __maybe_unused fat2rtc(u16 date, u16 time, struct rtc_time *tm)
1255 tm->tm_mday = date & 0x1f;
1256 tm->tm_mon = (date & 0x1e0) >> 5;
1257 tm->tm_year = (date >> 9) + 1980;
1259 tm->tm_sec = (time & 0x1f) << 1;
1260 tm->tm_min = (time & 0x7e0) >> 5;
1261 tm->tm_hour = time >> 11;
1263 rtc_calc_weekday(tm);
1268 int fat_size(const char *filename, loff_t *size)
1274 itr = malloc_cache_aligned(sizeof(fat_itr));
1277 ret = fat_itr_root(itr, &fsdata);
1281 ret = fat_itr_resolve(itr, filename, TYPE_FILE);
1284 * Directories don't have size, but fs_size() is not
1285 * expected to fail if passed a directory path:
1287 free(fsdata.fatbuf);
1288 ret = fat_itr_root(itr, &fsdata);
1291 ret = fat_itr_resolve(itr, filename, TYPE_DIR);
1297 *size = FAT2CPU32(itr->dent->size);
1299 free(fsdata.fatbuf);
1305 int fat_read_file(const char *filename, void *buf, loff_t offset, loff_t len,
1312 itr = malloc_cache_aligned(sizeof(fat_itr));
1315 ret = fat_itr_root(itr, &fsdata);
1319 ret = fat_itr_resolve(itr, filename, TYPE_FILE);
1323 debug("reading %s at pos %llu\n", filename, offset);
1325 /* For saving default max clustersize memory allocated to malloc pool */
1326 dir_entry *dentptr = itr->dent;
1328 ret = get_contents(&fsdata, dentptr, offset, buf, len, actread);
1331 free(fsdata.fatbuf);
1337 int file_fat_read(const char *filename, void *buffer, int maxsize)
1342 ret = fat_read_file(filename, buffer, 0, maxsize, &actread);
1350 struct fs_dir_stream parent;
1351 struct fs_dirent dirent;
1356 int fat_opendir(const char *filename, struct fs_dir_stream **dirsp)
1361 dir = malloc_cache_aligned(sizeof(*dir));
1364 memset(dir, 0, sizeof(*dir));
1366 ret = fat_itr_root(&dir->itr, &dir->fsdata);
1370 ret = fat_itr_resolve(&dir->itr, filename, TYPE_DIR);
1372 goto fail_free_both;
1374 *dirsp = (struct fs_dir_stream *)dir;
1378 free(dir->fsdata.fatbuf);
1384 int fat_readdir(struct fs_dir_stream *dirs, struct fs_dirent **dentp)
1386 fat_dir *dir = (fat_dir *)dirs;
1387 struct fs_dirent *dent = &dir->dirent;
1389 if (!fat_itr_next(&dir->itr))
1392 memset(dent, 0, sizeof(*dent));
1393 strcpy(dent->name, dir->itr.name);
1394 if (CONFIG_IS_ENABLED(EFI_LOADER)) {
1395 dent->attr = dir->itr.dent->attr;
1396 fat2rtc(le16_to_cpu(dir->itr.dent->cdate),
1397 le16_to_cpu(dir->itr.dent->ctime), &dent->create_time);
1398 fat2rtc(le16_to_cpu(dir->itr.dent->date),
1399 le16_to_cpu(dir->itr.dent->time), &dent->change_time);
1400 fat2rtc(le16_to_cpu(dir->itr.dent->adate),
1401 0, &dent->access_time);
1403 if (fat_itr_isdir(&dir->itr)) {
1404 dent->type = FS_DT_DIR;
1406 dent->type = FS_DT_REG;
1407 dent->size = FAT2CPU32(dir->itr.dent->size);
1415 void fat_closedir(struct fs_dir_stream *dirs)
1417 fat_dir *dir = (fat_dir *)dirs;
1418 free(dir->fsdata.fatbuf);
1422 void fat_close(void)
1426 int fat_uuid(char *uuid_str)
1429 volume_info volinfo;
1434 ret = read_bootsectandvi(&bs, &volinfo, &fatsize);
1438 id = volinfo.volume_id;
1439 sprintf(uuid_str, "%02X%02X-%02X%02X", id[3], id[2], id[1], id[0]);