1 // SPDX-License-Identifier: GPL-2.0+
5 * R/W (V)FAT 12/16/32 filesystem implementation by Donggeun Kim
8 #define LOG_CATEGORY LOGC_FS
18 #include <asm/byteorder.h>
19 #include <asm/cache.h>
20 #include <dm/uclass.h>
21 #include <linux/ctype.h>
22 #include <linux/math64.h>
25 static dir_entry *find_directory_entry(fat_itr *itr, char *filename);
26 static int new_dir_table(fat_itr *itr);
28 /* Characters that may only be used in long file names */
29 static const char LONG_ONLY_CHARS[] = "+,;=[]";
31 /* Combined size of the name and ext fields in the directory entry */
32 #define SHORT_NAME_SIZE 11
35 * str2fat() - convert string to valid FAT name characters
37 * Stop when reaching end of @src or a period.
39 * Replace characters that may only be used in long names by underscores.
40 * Convert lower case characters to upper case.
42 * To avoid assumptions about the code page we do not use characters
43 * above 0x7f for the short name.
45 * @dest: destination buffer
47 * @length: size of destination buffer
48 * Return: number of bytes in destination buffer
50 static int str2fat(char *dest, char *src, int length)
54 for (i = 0; i < length; ++src) {
61 if (strchr(LONG_ONLY_CHARS, c) || c > 0x7f)
63 else if (c >= 'a' && c <= 'z')
72 * fat_move_to_cluster() - position to first directory entry in cluster
74 * @itr: directory iterator
76 * Return: 0 for success, -EIO on error
78 static int fat_move_to_cluster(fat_itr *itr, unsigned int cluster)
82 /* position to the start of the directory */
83 itr->next_clust = cluster;
84 itr->last_cluster = 0;
85 if (!fat_next_cluster(itr, &nbytes))
87 itr->dent = (dir_entry *)itr->block;
88 itr->remaining = nbytes / sizeof(dir_entry) - 1;
93 * set_name() - set short name in directory entry
95 * The function determines if the @filename is a valid short name.
96 * In this case no long name is needed.
98 * If a long name is needed, a short name is constructed.
100 * @itr: directory iterator
101 * @filename: long file name
102 * @shortname: buffer of 11 bytes to receive chosen short name and extension
103 * Return: number of directory entries needed, negative on error
105 static int set_name(fat_itr *itr, const char *filename, char *shortname)
113 struct nameext dirent;
118 /* Initialize buffer */
119 memset(&dirent, ' ', sizeof(dirent));
121 /* Convert filename to upper case short name */
122 period = strrchr(filename, '.');
123 pos = (char *)filename;
129 str2fat(dirent.ext, period + 1, sizeof(dirent.ext));
130 period_location = str2fat(dirent.name, pos, sizeof(dirent.name));
131 if (period_location < 0)
132 return period_location;
133 if (*dirent.name == ' ')
135 /* Substitute character 0xe5 signaling deletetion by character 0x05 */
136 if (*dirent.name == DELETED_FLAG)
137 *dirent.name = aRING;
139 /* If filename and short name are the same, quit. */
140 sprintf(buf, "%.*s.%.3s", period_location, dirent.name, dirent.ext);
141 if (!strcmp(buf, filename)) {
144 } else if (!strcasecmp(buf, filename)) {
148 /* Construct an indexed short name */
149 for (i = 1; i < 0x200000; ++i) {
154 /* To speed up the search use random numbers */
159 j = 10 + (rand() >> j);
161 sprintf(buf, "~%d", j);
162 suffix_len = strlen(buf);
163 suffix_start = 8 - suffix_len;
164 if (suffix_start > period_location)
165 suffix_start = period_location;
166 memcpy(dirent.name + suffix_start, buf, suffix_len);
167 if (*dirent.ext != ' ')
168 sprintf(buf, "%.*s.%.3s", suffix_start + suffix_len,
169 dirent.name, dirent.ext);
171 sprintf(buf, "%.*s", suffix_start + suffix_len,
173 debug("generated short name: %s\n", buf);
175 /* Check that the short name does not exist yet. */
176 ret = fat_move_to_cluster(itr, itr->start_clust);
179 if (find_directory_entry(itr, buf))
186 debug("chosen short name: %s\n", buf);
187 /* Each long name directory entry takes 13 characters. */
188 ret = (strlen(filename) + 25) / 13;
190 memcpy(shortname, &dirent, SHORT_NAME_SIZE);
194 static int total_sector;
195 static int disk_write(__u32 block, __u32 nr_blocks, void *buf)
202 if (cur_part_info.start + block + nr_blocks >
203 cur_part_info.start + total_sector) {
204 printf("error: overflow occurs\n");
208 ret = blk_dwrite(cur_dev, cur_part_info.start + block, nr_blocks, buf);
209 if (nr_blocks && ret == 0)
216 * Write fat buffer into block device
218 static int flush_dirty_fat_buffer(fsdata *mydata)
220 int getsize = FATBUFBLOCKS;
221 __u32 fatlength = mydata->fatlength;
222 __u8 *bufptr = mydata->fatbuf;
223 __u32 startblock = mydata->fatbufnum * FATBUFBLOCKS;
225 debug("debug: evicting %d, dirty: %d\n", mydata->fatbufnum,
226 (int)mydata->fat_dirty);
228 if ((!mydata->fat_dirty) || (mydata->fatbufnum == -1))
231 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
232 if (startblock + getsize > fatlength)
233 getsize = fatlength - startblock;
235 startblock += mydata->fat_sect;
238 if (disk_write(startblock, getsize, bufptr) < 0) {
239 debug("error: writing FAT blocks\n");
243 if (mydata->fats == 2) {
244 /* Update corresponding second FAT blocks */
245 startblock += mydata->fatlength;
246 if (disk_write(startblock, getsize, bufptr) < 0) {
247 debug("error: writing second FAT blocks\n");
251 mydata->fat_dirty = 0;
257 * fat_find_empty_dentries() - find a sequence of available directory entries
259 * @itr: directory iterator
260 * @count: number of directory entries to find
261 * Return: 0 on success or negative error number
263 static int fat_find_empty_dentries(fat_itr *itr, int count)
265 unsigned int cluster;
271 ret = fat_move_to_cluster(itr, itr->start_clust);
277 log_debug("Not enough directory entries available\n");
280 switch (itr->dent->nameext.name[0]) {
284 /* Remember first deleted directory entry */
285 cluster = itr->clust;
287 remaining = itr->remaining;
300 (!itr->is_root || itr->fsdata->fatsize == 32) &&
305 /* Position back to first directory entry */
306 if (itr->clust != cluster) {
307 ret = fat_move_to_cluster(itr, cluster);
312 itr->remaining = remaining;
317 * Set the file name information from 'name' into 'slotptr',
319 static int str2slot(dir_slot *slotptr, const char *name, int *idx)
323 for (j = 0; j <= 8; j += 2) {
324 if (name[*idx] == 0x00) {
325 slotptr->name0_4[j] = 0;
326 slotptr->name0_4[j + 1] = 0;
330 slotptr->name0_4[j] = name[*idx];
334 for (j = 0; j <= 10; j += 2) {
335 if (name[*idx] == 0x00) {
336 slotptr->name5_10[j] = 0;
337 slotptr->name5_10[j + 1] = 0;
341 slotptr->name5_10[j] = name[*idx];
345 for (j = 0; j <= 2; j += 2) {
346 if (name[*idx] == 0x00) {
347 slotptr->name11_12[j] = 0;
348 slotptr->name11_12[j + 1] = 0;
352 slotptr->name11_12[j] = name[*idx];
357 if (name[*idx] == 0x00)
361 /* Not used characters are filled with 0xff 0xff */
363 for (; end_idx < 5; end_idx++) {
364 slotptr->name0_4[end_idx * 2] = 0xff;
365 slotptr->name0_4[end_idx * 2 + 1] = 0xff;
370 for (; end_idx < 6; end_idx++) {
371 slotptr->name5_10[end_idx * 2] = 0xff;
372 slotptr->name5_10[end_idx * 2 + 1] = 0xff;
377 for (; end_idx < 2; end_idx++) {
378 slotptr->name11_12[end_idx * 2] = 0xff;
379 slotptr->name11_12[end_idx * 2 + 1] = 0xff;
385 static int flush_dir(fat_itr *itr);
388 * fill_dir_slot() - fill directory entries for long name
390 * @itr: directory iterator
392 * @shortname: short name
393 * Return: 0 for success, -errno otherwise
396 fill_dir_slot(fat_itr *itr, const char *l_name, const char *shortname)
398 __u8 temp_dir_slot_buffer[MAX_LFN_SLOT * sizeof(dir_slot)];
399 dir_slot *slotptr = (dir_slot *)temp_dir_slot_buffer;
400 __u8 counter = 0, checksum;
403 /* Get short file name checksum value */
404 checksum = mkcksum((void *)shortname);
407 memset(slotptr, 0x00, sizeof(dir_slot));
408 ret = str2slot(slotptr, l_name, &idx);
409 slotptr->id = ++counter;
410 slotptr->attr = ATTR_VFAT;
411 slotptr->alias_checksum = checksum;
416 slotptr->id |= LAST_LONG_ENTRY_MASK;
418 while (counter >= 1) {
419 memcpy(itr->dent, slotptr, sizeof(dir_slot));
423 if (!itr->remaining) {
424 /* Write directory table to device */
425 ret = flush_dir(itr);
439 * Set the entry at index 'entry' in a FAT (12/16/32) table.
441 static int set_fatent_value(fsdata *mydata, __u32 entry, __u32 entry_value)
443 __u32 bufnum, offset, off16;
446 switch (mydata->fatsize) {
448 bufnum = entry / FAT32BUFSIZE;
449 offset = entry - bufnum * FAT32BUFSIZE;
452 bufnum = entry / FAT16BUFSIZE;
453 offset = entry - bufnum * FAT16BUFSIZE;
456 bufnum = entry / FAT12BUFSIZE;
457 offset = entry - bufnum * FAT12BUFSIZE;
460 /* Unsupported FAT size */
464 /* Read a new block of FAT entries into the cache. */
465 if (bufnum != mydata->fatbufnum) {
466 int getsize = FATBUFBLOCKS;
467 __u8 *bufptr = mydata->fatbuf;
468 __u32 fatlength = mydata->fatlength;
469 __u32 startblock = bufnum * FATBUFBLOCKS;
471 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
472 if (startblock + getsize > fatlength)
473 getsize = fatlength - startblock;
475 if (flush_dirty_fat_buffer(mydata) < 0)
478 startblock += mydata->fat_sect;
480 if (disk_read(startblock, getsize, bufptr) < 0) {
481 debug("Error reading FAT blocks\n");
484 mydata->fatbufnum = bufnum;
488 mydata->fat_dirty = 1;
490 /* Set the actual entry */
491 switch (mydata->fatsize) {
493 ((__u32 *) mydata->fatbuf)[offset] = cpu_to_le32(entry_value);
496 ((__u16 *) mydata->fatbuf)[offset] = cpu_to_le16(entry_value);
499 off16 = (offset * 3) / 4;
501 switch (offset & 0x3) {
503 val1 = cpu_to_le16(entry_value) & 0xfff;
504 ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff;
505 ((__u16 *)mydata->fatbuf)[off16] |= val1;
508 val1 = cpu_to_le16(entry_value) & 0xf;
509 val2 = (cpu_to_le16(entry_value) >> 4) & 0xff;
511 ((__u16 *)mydata->fatbuf)[off16] &= ~0xf000;
512 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 12);
514 ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xff;
515 ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
518 val1 = cpu_to_le16(entry_value) & 0xff;
519 val2 = (cpu_to_le16(entry_value) >> 8) & 0xf;
521 ((__u16 *)mydata->fatbuf)[off16] &= ~0xff00;
522 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 8);
524 ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xf;
525 ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
528 val1 = cpu_to_le16(entry_value) & 0xfff;
529 ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff0;
530 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 4);
545 * Determine the next free cluster after 'entry' in a FAT (12/16/32) table
546 * and link it to 'entry'. EOC marker is not set on returned entry.
548 static __u32 determine_fatent(fsdata *mydata, __u32 entry)
550 __u32 next_fat, next_entry = entry + 1;
553 next_fat = get_fatent(mydata, next_entry);
555 /* found free entry, link to entry */
556 set_fatent_value(mydata, entry, next_entry);
561 debug("FAT%d: entry: %08x, entry_value: %04x\n",
562 mydata->fatsize, entry, next_entry);
568 * set_sectors() - write data to sectors
570 * Write 'size' bytes from 'buffer' into the specified sector.
572 * @mydata: data to be written
573 * @startsect: sector to be written to
574 * @buffer: data to be written
575 * @size: bytes to be written (but not more than the size of a cluster)
576 * Return: 0 on success, -1 otherwise
579 set_sectors(fsdata *mydata, u32 startsect, u8 *buffer, u32 size)
583 debug("startsect: %d\n", startsect);
585 if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
586 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
588 debug("FAT: Misaligned buffer address (%p)\n", buffer);
590 while (size >= mydata->sect_size) {
591 memcpy(tmpbuf, buffer, mydata->sect_size);
592 ret = disk_write(startsect++, 1, tmpbuf);
594 debug("Error writing data (got %d)\n", ret);
598 buffer += mydata->sect_size;
599 size -= mydata->sect_size;
601 } else if (size >= mydata->sect_size) {
604 nsects = size / mydata->sect_size;
605 ret = disk_write(startsect, nsects, buffer);
607 debug("Error writing data (got %d)\n", ret);
612 buffer += nsects * mydata->sect_size;
613 size -= nsects * mydata->sect_size;
617 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
618 /* Do not leak content of stack */
619 memset(tmpbuf, 0, mydata->sect_size);
620 memcpy(tmpbuf, buffer, size);
621 ret = disk_write(startsect, 1, tmpbuf);
623 debug("Error writing data (got %d)\n", ret);
632 * set_cluster() - write data to cluster
634 * Write 'size' bytes from 'buffer' into the specified cluster.
636 * @mydata: data to be written
637 * @clustnum: cluster to be written to
638 * @buffer: data to be written
639 * @size: bytes to be written (but not more than the size of a cluster)
640 * Return: 0 on success, -1 otherwise
643 set_cluster(fsdata *mydata, u32 clustnum, u8 *buffer, u32 size)
645 return set_sectors(mydata, clust_to_sect(mydata, clustnum),
650 * flush_dir() - flush directory
652 * @itr: directory iterator
653 * Return: 0 for success, -EIO on error
655 static int flush_dir(fat_itr *itr)
657 fsdata *mydata = itr->fsdata;
658 u32 startsect, sect_offset, nsects;
661 if (!itr->is_root || mydata->fatsize == 32) {
662 ret = set_cluster(mydata, itr->clust, itr->block,
663 mydata->clust_size * mydata->sect_size);
667 sect_offset = itr->clust * mydata->clust_size;
668 startsect = mydata->rootdir_sect + sect_offset;
669 /* do not write past the end of rootdir */
670 nsects = min_t(u32, mydata->clust_size,
671 mydata->rootdir_size - sect_offset);
673 ret = set_sectors(mydata, startsect, itr->block,
674 nsects * mydata->sect_size);
677 log_err("Error: writing directory entry\n");
684 * Read and modify data on existing and consecutive cluster blocks
687 get_set_cluster(fsdata *mydata, __u32 clustnum, loff_t pos, __u8 *buffer,
688 loff_t size, loff_t *gotsize)
690 static u8 *tmpbuf_cluster;
691 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
693 loff_t clustcount, wsize;
700 if (!tmpbuf_cluster) {
701 tmpbuf_cluster = memalign(ARCH_DMA_MINALIGN, MAX_CLUSTSIZE);
706 assert(pos < bytesperclust);
707 startsect = clust_to_sect(mydata, clustnum);
709 debug("clustnum: %d, startsect: %d, pos: %lld\n",
710 clustnum, startsect, pos);
712 /* partial write at beginning */
714 wsize = min(bytesperclust - pos, size);
715 ret = disk_read(startsect, mydata->clust_size, tmpbuf_cluster);
716 if (ret != mydata->clust_size) {
717 debug("Error reading data (got %d)\n", ret);
721 memcpy(tmpbuf_cluster + pos, buffer, wsize);
722 ret = disk_write(startsect, mydata->clust_size, tmpbuf_cluster);
723 if (ret != mydata->clust_size) {
724 debug("Error writing data (got %d)\n", ret);
732 startsect += mydata->clust_size;
738 /* full-cluster write */
739 if (size >= bytesperclust) {
740 clustcount = lldiv(size, bytesperclust);
742 if (!((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1))) {
743 wsize = clustcount * bytesperclust;
744 ret = disk_write(startsect,
745 clustcount * mydata->clust_size,
747 if (ret != clustcount * mydata->clust_size) {
748 debug("Error writing data (got %d)\n", ret);
756 startsect += clustcount * mydata->clust_size;
758 for (i = 0; i < clustcount; i++) {
759 memcpy(tmpbuf_cluster, buffer, bytesperclust);
760 ret = disk_write(startsect,
763 if (ret != mydata->clust_size) {
764 debug("Error writing data (got %d)\n",
769 size -= bytesperclust;
770 buffer += bytesperclust;
771 *gotsize += bytesperclust;
773 startsect += mydata->clust_size;
778 /* partial write at end */
781 ret = disk_read(startsect, mydata->clust_size, tmpbuf_cluster);
782 if (ret != mydata->clust_size) {
783 debug("Error reading data (got %d)\n", ret);
786 memcpy(tmpbuf_cluster, buffer, wsize);
787 ret = disk_write(startsect, mydata->clust_size, tmpbuf_cluster);
788 if (ret != mydata->clust_size) {
789 debug("Error writing data (got %d)\n", ret);
803 * Find the first empty cluster
805 static int find_empty_cluster(fsdata *mydata)
807 __u32 fat_val, entry = 3;
810 fat_val = get_fatent(mydata, entry);
820 * new_dir_table() - allocate a cluster for additional directory entries
822 * @itr: directory iterator
823 * Return: 0 on success, -EIO otherwise
825 static int new_dir_table(fat_itr *itr)
827 fsdata *mydata = itr->fsdata;
828 int dir_newclust = 0;
829 int dir_oldclust = itr->clust;
830 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
832 dir_newclust = find_empty_cluster(mydata);
835 * Flush before updating FAT to ensure valid directory structure
836 * in case of failure.
838 itr->clust = dir_newclust;
839 itr->next_clust = dir_newclust;
840 memset(itr->block, 0x00, bytesperclust);
844 set_fatent_value(mydata, dir_oldclust, dir_newclust);
845 if (mydata->fatsize == 32)
846 set_fatent_value(mydata, dir_newclust, 0xffffff8);
847 else if (mydata->fatsize == 16)
848 set_fatent_value(mydata, dir_newclust, 0xfff8);
849 else if (mydata->fatsize == 12)
850 set_fatent_value(mydata, dir_newclust, 0xff8);
852 if (flush_dirty_fat_buffer(mydata) < 0)
855 itr->dent = (dir_entry *)itr->block;
856 itr->last_cluster = 1;
857 itr->remaining = bytesperclust / sizeof(dir_entry) - 1;
863 * Set empty cluster from 'entry' to the end of a file
865 static int clear_fatent(fsdata *mydata, __u32 entry)
869 while (!CHECK_CLUST(entry, mydata->fatsize)) {
870 fat_val = get_fatent(mydata, entry);
872 set_fatent_value(mydata, entry, 0);
879 /* Flush fat buffer */
880 if (flush_dirty_fat_buffer(mydata) < 0)
887 * Set start cluster in directory entry
889 static void set_start_cluster(const fsdata *mydata, dir_entry *dentptr,
892 if (mydata->fatsize == 32)
894 cpu_to_le16((start_cluster & 0xffff0000) >> 16);
895 dentptr->start = cpu_to_le16(start_cluster & 0xffff);
899 * Check whether adding a file makes the file system to
900 * exceed the size of the block device
901 * Return -1 when overflow occurs, otherwise return 0
903 static int check_overflow(fsdata *mydata, __u32 clustnum, loff_t size)
905 __u32 startsect, sect_num, offset;
908 startsect = clust_to_sect(mydata, clustnum);
910 startsect = mydata->rootdir_sect;
912 sect_num = div_u64_rem(size, mydata->sect_size, &offset);
917 if (startsect + sect_num > total_sector)
923 * Write at most 'maxsize' bytes from 'buffer' into
924 * the file associated with 'dentptr'
925 * Update the number of bytes written in *gotsize and return 0
926 * or return -1 on fatal errors.
929 set_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos, __u8 *buffer,
930 loff_t maxsize, loff_t *gotsize)
932 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
933 __u32 curclust = START(dentptr);
934 __u32 endclust = 0, newclust = 0;
935 u64 cur_pos, filesize;
936 loff_t offset, actsize, wsize;
939 filesize = pos + maxsize;
941 debug("%llu bytes\n", filesize);
946 if (!CHECK_CLUST(curclust, mydata->fatsize) ||
947 IS_LAST_CLUST(curclust, mydata->fatsize)) {
948 clear_fatent(mydata, curclust);
949 set_start_cluster(mydata, dentptr, 0);
952 debug("curclust: 0x%x\n", curclust);
953 debug("Invalid FAT entry\n");
962 /* go to cluster at pos */
963 cur_pos = bytesperclust;
967 if (IS_LAST_CLUST(curclust, mydata->fatsize))
970 newclust = get_fatent(mydata, curclust);
971 if (!IS_LAST_CLUST(newclust, mydata->fatsize) &&
972 CHECK_CLUST(newclust, mydata->fatsize)) {
973 debug("curclust: 0x%x\n", curclust);
974 debug("Invalid FAT entry\n");
978 cur_pos += bytesperclust;
981 if (IS_LAST_CLUST(curclust, mydata->fatsize)) {
982 assert(pos == cur_pos);
986 assert(pos < cur_pos);
987 cur_pos -= bytesperclust;
990 assert(IS_LAST_CLUST(curclust, mydata->fatsize) ||
991 !CHECK_CLUST(curclust, mydata->fatsize));
994 /* search for allocated consecutive clusters */
995 actsize = bytesperclust;
998 if (filesize <= (cur_pos + actsize))
1001 newclust = get_fatent(mydata, endclust);
1003 if (newclust != endclust + 1)
1005 if (IS_LAST_CLUST(newclust, mydata->fatsize))
1007 if (CHECK_CLUST(newclust, mydata->fatsize)) {
1008 debug("curclust: 0x%x\n", curclust);
1009 debug("Invalid FAT entry\n");
1013 actsize += bytesperclust;
1014 endclust = newclust;
1017 /* overwrite to <curclust..endclust> */
1021 offset = pos - cur_pos;
1022 wsize = min_t(unsigned long long, actsize, filesize - cur_pos);
1025 if (get_set_cluster(mydata, curclust, offset,
1026 buffer, wsize, &actsize)) {
1027 printf("Error get-and-setting cluster\n");
1032 cur_pos += offset + wsize;
1034 if (filesize <= cur_pos)
1037 if (IS_LAST_CLUST(newclust, mydata->fatsize))
1038 /* no more clusters */
1041 curclust = newclust;
1044 if (filesize <= cur_pos) {
1046 newclust = get_fatent(mydata, endclust);
1047 if (!IS_LAST_CLUST(newclust, mydata->fatsize)) {
1048 /* truncate the rest */
1049 clear_fatent(mydata, newclust);
1051 /* Mark end of file in FAT */
1052 if (mydata->fatsize == 12)
1054 else if (mydata->fatsize == 16)
1056 else if (mydata->fatsize == 32)
1057 newclust = 0xfffffff;
1058 set_fatent_value(mydata, endclust, newclust);
1064 curclust = endclust;
1065 filesize -= cur_pos;
1066 assert(!do_div(cur_pos, bytesperclust));
1069 /* allocate and write */
1072 /* Assure that curclust is valid */
1074 curclust = find_empty_cluster(mydata);
1075 set_start_cluster(mydata, dentptr, curclust);
1077 newclust = get_fatent(mydata, curclust);
1079 if (IS_LAST_CLUST(newclust, mydata->fatsize)) {
1080 newclust = determine_fatent(mydata, curclust);
1081 set_fatent_value(mydata, curclust, newclust);
1082 curclust = newclust;
1084 debug("error: something wrong\n");
1089 /* TODO: already partially written */
1090 if (check_overflow(mydata, curclust, filesize)) {
1091 printf("Error: no space left: %llu\n", filesize);
1095 actsize = bytesperclust;
1096 endclust = curclust;
1098 /* search for consecutive clusters */
1099 while (actsize < filesize) {
1100 newclust = determine_fatent(mydata, endclust);
1102 if ((newclust - 1) != endclust)
1103 /* write to <curclust..endclust> */
1106 if (CHECK_CLUST(newclust, mydata->fatsize)) {
1107 debug("newclust: 0x%x\n", newclust);
1108 debug("Invalid FAT entry\n");
1111 endclust = newclust;
1112 actsize += bytesperclust;
1115 /* set remaining bytes */
1117 if (set_cluster(mydata, curclust, buffer, (u32)actsize) != 0) {
1118 debug("error: writing cluster\n");
1121 *gotsize += actsize;
1123 /* Mark end of file in FAT */
1124 if (mydata->fatsize == 12)
1126 else if (mydata->fatsize == 16)
1128 else if (mydata->fatsize == 32)
1129 newclust = 0xfffffff;
1130 set_fatent_value(mydata, endclust, newclust);
1134 if (set_cluster(mydata, curclust, buffer, (u32)actsize) != 0) {
1135 debug("error: writing cluster\n");
1138 *gotsize += actsize;
1139 filesize -= actsize;
1142 if (CHECK_CLUST(newclust, mydata->fatsize)) {
1143 debug("newclust: 0x%x\n", newclust);
1144 debug("Invalid FAT entry\n");
1147 actsize = bytesperclust;
1148 curclust = endclust = newclust;
1155 * dentry_set_time() - set change time
1157 * @dentptr: directory entry
1159 static void dentry_set_time(dir_entry *dentptr)
1161 if (CONFIG_IS_ENABLED(DM_RTC)) {
1162 struct udevice *dev;
1167 uclass_first_device(UCLASS_RTC, &dev);
1170 if (dm_rtc_get(dev, &tm))
1172 if (tm.tm_year < 1980 || tm.tm_year > 2107)
1174 date = (tm.tm_mday & 0x1f) |
1175 ((tm.tm_mon & 0xf) << 5) |
1176 ((tm.tm_year - 1980) << 9);
1177 time = (tm.tm_sec > 1) |
1178 ((tm.tm_min & 0x3f) << 5) |
1180 dentptr->date = date;
1181 dentptr->time = time;
1185 dentptr->date = 0x2821; /* 2000-01-01 */
1190 * fill_dentry() - fill directory entry with shortname
1192 * @mydata: private filesystem parameters
1193 * @dentptr: directory entry
1194 * @shortname: chosen short name
1195 * @start_cluster: first cluster of file
1197 * @attr: file attributes
1199 static void fill_dentry(fsdata *mydata, dir_entry *dentptr,
1200 const char *shortname, __u32 start_cluster, __u32 size, __u8 attr)
1202 memset(dentptr, 0, sizeof(*dentptr));
1204 set_start_cluster(mydata, dentptr, start_cluster);
1205 dentptr->size = cpu_to_le32(size);
1207 dentptr->attr = attr;
1209 /* Set change date */
1210 dentry_set_time(dentptr);
1211 /* Set creation date */
1212 dentptr->cdate = dentptr->date;
1213 dentptr->ctime = dentptr->time;
1215 memcpy(&dentptr->nameext, shortname, SHORT_NAME_SIZE);
1219 * find_directory_entry() - find a directory entry by filename
1221 * @itr: directory iterator
1222 * @filename: name of file to find
1223 * Return: directory entry or NULL
1225 static dir_entry *find_directory_entry(fat_itr *itr, char *filename)
1229 while (fat_itr_next(itr)) {
1230 /* check both long and short name: */
1231 if (!strcasecmp(filename, itr->name))
1233 else if (itr->name != itr->s_name &&
1234 !strcasecmp(filename, itr->s_name))
1240 if (itr->dent->nameext.name[0] == '\0')
1249 static int split_filename(char *filename, char **dirname, char **basename)
1251 char *p, *last_slash, *last_slash_cont;
1256 last_slash_cont = NULL;
1258 if (ISDIRDELIM(*p)) {
1260 last_slash_cont = p;
1261 /* continuous slashes */
1262 while (ISDIRDELIM(*p))
1263 last_slash_cont = p++;
1271 if (last_slash_cont == (filename + strlen(filename) - 1)) {
1272 /* remove trailing slashes */
1277 if (last_slash == filename) {
1278 /* avoid ""(null) directory */
1282 *dirname = filename;
1285 *last_slash_cont = '\0';
1286 filename = last_slash_cont + 1;
1288 *dirname = "/"; /* root by default */
1292 * The FAT32 File System Specification v1.03 requires leading and
1293 * trailing spaces as well as trailing periods to be ignored.
1295 for (; *filename == ' '; ++filename)
1298 /* Keep special entries '.' and '..' */
1299 if (filename[0] == '.' &&
1300 (!filename[1] || (filename[1] == '.' && !filename[2])))
1303 /* Remove trailing periods and spaces */
1304 for (p = filename + strlen(filename) - 1; p >= filename; --p) {
1316 *basename = filename;
1322 * normalize_longname() - check long file name and convert to lower case
1324 * We assume here that the FAT file system is using an 8bit code page.
1325 * Linux typically uses CP437, EDK2 assumes CP1250.
1327 * @l_filename: preallocated buffer receiving the normalized name
1328 * @filename: filename to normalize
1329 * Return: 0 on success, -1 on failure
1331 static int normalize_longname(char *l_filename, const char *filename)
1333 const char *p, illegal[] = "<>:\"/\\|?*";
1336 len = strlen(filename);
1337 if (!len || len >= VFAT_MAXLEN_BYTES || filename[len - 1] == '.')
1340 for (p = filename; *p; ++p) {
1341 if ((unsigned char)*p < 0x20)
1343 if (strchr(illegal, *p))
1347 strcpy(l_filename, filename);
1348 downcase(l_filename, VFAT_MAXLEN_BYTES);
1353 int file_fat_write_at(const char *filename, loff_t pos, void *buffer,
1354 loff_t size, loff_t *actwrite)
1357 fsdata datablock = { .fatbuf = NULL, };
1358 fsdata *mydata = &datablock;
1359 fat_itr *itr = NULL;
1361 char *filename_copy, *parent, *basename;
1362 char l_filename[VFAT_MAXLEN_BYTES];
1364 debug("writing %s\n", filename);
1366 filename_copy = strdup(filename);
1370 split_filename(filename_copy, &parent, &basename);
1371 if (!strlen(basename)) {
1376 if (normalize_longname(l_filename, basename)) {
1377 printf("FAT: illegal filename (%s)\n", basename);
1382 itr = malloc_cache_aligned(sizeof(fat_itr));
1388 ret = fat_itr_root(itr, &datablock);
1392 total_sector = datablock.total_sect;
1394 ret = fat_itr_resolve(itr, parent, TYPE_DIR);
1396 printf("%s: doesn't exist (%d)\n", parent, ret);
1400 retdent = find_directory_entry(itr, l_filename);
1403 if (fat_itr_isdir(itr)) {
1410 /* Append to the end */
1411 pos = FAT2CPU32(retdent->size);
1412 if (pos > retdent->size) {
1413 /* No hole allowed */
1418 /* Update file size in a directory entry */
1419 retdent->size = cpu_to_le32(pos + size);
1420 /* Update change date */
1421 dentry_set_time(retdent);
1423 /* Create a new file */
1424 char shortname[SHORT_NAME_SIZE];
1428 /* No hole allowed */
1433 /* Check if long name is needed */
1434 ndent = set_name(itr, basename, shortname);
1439 ret = fat_find_empty_dentries(itr, ndent);
1443 /* Set long name entries */
1444 ret = fill_dir_slot(itr, basename, shortname);
1449 /* Set short name entry */
1450 fill_dentry(itr->fsdata, itr->dent, shortname, 0, size,
1453 retdent = itr->dent;
1456 ret = set_contents(mydata, retdent, pos, buffer, size, actwrite);
1458 printf("Error: writing contents\n");
1462 debug("attempt to write 0x%llx bytes\n", *actwrite);
1464 /* Flush fat buffer */
1465 ret = flush_dirty_fat_buffer(mydata);
1467 printf("Error: flush fat buffer\n");
1472 /* Write directory table to device */
1473 ret = flush_dir(itr);
1476 free(filename_copy);
1477 free(mydata->fatbuf);
1482 int file_fat_write(const char *filename, void *buffer, loff_t offset,
1483 loff_t maxsize, loff_t *actwrite)
1485 return file_fat_write_at(filename, offset, buffer, maxsize, actwrite);
1488 static int fat_dir_entries(fat_itr *itr)
1491 fsdata fsdata = { .fatbuf = NULL, }, *mydata = &fsdata;
1492 /* for FATBUFSIZE */
1495 dirs = malloc_cache_aligned(sizeof(fat_itr));
1497 debug("Error: allocating memory\n");
1502 /* duplicate fsdata */
1503 fat_itr_child(dirs, itr);
1504 fsdata = *dirs->fsdata;
1506 /* allocate local fat buffer */
1507 fsdata.fatbuf = malloc_cache_aligned(FATBUFSIZE);
1508 if (!fsdata.fatbuf) {
1509 debug("Error: allocating memory\n");
1513 fsdata.fatbufnum = -1;
1514 dirs->fsdata = &fsdata;
1516 for (count = 0; fat_itr_next(dirs); count++)
1520 free(fsdata.fatbuf);
1526 * delete_single_dentry() - delete a single directory entry
1528 * @itr: directory iterator
1529 * Return: 0 for success
1531 static int delete_single_dentry(fat_itr *itr)
1533 struct dir_entry *dent = itr->dent;
1535 memset(dent, 0, sizeof(*dent));
1536 dent->nameext.name[0] = DELETED_FLAG;
1538 if (!itr->remaining)
1539 return flush_dir(itr);
1544 * delete_long_name() - delete long name directory entries
1546 * @itr: directory iterator
1547 * Return: 0 for success
1549 static int delete_long_name(fat_itr *itr)
1551 int seqn = itr->dent->nameext.name[0] & ~LAST_LONG_ENTRY_MASK;
1554 struct dir_entry *dent;
1557 ret = delete_single_dentry(itr);
1560 dent = next_dent(itr);
1568 * delete_dentry_long() - remove directory entry
1570 * @itr: directory iterator
1571 * Return: 0 for success
1573 static int delete_dentry_long(fat_itr *itr)
1575 fsdata *mydata = itr->fsdata;
1576 dir_entry *dent = itr->dent;
1578 /* free cluster blocks */
1579 clear_fatent(mydata, START(dent));
1580 if (flush_dirty_fat_buffer(mydata) < 0) {
1581 printf("Error: flush fat buffer\n");
1584 /* Position to first directory entry for long name */
1585 if (itr->clust != itr->dent_clust) {
1588 ret = fat_move_to_cluster(itr, itr->dent_clust);
1592 itr->dent = itr->dent_start;
1593 itr->remaining = itr->dent_rem;
1594 dent = itr->dent_start;
1595 /* Delete long name */
1596 if ((dent->attr & ATTR_VFAT) == ATTR_VFAT &&
1597 (dent->nameext.name[0] & LAST_LONG_ENTRY_MASK)) {
1600 ret = delete_long_name(itr);
1604 /* Delete short name */
1605 delete_single_dentry(itr);
1606 return flush_dir(itr);
1609 int fat_unlink(const char *filename)
1611 fsdata fsdata = { .fatbuf = NULL, };
1612 fat_itr *itr = NULL;
1614 char *filename_copy, *dirname, *basename;
1616 filename_copy = strdup(filename);
1617 itr = malloc_cache_aligned(sizeof(fat_itr));
1618 if (!itr || !filename_copy) {
1619 printf("Error: out of memory\n");
1623 split_filename(filename_copy, &dirname, &basename);
1625 if (!strcmp(dirname, "/") && !strcmp(basename, "")) {
1626 printf("Error: cannot remove root\n");
1631 ret = fat_itr_root(itr, &fsdata);
1635 total_sector = fsdata.total_sect;
1637 ret = fat_itr_resolve(itr, dirname, TYPE_DIR);
1639 printf("%s: doesn't exist (%d)\n", dirname, ret);
1644 if (!find_directory_entry(itr, basename)) {
1645 log_err("%s: doesn't exist (%d)\n", basename, -ENOENT);
1650 if (fat_itr_isdir(itr)) {
1651 n_entries = fat_dir_entries(itr);
1652 if (n_entries < 0) {
1656 if (n_entries > 2) {
1657 printf("Error: directory is not empty: %d\n",
1664 ret = delete_dentry_long(itr);
1667 free(fsdata.fatbuf);
1669 free(filename_copy);
1674 int fat_mkdir(const char *dirname)
1677 fsdata datablock = { .fatbuf = NULL, };
1678 fsdata *mydata = &datablock;
1679 fat_itr *itr = NULL;
1680 char *dirname_copy, *parent, *basename;
1681 char l_dirname[VFAT_MAXLEN_BYTES];
1684 unsigned int bytesperclust;
1685 dir_entry *dotdent = NULL;
1687 dirname_copy = strdup(dirname);
1691 split_filename(dirname_copy, &parent, &basename);
1692 if (!strlen(basename)) {
1697 if (normalize_longname(l_dirname, basename)) {
1698 printf("FAT: illegal filename (%s)\n", basename);
1703 itr = malloc_cache_aligned(sizeof(fat_itr));
1709 ret = fat_itr_root(itr, &datablock);
1713 total_sector = datablock.total_sect;
1715 ret = fat_itr_resolve(itr, parent, TYPE_DIR);
1717 printf("%s: doesn't exist (%d)\n", parent, ret);
1721 retdent = find_directory_entry(itr, l_dirname);
1724 printf("%s: already exists\n", l_dirname);
1728 char shortname[SHORT_NAME_SIZE];
1732 /* root dir cannot have "." or ".." */
1733 if (!strcmp(l_dirname, ".") ||
1734 !strcmp(l_dirname, "..")) {
1740 /* Check if long name is needed */
1741 ndent = set_name(itr, basename, shortname);
1746 ret = fat_find_empty_dentries(itr, ndent);
1750 /* Set long name entries */
1751 ret = fill_dir_slot(itr, basename, shortname);
1756 /* Set attribute as archive for regular file */
1757 fill_dentry(itr->fsdata, itr->dent, shortname, 0, 0,
1758 ATTR_DIR | ATTR_ARCH);
1760 retdent = itr->dent;
1763 /* Default entries */
1764 bytesperclust = mydata->clust_size * mydata->sect_size;
1765 dotdent = malloc_cache_aligned(bytesperclust);
1770 memset(dotdent, 0, bytesperclust);
1772 memcpy(&dotdent[0].nameext, ". ", 11);
1773 dotdent[0].attr = ATTR_DIR | ATTR_ARCH;
1775 memcpy(&dotdent[1].nameext, ".. ", 11);
1776 dotdent[1].attr = ATTR_DIR | ATTR_ARCH;
1779 set_start_cluster(mydata, &dotdent[1], 0);
1781 set_start_cluster(mydata, &dotdent[1], itr->start_clust);
1783 ret = set_contents(mydata, retdent, 0, (__u8 *)dotdent,
1784 bytesperclust, &actwrite);
1786 printf("Error: writing contents\n");
1789 /* Write twice for "." */
1790 set_start_cluster(mydata, &dotdent[0], START(retdent));
1791 ret = set_contents(mydata, retdent, 0, (__u8 *)dotdent,
1792 bytesperclust, &actwrite);
1794 printf("Error: writing contents\n");
1798 /* Flush fat buffer */
1799 ret = flush_dirty_fat_buffer(mydata);
1801 printf("Error: flush fat buffer\n");
1806 /* Write directory table to device */
1807 ret = flush_dir(itr);
1811 free(mydata->fatbuf);