1 // SPDX-License-Identifier: GPL-2.0+
5 * R/O (V)FAT 12/16/32 filesystem implementation by Marcus Sundberg
18 #include <asm/byteorder.h>
22 #include <asm/cache.h>
23 #include <linux/compiler.h>
24 #include <linux/ctype.h>
27 * Convert a string to lowercase. Converts at most 'len' characters,
28 * 'len' may be larger than the length of 'str' if 'str' is NULL
31 static void downcase(char *str, size_t len)
33 while (*str != '\0' && len--) {
39 static struct blk_desc *cur_dev;
40 static struct disk_partition cur_part_info;
42 #define DOS_BOOT_MAGIC_OFFSET 0x1fe
43 #define DOS_FS_TYPE_OFFSET 0x36
44 #define DOS_FS32_TYPE_OFFSET 0x52
46 static int disk_read(__u32 block, __u32 nr_blocks, void *buf)
53 ret = blk_dread(cur_dev, cur_part_info.start + block, nr_blocks, buf);
61 int fat_set_blk_dev(struct blk_desc *dev_desc, struct disk_partition *info)
63 ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, dev_desc->blksz);
66 cur_part_info = *info;
68 /* Make sure it has a valid FAT header */
69 if (disk_read(0, 1, buffer) != 1) {
74 /* Check if it's actually a DOS volume */
75 if (memcmp(buffer + DOS_BOOT_MAGIC_OFFSET, "\x55\xAA", 2)) {
80 /* Check for FAT12/FAT16/FAT32 filesystem */
81 if (!memcmp(buffer + DOS_FS_TYPE_OFFSET, "FAT", 3))
83 if (!memcmp(buffer + DOS_FS32_TYPE_OFFSET, "FAT32", 5))
90 int fat_register_device(struct blk_desc *dev_desc, int part_no)
92 struct disk_partition info;
94 /* First close any currently found FAT filesystem */
97 /* Read the partition table, if present */
98 if (part_get_info(dev_desc, part_no, &info)) {
100 printf("** Partition %d not valid on device %d **\n",
101 part_no, dev_desc->devnum);
106 info.size = dev_desc->lba;
107 info.blksz = dev_desc->blksz;
111 #if CONFIG_IS_ENABLED(PARTITION_UUIDS)
116 return fat_set_blk_dev(dev_desc, &info);
120 * Extract zero terminated short name from a directory entry.
122 static void get_name(dir_entry *dirent, char *s_name)
126 memcpy(s_name, dirent->nameext.name, 8);
129 while (*ptr && *ptr != ' ')
131 if (dirent->lcase & CASE_LOWER_BASE)
132 downcase(s_name, (unsigned)(ptr - s_name));
133 if (dirent->nameext.ext[0] && dirent->nameext.ext[0] != ' ') {
135 memcpy(ptr, dirent->nameext.ext, 3);
136 if (dirent->lcase & CASE_LOWER_EXT)
139 while (*ptr && *ptr != ' ')
143 if (*s_name == DELETED_FLAG)
145 else if (*s_name == aRING)
146 *s_name = DELETED_FLAG;
149 static int flush_dirty_fat_buffer(fsdata *mydata);
151 #if !CONFIG_IS_ENABLED(FAT_WRITE)
152 /* Stub for read only operation */
153 int flush_dirty_fat_buffer(fsdata *mydata)
161 * Get the entry at index 'entry' in a FAT (12/16/32) table.
162 * On failure 0x00 is returned.
164 static __u32 get_fatent(fsdata *mydata, __u32 entry)
170 if (CHECK_CLUST(entry, mydata->fatsize)) {
171 printf("Error: Invalid FAT entry: 0x%08x\n", entry);
175 switch (mydata->fatsize) {
177 bufnum = entry / FAT32BUFSIZE;
178 offset = entry - bufnum * FAT32BUFSIZE;
181 bufnum = entry / FAT16BUFSIZE;
182 offset = entry - bufnum * FAT16BUFSIZE;
185 bufnum = entry / FAT12BUFSIZE;
186 offset = entry - bufnum * FAT12BUFSIZE;
190 /* Unsupported FAT size */
194 debug("FAT%d: entry: 0x%08x = %d, offset: 0x%04x = %d\n",
195 mydata->fatsize, entry, entry, offset, offset);
197 /* Read a new block of FAT entries into the cache. */
198 if (bufnum != mydata->fatbufnum) {
199 __u32 getsize = FATBUFBLOCKS;
200 __u8 *bufptr = mydata->fatbuf;
201 __u32 fatlength = mydata->fatlength;
202 __u32 startblock = bufnum * FATBUFBLOCKS;
204 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
205 if (startblock + getsize > fatlength)
206 getsize = fatlength - startblock;
208 startblock += mydata->fat_sect; /* Offset from start of disk */
210 /* Write back the fatbuf to the disk */
211 if (flush_dirty_fat_buffer(mydata) < 0)
214 if (disk_read(startblock, getsize, bufptr) < 0) {
215 debug("Error reading FAT blocks\n");
218 mydata->fatbufnum = bufnum;
221 /* Get the actual entry from the table */
222 switch (mydata->fatsize) {
224 ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]);
227 ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]);
230 off8 = (offset * 3) / 2;
231 /* fatbut + off8 may be unaligned, read in byte granularity */
232 ret = mydata->fatbuf[off8] + (mydata->fatbuf[off8 + 1] << 8);
238 debug("FAT%d: ret: 0x%08x, entry: 0x%08x, offset: 0x%04x\n",
239 mydata->fatsize, ret, entry, offset);
245 * Read at most 'size' bytes from the specified cluster into 'buffer'.
246 * Return 0 on success, -1 otherwise.
249 get_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer, unsigned long size)
255 startsect = clust_to_sect(mydata, clustnum);
257 startsect = mydata->rootdir_sect;
260 debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect);
262 if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
263 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
265 debug("FAT: Misaligned buffer address (%p)\n", buffer);
267 while (size >= mydata->sect_size) {
268 ret = disk_read(startsect++, 1, tmpbuf);
270 debug("Error reading data (got %d)\n", ret);
274 memcpy(buffer, tmpbuf, mydata->sect_size);
275 buffer += mydata->sect_size;
276 size -= mydata->sect_size;
281 idx = size / mydata->sect_size;
285 ret = disk_read(startsect, idx, buffer);
287 debug("Error reading data (got %d)\n", ret);
291 idx *= mydata->sect_size;
296 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
298 ret = disk_read(startsect, 1, tmpbuf);
300 debug("Error reading data (got %d)\n", ret);
304 memcpy(buffer, tmpbuf, size);
311 * get_contents() - read from file
313 * Read at most 'maxsize' bytes from 'pos' in the file associated with 'dentptr'
314 * into 'buffer'. Update the number of bytes read in *gotsize or return -1 on
317 * @mydata: file system description
318 * @dentprt: directory entry pointer
319 * @pos: position from where to read
320 * @buffer: buffer into which to read
321 * @maxsize: maximum number of bytes to read
322 * @gotsize: number of bytes actually read
323 * Return: -1 on error, otherwise 0
325 static int get_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos,
326 __u8 *buffer, loff_t maxsize, loff_t *gotsize)
328 loff_t filesize = FAT2CPU32(dentptr->size);
329 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
330 __u32 curclust = START(dentptr);
331 __u32 endclust, newclust;
335 debug("Filesize: %llu bytes\n", filesize);
337 if (pos >= filesize) {
338 debug("Read position past EOF: %llu\n", pos);
342 if (maxsize > 0 && filesize > pos + maxsize)
343 filesize = pos + maxsize;
345 debug("%llu bytes\n", filesize);
347 actsize = bytesperclust;
349 /* go to cluster at pos */
350 while (actsize <= pos) {
351 curclust = get_fatent(mydata, curclust);
352 if (CHECK_CLUST(curclust, mydata->fatsize)) {
353 debug("curclust: 0x%x\n", curclust);
354 printf("Invalid FAT entry\n");
357 actsize += bytesperclust;
361 actsize -= bytesperclust;
365 /* align to beginning of next cluster if any */
369 actsize = min(filesize, (loff_t)bytesperclust);
370 tmp_buffer = malloc_cache_aligned(actsize);
372 debug("Error: allocating buffer\n");
376 if (get_cluster(mydata, curclust, tmp_buffer, actsize) != 0) {
377 printf("Error reading cluster\n");
383 memcpy(buffer, tmp_buffer + pos, actsize);
390 curclust = get_fatent(mydata, curclust);
391 if (CHECK_CLUST(curclust, mydata->fatsize)) {
392 debug("curclust: 0x%x\n", curclust);
393 printf("Invalid FAT entry\n");
398 actsize = bytesperclust;
402 /* search for consecutive clusters */
403 while (actsize < filesize) {
404 newclust = get_fatent(mydata, endclust);
405 if ((newclust - 1) != endclust)
407 if (CHECK_CLUST(newclust, mydata->fatsize)) {
408 debug("curclust: 0x%x\n", newclust);
409 printf("Invalid FAT entry\n");
413 actsize += bytesperclust;
416 /* get remaining bytes */
418 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
419 printf("Error reading cluster\n");
425 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
426 printf("Error reading cluster\n");
429 *gotsize += (int)actsize;
433 curclust = get_fatent(mydata, endclust);
434 if (CHECK_CLUST(curclust, mydata->fatsize)) {
435 debug("curclust: 0x%x\n", curclust);
436 printf("Invalid FAT entry\n");
439 actsize = bytesperclust;
445 * Extract the file name information from 'slotptr' into 'l_name',
446 * starting at l_name[*idx].
447 * Return 1 if terminator (zero byte) is found, 0 otherwise.
449 static int slot2str(dir_slot *slotptr, char *l_name, int *idx)
453 for (j = 0; j <= 8; j += 2) {
454 l_name[*idx] = slotptr->name0_4[j];
455 if (l_name[*idx] == 0x00)
459 for (j = 0; j <= 10; j += 2) {
460 l_name[*idx] = slotptr->name5_10[j];
461 if (l_name[*idx] == 0x00)
465 for (j = 0; j <= 2; j += 2) {
466 l_name[*idx] = slotptr->name11_12[j];
467 if (l_name[*idx] == 0x00)
475 /* Calculate short name checksum */
476 static __u8 mkcksum(struct nameext *nameext)
479 u8 *pos = (void *)nameext;
483 for (i = 0; i < 11; i++)
484 ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + pos[i];
490 * Read boot sector and volume info from a FAT filesystem
493 read_bootsectandvi(boot_sector *bs, volume_info *volinfo, int *fatsize)
496 volume_info *vistart;
499 if (cur_dev == NULL) {
500 debug("Error: no device selected\n");
504 block = malloc_cache_aligned(cur_dev->blksz);
506 debug("Error: allocating block\n");
510 if (disk_read(0, 1, block) < 0) {
511 debug("Error: reading block\n");
515 memcpy(bs, block, sizeof(boot_sector));
516 bs->reserved = FAT2CPU16(bs->reserved);
517 bs->fat_length = FAT2CPU16(bs->fat_length);
518 bs->secs_track = FAT2CPU16(bs->secs_track);
519 bs->heads = FAT2CPU16(bs->heads);
520 bs->total_sect = FAT2CPU32(bs->total_sect);
523 if (bs->fat_length == 0) {
525 bs->fat32_length = FAT2CPU32(bs->fat32_length);
526 bs->flags = FAT2CPU16(bs->flags);
527 bs->root_cluster = FAT2CPU32(bs->root_cluster);
528 bs->info_sector = FAT2CPU16(bs->info_sector);
529 bs->backup_boot = FAT2CPU16(bs->backup_boot);
530 vistart = (volume_info *)(block + sizeof(boot_sector));
533 vistart = (volume_info *)&(bs->fat32_length);
536 memcpy(volinfo, vistart, sizeof(volume_info));
538 if (*fatsize == 32) {
539 if (strncmp(FAT32_SIGN, vistart->fs_type, SIGNLEN) == 0)
542 if (strncmp(FAT12_SIGN, vistart->fs_type, SIGNLEN) == 0) {
546 if (strncmp(FAT16_SIGN, vistart->fs_type, SIGNLEN) == 0) {
552 debug("Error: broken fs_type sign\n");
560 static int get_fs_info(fsdata *mydata)
566 ret = read_bootsectandvi(&bs, &volinfo, &mydata->fatsize);
568 debug("Error: reading boot sector\n");
572 if (mydata->fatsize == 32) {
573 mydata->fatlength = bs.fat32_length;
574 mydata->total_sect = bs.total_sect;
576 mydata->fatlength = bs.fat_length;
577 mydata->total_sect = (bs.sectors[1] << 8) + bs.sectors[0];
578 if (!mydata->total_sect)
579 mydata->total_sect = bs.total_sect;
581 if (!mydata->total_sect) /* unlikely */
582 mydata->total_sect = (u32)cur_part_info.size;
584 mydata->fats = bs.fats;
585 mydata->fat_sect = bs.reserved;
587 mydata->rootdir_sect = mydata->fat_sect + mydata->fatlength * bs.fats;
589 mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0];
590 mydata->clust_size = bs.cluster_size;
591 if (mydata->sect_size != cur_part_info.blksz) {
592 printf("Error: FAT sector size mismatch (fs=%hu, dev=%lu)\n",
593 mydata->sect_size, cur_part_info.blksz);
596 if (mydata->clust_size == 0) {
597 printf("Error: FAT cluster size not set\n");
600 if ((unsigned int)mydata->clust_size * mydata->sect_size >
602 printf("Error: FAT cluster size too big (cs=%u, max=%u)\n",
603 (unsigned int)mydata->clust_size * mydata->sect_size,
608 if (mydata->fatsize == 32) {
609 mydata->data_begin = mydata->rootdir_sect -
610 (mydata->clust_size * 2);
611 mydata->root_cluster = bs.root_cluster;
613 mydata->rootdir_size = ((bs.dir_entries[1] * (int)256 +
617 mydata->data_begin = mydata->rootdir_sect +
618 mydata->rootdir_size -
619 (mydata->clust_size * 2);
622 * The root directory is not cluster-aligned and may be on a
623 * "negative" cluster, this will be handled specially in
624 * fat_next_cluster().
626 mydata->root_cluster = 0;
629 mydata->fatbufnum = -1;
630 mydata->fat_dirty = 0;
631 mydata->fatbuf = malloc_cache_aligned(FATBUFSIZE);
632 if (mydata->fatbuf == NULL) {
633 debug("Error: allocating memory\n");
637 debug("FAT%d, fat_sect: %d, fatlength: %d\n",
638 mydata->fatsize, mydata->fat_sect, mydata->fatlength);
639 debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n"
640 "Data begins at: %d\n",
641 mydata->root_cluster,
642 mydata->rootdir_sect,
643 mydata->rootdir_sect * mydata->sect_size, mydata->data_begin);
644 debug("Sector size: %d, cluster size: %d\n", mydata->sect_size,
651 * struct fat_itr - directory iterator, to simplify filesystem traversal
653 * Implements an iterator pattern to traverse directory tables,
654 * transparently handling directory tables split across multiple
655 * clusters, and the difference between FAT12/FAT16 root directory
656 * (contiguous) and subdirectories + FAT32 root (chained).
662 * for (fat_itr_root(&itr, fsdata); fat_itr_next(&itr); ) {
663 * // to traverse down to a subdirectory pointed to by
664 * // current iterator position:
665 * fat_itr_child(&itr, &itr);
668 * For a more complete example, see fat_itr_resolve().
672 * @fsdata: filesystem parameters
676 * @start_clust: first cluster
678 unsigned int start_clust;
680 * @clust: current cluster
684 * @next_clust: next cluster if remaining == 0
686 unsigned int next_clust;
688 * @last_cluster: set if last cluster of directory reached
692 * @is_root: is iterator at root directory
696 * @remaining: remaining directory entries in current cluster
700 * @dent: current directory entry
704 * @dent_rem: remaining entries after long name start
708 * @dent_clust: cluster of long name start
710 unsigned int dent_clust;
712 * @dent_start: first directory entry for long name
714 dir_entry *dent_start;
716 * @l_name: long name of current directory entry
718 char l_name[VFAT_MAXLEN_BYTES];
720 * @s_name: short 8.3 name of current directory entry
724 * @name: l_name if there is one, else s_name
728 * @block: buffer for current cluster
730 u8 block[MAX_CLUSTSIZE] __aligned(ARCH_DMA_MINALIGN);
733 static int fat_itr_isdir(fat_itr *itr);
736 * fat_itr_root() - initialize an iterator to start at the root
739 * @itr: iterator to initialize
740 * @fsdata: filesystem data for the partition
741 * @return 0 on success, else -errno
743 static int fat_itr_root(fat_itr *itr, fsdata *fsdata)
745 if (get_fs_info(fsdata))
748 itr->fsdata = fsdata;
749 itr->start_clust = fsdata->root_cluster;
750 itr->clust = fsdata->root_cluster;
751 itr->next_clust = fsdata->root_cluster;
754 itr->last_cluster = 0;
761 * fat_itr_child() - initialize an iterator to descend into a sub-
764 * Initializes 'itr' to iterate the contents of the directory at
765 * the current cursor position of 'parent'. It is an error to
766 * call this if the current cursor of 'parent' is pointing at a
769 * Note that 'itr' and 'parent' can be the same pointer if you do
770 * not need to preserve 'parent' after this call, which is useful
771 * for traversing directory structure to resolve a file/directory.
773 * @itr: iterator to initialize
774 * @parent: the iterator pointing at a directory entry in the
775 * parent directory of the directory to iterate
777 static void fat_itr_child(fat_itr *itr, fat_itr *parent)
779 fsdata *mydata = parent->fsdata; /* for silly macros */
780 unsigned clustnum = START(parent->dent);
782 assert(fat_itr_isdir(parent));
784 itr->fsdata = parent->fsdata;
785 itr->start_clust = clustnum;
787 itr->clust = clustnum;
788 itr->next_clust = clustnum;
791 itr->clust = parent->fsdata->root_cluster;
792 itr->next_clust = parent->fsdata->root_cluster;
793 itr->start_clust = parent->fsdata->root_cluster;
798 itr->last_cluster = 0;
802 * fat_next_cluster() - load next FAT cluster
804 * The function is used when iterating through directories. It loads the
805 * next cluster with directory entries
807 * @itr: directory iterator
808 * @nbytes: number of bytes read, 0 on error
809 * Return: first directory entry, NULL on error
811 void *fat_next_cluster(fat_itr *itr, unsigned int *nbytes)
817 /* have we reached the end? */
818 if (itr->last_cluster)
821 if (itr->is_root && itr->fsdata->fatsize != 32) {
823 * The root directory is located before the data area and
824 * cannot be indexed using the regular unsigned cluster
825 * numbers (it may start at a "negative" cluster or not at a
826 * cluster boundary at all), so consider itr->next_clust to be
827 * a offset in cluster-sized units from the start of rootdir.
829 unsigned sect_offset = itr->next_clust * itr->fsdata->clust_size;
830 unsigned remaining_sects = itr->fsdata->rootdir_size - sect_offset;
831 sect = itr->fsdata->rootdir_sect + sect_offset;
832 /* do not read past the end of rootdir */
833 read_size = min_t(u32, itr->fsdata->clust_size,
836 sect = clust_to_sect(itr->fsdata, itr->next_clust);
837 read_size = itr->fsdata->clust_size;
840 log_debug("FAT read(sect=%d), clust_size=%d, read_size=%u\n",
841 sect, itr->fsdata->clust_size, read_size);
844 * NOTE: do_fat_read_at() had complicated logic to deal w/
845 * vfat names that span multiple clusters in the fat16 case,
846 * which get_dentfromdir() probably also needed (and was
847 * missing). And not entirely sure what fat32 didn't have
848 * the same issue.. We solve that by only caring about one
849 * dent at a time and iteratively constructing the vfat long
852 ret = disk_read(sect, read_size, itr->block);
854 debug("Error: reading block\n");
858 *nbytes = read_size * itr->fsdata->sect_size;
859 itr->clust = itr->next_clust;
860 if (itr->is_root && itr->fsdata->fatsize != 32) {
862 if (itr->next_clust * itr->fsdata->clust_size >=
863 itr->fsdata->rootdir_size) {
864 debug("nextclust: 0x%x\n", itr->next_clust);
865 itr->last_cluster = 1;
868 itr->next_clust = get_fatent(itr->fsdata, itr->next_clust);
869 if (CHECK_CLUST(itr->next_clust, itr->fsdata->fatsize)) {
870 debug("nextclust: 0x%x\n", itr->next_clust);
871 itr->last_cluster = 1;
878 static dir_entry *next_dent(fat_itr *itr)
880 if (itr->remaining == 0) {
882 struct dir_entry *dent = fat_next_cluster(itr, &nbytes);
884 /* have we reached the last cluster? */
886 /* a sign for no more entries left */
891 itr->remaining = nbytes / sizeof(dir_entry) - 1;
898 /* have we reached the last valid entry? */
899 if (itr->dent->nameext.name[0] == 0)
905 static dir_entry *extract_vfat_name(fat_itr *itr)
907 struct dir_entry *dent = itr->dent;
908 int seqn = itr->dent->nameext.name[0] & ~LAST_LONG_ENTRY_MASK;
909 u8 chksum, alias_checksum = ((dir_slot *)dent)->alias_checksum;
916 slot2str((dir_slot *)dent, buf, &idx);
918 if (n + idx >= sizeof(itr->l_name))
921 /* shift accumulated long-name up and copy new part in: */
922 memmove(itr->l_name + idx, itr->l_name, n);
923 memcpy(itr->l_name, buf, idx);
926 dent = next_dent(itr);
932 * We are now at the short file name entry.
933 * If it is marked as deleted, just skip it.
935 if (dent->nameext.name[0] == DELETED_FLAG ||
936 dent->nameext.name[0] == aRING)
939 itr->l_name[n] = '\0';
941 chksum = mkcksum(&dent->nameext);
943 /* checksum mismatch could mean deleted file, etc.. skip it: */
944 if (chksum != alias_checksum) {
945 debug("** chksum=%x, alias_checksum=%x, l_name=%s, s_name=%8s.%3s\n",
946 chksum, alias_checksum, itr->l_name, dent->nameext.name,
955 * fat_itr_next() - step to the next entry in a directory
957 * Must be called once on a new iterator before the cursor is valid.
959 * @itr: the iterator to iterate
960 * @return boolean, 1 if success or 0 if no more entries in the
963 static int fat_itr_next(fat_itr *itr)
970 * One logical directory entry consist of following slots:
972 * dent[N - N]: LFN[N - 1] N|0x40 ATTR_VFAT
974 * dent[N - 2]: LFN[1] 2 ATTR_VFAT
975 * dent[N - 1]: LFN[0] 1 ATTR_VFAT
976 * dent[N]: SFN ATTR_ARCH
980 dent = next_dent(itr);
982 itr->dent_start = NULL;
985 itr->dent_rem = itr->remaining;
986 itr->dent_start = itr->dent;
987 itr->dent_clust = itr->clust;
988 if (dent->nameext.name[0] == DELETED_FLAG)
991 if (dent->attr & ATTR_VOLUME) {
992 if ((dent->attr & ATTR_VFAT) == ATTR_VFAT &&
993 (dent->nameext.name[0] & LAST_LONG_ENTRY_MASK)) {
995 dent = extract_vfat_name(itr);
997 * If succeeded, dent has a valid short file
998 * name entry for the current entry.
999 * If failed, itr points to a current bogus
1000 * entry. So after fetching a next one,
1001 * it may have a short file name entry
1002 * for this bogus entry so that we can still
1003 * check for a short name.
1007 itr->name = itr->l_name;
1010 /* Volume label or VFAT entry, skip */
1015 /* short file name */
1019 get_name(dent, itr->s_name);
1021 itr->name = itr->s_name;
1027 * fat_itr_isdir() - is current cursor position pointing to a directory
1029 * @itr: the iterator
1030 * @return true if cursor is at a directory
1032 static int fat_itr_isdir(fat_itr *itr)
1034 return !!(itr->dent->attr & ATTR_DIR);
1041 #define TYPE_FILE 0x1
1042 #define TYPE_DIR 0x2
1043 #define TYPE_ANY (TYPE_FILE | TYPE_DIR)
1046 * fat_itr_resolve() - traverse directory structure to resolve the
1049 * Traverse directory structure to the requested path. If the specified
1050 * path is to a directory, this will descend into the directory and
1051 * leave it iterator at the start of the directory. If the path is to a
1052 * file, it will leave the iterator in the parent directory with current
1053 * cursor at file's entry in the directory.
1055 * @itr: iterator initialized to root
1056 * @path: the requested path
1057 * @type: bitmask of allowable file types
1058 * @return 0 on success or -errno
1060 static int fat_itr_resolve(fat_itr *itr, const char *path, unsigned type)
1064 /* chomp any extra leading slashes: */
1065 while (path[0] && ISDIRDELIM(path[0]))
1068 /* are we at the end? */
1069 if (strlen(path) == 0) {
1070 if (!(type & TYPE_DIR))
1075 /* find length of next path entry: */
1077 while (next[0] && !ISDIRDELIM(next[0]))
1081 /* root dir doesn't have "." nor ".." */
1082 if ((((next - path) == 1) && !strncmp(path, ".", 1)) ||
1083 (((next - path) == 2) && !strncmp(path, "..", 2))) {
1084 /* point back to itself */
1085 itr->clust = itr->fsdata->root_cluster;
1086 itr->next_clust = itr->fsdata->root_cluster;
1087 itr->start_clust = itr->fsdata->root_cluster;
1090 itr->last_cluster = 0;
1093 if (type & TYPE_DIR)
1099 return fat_itr_resolve(itr, next, type);
1103 while (fat_itr_next(itr)) {
1105 unsigned n = max(strlen(itr->name), (size_t)(next - path));
1107 /* check both long and short name: */
1108 if (!strncasecmp(path, itr->name, n))
1110 else if (itr->name != itr->s_name &&
1111 !strncasecmp(path, itr->s_name, n))
1117 if (fat_itr_isdir(itr)) {
1118 /* recurse into directory: */
1119 fat_itr_child(itr, itr);
1120 return fat_itr_resolve(itr, next, type);
1121 } else if (next[0]) {
1123 * If next is not empty then we have a case
1124 * like: /path/to/realfile/nonsense
1126 debug("bad trailing path: %s\n", next);
1128 } else if (!(type & TYPE_FILE)) {
1138 int file_fat_detectfs(void)
1141 volume_info volinfo;
1145 if (cur_dev == NULL) {
1146 printf("No current device\n");
1150 if (IS_ENABLED(CONFIG_HAVE_BLOCK_DEVICE)) {
1151 printf("Interface: %s\n", blk_get_if_type_name(cur_dev->if_type));
1152 printf(" Device %d: ", cur_dev->devnum);
1156 if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
1157 printf("\nNo valid FAT fs found\n");
1161 memcpy(vol_label, volinfo.volume_label, 11);
1162 vol_label[11] = '\0';
1163 volinfo.fs_type[5] = '\0';
1165 printf("Filesystem: %s \"%s\"\n", volinfo.fs_type, vol_label);
1170 int fat_exists(const char *filename)
1176 itr = malloc_cache_aligned(sizeof(fat_itr));
1179 ret = fat_itr_root(itr, &fsdata);
1183 ret = fat_itr_resolve(itr, filename, TYPE_ANY);
1184 free(fsdata.fatbuf);
1191 * fat2rtc() - convert FAT time stamp to RTC file stamp
1195 * @tm: RTC time stamp
1197 static void __maybe_unused fat2rtc(u16 date, u16 time, struct rtc_time *tm)
1199 tm->tm_mday = date & 0x1f;
1200 tm->tm_mon = (date & 0x1e0) >> 4;
1201 tm->tm_year = (date >> 9) + 1980;
1203 tm->tm_sec = (time & 0x1f) << 1;
1204 tm->tm_min = (time & 0x7e0) >> 5;
1205 tm->tm_hour = time >> 11;
1207 rtc_calc_weekday(tm);
1212 int fat_size(const char *filename, loff_t *size)
1218 itr = malloc_cache_aligned(sizeof(fat_itr));
1221 ret = fat_itr_root(itr, &fsdata);
1225 ret = fat_itr_resolve(itr, filename, TYPE_FILE);
1228 * Directories don't have size, but fs_size() is not
1229 * expected to fail if passed a directory path:
1231 free(fsdata.fatbuf);
1232 ret = fat_itr_root(itr, &fsdata);
1235 ret = fat_itr_resolve(itr, filename, TYPE_DIR);
1241 *size = FAT2CPU32(itr->dent->size);
1243 free(fsdata.fatbuf);
1249 int file_fat_read_at(const char *filename, loff_t pos, void *buffer,
1250 loff_t maxsize, loff_t *actread)
1256 itr = malloc_cache_aligned(sizeof(fat_itr));
1259 ret = fat_itr_root(itr, &fsdata);
1263 ret = fat_itr_resolve(itr, filename, TYPE_FILE);
1267 debug("reading %s at pos %llu\n", filename, pos);
1269 /* For saving default max clustersize memory allocated to malloc pool */
1270 dir_entry *dentptr = itr->dent;
1272 ret = get_contents(&fsdata, dentptr, pos, buffer, maxsize, actread);
1275 free(fsdata.fatbuf);
1281 int file_fat_read(const char *filename, void *buffer, int maxsize)
1286 ret = file_fat_read_at(filename, 0, buffer, maxsize, &actread);
1293 int fat_read_file(const char *filename, void *buf, loff_t offset, loff_t len,
1298 ret = file_fat_read_at(filename, offset, buf, len, actread);
1300 printf("** Unable to read file %s **\n", filename);
1306 struct fs_dir_stream parent;
1307 struct fs_dirent dirent;
1312 int fat_opendir(const char *filename, struct fs_dir_stream **dirsp)
1317 dir = malloc_cache_aligned(sizeof(*dir));
1320 memset(dir, 0, sizeof(*dir));
1322 ret = fat_itr_root(&dir->itr, &dir->fsdata);
1326 ret = fat_itr_resolve(&dir->itr, filename, TYPE_DIR);
1328 goto fail_free_both;
1330 *dirsp = (struct fs_dir_stream *)dir;
1334 free(dir->fsdata.fatbuf);
1340 int fat_readdir(struct fs_dir_stream *dirs, struct fs_dirent **dentp)
1342 fat_dir *dir = (fat_dir *)dirs;
1343 struct fs_dirent *dent = &dir->dirent;
1345 if (!fat_itr_next(&dir->itr))
1348 memset(dent, 0, sizeof(*dent));
1349 strcpy(dent->name, dir->itr.name);
1350 if (CONFIG_IS_ENABLED(EFI_LOADER)) {
1351 dent->attr = dir->itr.dent->attr;
1352 fat2rtc(le16_to_cpu(dir->itr.dent->cdate),
1353 le16_to_cpu(dir->itr.dent->ctime), &dent->create_time);
1354 fat2rtc(le16_to_cpu(dir->itr.dent->date),
1355 le16_to_cpu(dir->itr.dent->time), &dent->change_time);
1356 fat2rtc(le16_to_cpu(dir->itr.dent->adate),
1357 0, &dent->access_time);
1359 if (fat_itr_isdir(&dir->itr)) {
1360 dent->type = FS_DT_DIR;
1362 dent->type = FS_DT_REG;
1363 dent->size = FAT2CPU32(dir->itr.dent->size);
1371 void fat_closedir(struct fs_dir_stream *dirs)
1373 fat_dir *dir = (fat_dir *)dirs;
1374 free(dir->fsdata.fatbuf);
1378 void fat_close(void)
1382 int fat_uuid(char *uuid_str)
1385 volume_info volinfo;
1390 ret = read_bootsectandvi(&bs, &volinfo, &fatsize);
1394 id = volinfo.volume_id;
1395 sprintf(uuid_str, "%02X%02X-%02X%02X", id[3], id[2], id[1], id[0]);