1 // SPDX-License-Identifier: GPL-2.0+
5 * R/W (V)FAT 12/16/32 filesystem implementation by Donggeun Kim
17 #include <asm/byteorder.h>
18 #include <asm/cache.h>
19 #include <linux/ctype.h>
20 #include <linux/math64.h>
23 static dir_entry *find_directory_entry(fat_itr *itr, char *filename);
24 static int new_dir_table(fat_itr *itr);
26 /* Characters that may only be used in long file names */
27 static const char LONG_ONLY_CHARS[] = "+,;=[]";
29 /* Combined size of the name and ext fields in the directory entry */
30 #define SHORT_NAME_SIZE 11
33 * str2fat() - convert string to valid FAT name characters
35 * Stop when reaching end of @src or a period.
37 * Replace characters that may only be used in long names by underscores.
38 * Convert lower case characters to upper case.
40 * To avoid assumptions about the code page we do not use characters
41 * above 0x7f for the short name.
43 * @dest: destination buffer
45 * @length: size of destination buffer
46 * Return: number of bytes in destination buffer
48 static int str2fat(char *dest, char *src, int length)
52 for (i = 0; i < length; ++src) {
59 if (strchr(LONG_ONLY_CHARS, c) || c > 0x7f)
61 else if (c >= 'a' && c <= 'z')
70 * fat_move_to_cluster() - position to first directory entry in cluster
72 * @itr: directory iterator
74 * Return: 0 for success, -EIO on error
76 static int fat_move_to_cluster(fat_itr *itr, unsigned int cluster)
80 /* position to the start of the directory */
81 itr->next_clust = cluster;
82 itr->last_cluster = 0;
83 if (!fat_next_cluster(itr, &nbytes))
85 itr->dent = (dir_entry *)itr->block;
86 itr->remaining = nbytes / sizeof(dir_entry) - 1;
91 * set_name() - set short name in directory entry
93 * The function determines if the @filename is a valid short name.
94 * In this case no long name is needed.
96 * If a long name is needed, a short name is constructed.
98 * @itr: directory iterator
99 * @filename: long file name
100 * @shortname: buffer of 11 bytes to receive chosen short name and extension
101 * Return: number of directory entries needed, negative on error
103 static int set_name(fat_itr *itr, const char *filename, char *shortname)
111 struct nameext dirent;
116 /* Initialize buffer */
117 memset(&dirent, ' ', sizeof(dirent));
119 /* Convert filename to upper case short name */
120 period = strrchr(filename, '.');
121 pos = (char *)filename;
127 str2fat(dirent.ext, period + 1, sizeof(dirent.ext));
128 period_location = str2fat(dirent.name, pos, sizeof(dirent.name));
129 if (period_location < 0)
130 return period_location;
131 if (*dirent.name == ' ')
133 /* 0xe5 signals a deleted directory entry. Replace it by 0x05. */
134 if (*dirent.name == 0xe5)
137 /* If filename and short name are the same, quit. */
138 sprintf(buf, "%.*s.%.3s", period_location, dirent.name, dirent.ext);
139 if (!strcmp(buf, filename)) {
144 /* Construct an indexed short name */
145 for (i = 1; i < 0x200000; ++i) {
150 /* To speed up the search use random numbers */
155 j = 10 + (rand() >> j);
157 sprintf(buf, "~%d", j);
158 suffix_len = strlen(buf);
159 suffix_start = 8 - suffix_len;
160 if (suffix_start > period_location)
161 suffix_start = period_location;
162 memcpy(dirent.name + suffix_start, buf, suffix_len);
163 if (*dirent.ext != ' ')
164 sprintf(buf, "%.*s.%.3s", suffix_start + suffix_len,
165 dirent.name, dirent.ext);
167 sprintf(buf, "%.*s", suffix_start + suffix_len,
169 debug("generated short name: %s\n", buf);
171 /* Check that the short name does not exist yet. */
172 ret = fat_move_to_cluster(itr, itr->start_clust);
175 if (find_directory_entry(itr, buf))
178 debug("chosen short name: %s\n", buf);
179 /* Each long name directory entry takes 13 characters. */
180 ret = (strlen(filename) + 25) / 13;
185 memcpy(shortname, &dirent, SHORT_NAME_SIZE);
189 static int total_sector;
190 static int disk_write(__u32 block, __u32 nr_blocks, void *buf)
197 if (cur_part_info.start + block + nr_blocks >
198 cur_part_info.start + total_sector) {
199 printf("error: overflow occurs\n");
203 ret = blk_dwrite(cur_dev, cur_part_info.start + block, nr_blocks, buf);
204 if (nr_blocks && ret == 0)
211 * Write fat buffer into block device
213 static int flush_dirty_fat_buffer(fsdata *mydata)
215 int getsize = FATBUFBLOCKS;
216 __u32 fatlength = mydata->fatlength;
217 __u8 *bufptr = mydata->fatbuf;
218 __u32 startblock = mydata->fatbufnum * FATBUFBLOCKS;
220 debug("debug: evicting %d, dirty: %d\n", mydata->fatbufnum,
221 (int)mydata->fat_dirty);
223 if ((!mydata->fat_dirty) || (mydata->fatbufnum == -1))
226 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
227 if (startblock + getsize > fatlength)
228 getsize = fatlength - startblock;
230 startblock += mydata->fat_sect;
233 if (disk_write(startblock, getsize, bufptr) < 0) {
234 debug("error: writing FAT blocks\n");
238 if (mydata->fats == 2) {
239 /* Update corresponding second FAT blocks */
240 startblock += mydata->fatlength;
241 if (disk_write(startblock, getsize, bufptr) < 0) {
242 debug("error: writing second FAT blocks\n");
246 mydata->fat_dirty = 0;
252 * fat_find_empty_dentries() - find a sequence of available directory entries
254 * @itr: directory iterator
255 * @count: number of directory entries to find
256 * Return: 0 on success or negative error number
258 static int fat_find_empty_dentries(fat_itr *itr, int count)
260 unsigned int cluster;
266 ret = fat_move_to_cluster(itr, itr->start_clust);
272 log_debug("Not enough directory entries available\n");
275 switch (itr->dent->nameext.name[0]) {
279 /* Remember first deleted directory entry */
280 cluster = itr->clust;
282 remaining = itr->remaining;
295 (!itr->is_root || itr->fsdata->fatsize == 32) &&
300 /* Position back to first directory entry */
301 if (itr->clust != cluster) {
302 ret = fat_move_to_cluster(itr, cluster);
307 itr->remaining = remaining;
312 * Set the file name information from 'name' into 'slotptr',
314 static int str2slot(dir_slot *slotptr, const char *name, int *idx)
318 for (j = 0; j <= 8; j += 2) {
319 if (name[*idx] == 0x00) {
320 slotptr->name0_4[j] = 0;
321 slotptr->name0_4[j + 1] = 0;
325 slotptr->name0_4[j] = name[*idx];
329 for (j = 0; j <= 10; j += 2) {
330 if (name[*idx] == 0x00) {
331 slotptr->name5_10[j] = 0;
332 slotptr->name5_10[j + 1] = 0;
336 slotptr->name5_10[j] = name[*idx];
340 for (j = 0; j <= 2; j += 2) {
341 if (name[*idx] == 0x00) {
342 slotptr->name11_12[j] = 0;
343 slotptr->name11_12[j + 1] = 0;
347 slotptr->name11_12[j] = name[*idx];
352 if (name[*idx] == 0x00)
356 /* Not used characters are filled with 0xff 0xff */
358 for (; end_idx < 5; end_idx++) {
359 slotptr->name0_4[end_idx * 2] = 0xff;
360 slotptr->name0_4[end_idx * 2 + 1] = 0xff;
365 for (; end_idx < 6; end_idx++) {
366 slotptr->name5_10[end_idx * 2] = 0xff;
367 slotptr->name5_10[end_idx * 2 + 1] = 0xff;
372 for (; end_idx < 2; end_idx++) {
373 slotptr->name11_12[end_idx * 2] = 0xff;
374 slotptr->name11_12[end_idx * 2 + 1] = 0xff;
380 static int flush_dir(fat_itr *itr);
383 * fill_dir_slot() - fill directory entries for long name
385 * @itr: directory iterator
387 * @shortname: short name
388 * Return: 0 for success, -errno otherwise
391 fill_dir_slot(fat_itr *itr, const char *l_name, const char *shortname)
393 __u8 temp_dir_slot_buffer[MAX_LFN_SLOT * sizeof(dir_slot)];
394 dir_slot *slotptr = (dir_slot *)temp_dir_slot_buffer;
395 __u8 counter = 0, checksum;
398 /* Get short file name checksum value */
399 checksum = mkcksum((void *)shortname);
402 memset(slotptr, 0x00, sizeof(dir_slot));
403 ret = str2slot(slotptr, l_name, &idx);
404 slotptr->id = ++counter;
405 slotptr->attr = ATTR_VFAT;
406 slotptr->alias_checksum = checksum;
411 slotptr->id |= LAST_LONG_ENTRY_MASK;
413 while (counter >= 1) {
414 memcpy(itr->dent, slotptr, sizeof(dir_slot));
418 if (!itr->remaining) {
419 /* Write directory table to device */
420 ret = flush_dir(itr);
434 * Set the entry at index 'entry' in a FAT (12/16/32) table.
436 static int set_fatent_value(fsdata *mydata, __u32 entry, __u32 entry_value)
438 __u32 bufnum, offset, off16;
441 switch (mydata->fatsize) {
443 bufnum = entry / FAT32BUFSIZE;
444 offset = entry - bufnum * FAT32BUFSIZE;
447 bufnum = entry / FAT16BUFSIZE;
448 offset = entry - bufnum * FAT16BUFSIZE;
451 bufnum = entry / FAT12BUFSIZE;
452 offset = entry - bufnum * FAT12BUFSIZE;
455 /* Unsupported FAT size */
459 /* Read a new block of FAT entries into the cache. */
460 if (bufnum != mydata->fatbufnum) {
461 int getsize = FATBUFBLOCKS;
462 __u8 *bufptr = mydata->fatbuf;
463 __u32 fatlength = mydata->fatlength;
464 __u32 startblock = bufnum * FATBUFBLOCKS;
466 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
467 if (startblock + getsize > fatlength)
468 getsize = fatlength - startblock;
470 if (flush_dirty_fat_buffer(mydata) < 0)
473 startblock += mydata->fat_sect;
475 if (disk_read(startblock, getsize, bufptr) < 0) {
476 debug("Error reading FAT blocks\n");
479 mydata->fatbufnum = bufnum;
483 mydata->fat_dirty = 1;
485 /* Set the actual entry */
486 switch (mydata->fatsize) {
488 ((__u32 *) mydata->fatbuf)[offset] = cpu_to_le32(entry_value);
491 ((__u16 *) mydata->fatbuf)[offset] = cpu_to_le16(entry_value);
494 off16 = (offset * 3) / 4;
496 switch (offset & 0x3) {
498 val1 = cpu_to_le16(entry_value) & 0xfff;
499 ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff;
500 ((__u16 *)mydata->fatbuf)[off16] |= val1;
503 val1 = cpu_to_le16(entry_value) & 0xf;
504 val2 = (cpu_to_le16(entry_value) >> 4) & 0xff;
506 ((__u16 *)mydata->fatbuf)[off16] &= ~0xf000;
507 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 12);
509 ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xff;
510 ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
513 val1 = cpu_to_le16(entry_value) & 0xff;
514 val2 = (cpu_to_le16(entry_value) >> 8) & 0xf;
516 ((__u16 *)mydata->fatbuf)[off16] &= ~0xff00;
517 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 8);
519 ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xf;
520 ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
523 val1 = cpu_to_le16(entry_value) & 0xfff;
524 ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff0;
525 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 4);
540 * Determine the next free cluster after 'entry' in a FAT (12/16/32) table
541 * and link it to 'entry'. EOC marker is not set on returned entry.
543 static __u32 determine_fatent(fsdata *mydata, __u32 entry)
545 __u32 next_fat, next_entry = entry + 1;
548 next_fat = get_fatent(mydata, next_entry);
550 /* found free entry, link to entry */
551 set_fatent_value(mydata, entry, next_entry);
556 debug("FAT%d: entry: %08x, entry_value: %04x\n",
557 mydata->fatsize, entry, next_entry);
563 * set_sectors() - write data to sectors
565 * Write 'size' bytes from 'buffer' into the specified sector.
567 * @mydata: data to be written
568 * @startsect: sector to be written to
569 * @buffer: data to be written
570 * @size: bytes to be written (but not more than the size of a cluster)
571 * Return: 0 on success, -1 otherwise
574 set_sectors(fsdata *mydata, u32 startsect, u8 *buffer, u32 size)
578 debug("startsect: %d\n", startsect);
580 if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
581 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
583 debug("FAT: Misaligned buffer address (%p)\n", buffer);
585 while (size >= mydata->sect_size) {
586 memcpy(tmpbuf, buffer, mydata->sect_size);
587 ret = disk_write(startsect++, 1, tmpbuf);
589 debug("Error writing data (got %d)\n", ret);
593 buffer += mydata->sect_size;
594 size -= mydata->sect_size;
596 } else if (size >= mydata->sect_size) {
599 nsects = size / mydata->sect_size;
600 ret = disk_write(startsect, nsects, buffer);
602 debug("Error writing data (got %d)\n", ret);
607 buffer += nsects * mydata->sect_size;
608 size -= nsects * mydata->sect_size;
612 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
613 /* Do not leak content of stack */
614 memset(tmpbuf, 0, mydata->sect_size);
615 memcpy(tmpbuf, buffer, size);
616 ret = disk_write(startsect, 1, tmpbuf);
618 debug("Error writing data (got %d)\n", ret);
627 * set_cluster() - write data to cluster
629 * Write 'size' bytes from 'buffer' into the specified cluster.
631 * @mydata: data to be written
632 * @clustnum: cluster to be written to
633 * @buffer: data to be written
634 * @size: bytes to be written (but not more than the size of a cluster)
635 * Return: 0 on success, -1 otherwise
638 set_cluster(fsdata *mydata, u32 clustnum, u8 *buffer, u32 size)
640 return set_sectors(mydata, clust_to_sect(mydata, clustnum),
645 * flush_dir() - flush directory
647 * @itr: directory iterator
648 * Return: 0 for success, -EIO on error
650 static int flush_dir(fat_itr *itr)
652 fsdata *mydata = itr->fsdata;
653 u32 startsect, sect_offset, nsects;
656 if (!itr->is_root || mydata->fatsize == 32) {
657 ret = set_cluster(mydata, itr->clust, itr->block,
658 mydata->clust_size * mydata->sect_size);
662 sect_offset = itr->clust * mydata->clust_size;
663 startsect = mydata->rootdir_sect + sect_offset;
664 /* do not write past the end of rootdir */
665 nsects = min_t(u32, mydata->clust_size,
666 mydata->rootdir_size - sect_offset);
668 ret = set_sectors(mydata, startsect, itr->block,
669 nsects * mydata->sect_size);
672 log_err("Error: writing directory entry\n");
679 * Read and modify data on existing and consecutive cluster blocks
682 get_set_cluster(fsdata *mydata, __u32 clustnum, loff_t pos, __u8 *buffer,
683 loff_t size, loff_t *gotsize)
685 static u8 *tmpbuf_cluster;
686 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
689 int clustcount, i, ret;
695 if (!tmpbuf_cluster) {
696 tmpbuf_cluster = memalign(ARCH_DMA_MINALIGN, MAX_CLUSTSIZE);
701 assert(pos < bytesperclust);
702 startsect = clust_to_sect(mydata, clustnum);
704 debug("clustnum: %d, startsect: %d, pos: %lld\n",
705 clustnum, startsect, pos);
707 /* partial write at beginning */
709 wsize = min(bytesperclust - pos, size);
710 ret = disk_read(startsect, mydata->clust_size, tmpbuf_cluster);
711 if (ret != mydata->clust_size) {
712 debug("Error reading data (got %d)\n", ret);
716 memcpy(tmpbuf_cluster + pos, buffer, wsize);
717 ret = disk_write(startsect, mydata->clust_size, tmpbuf_cluster);
718 if (ret != mydata->clust_size) {
719 debug("Error writing data (got %d)\n", ret);
727 startsect += mydata->clust_size;
733 /* full-cluster write */
734 if (size >= bytesperclust) {
735 clustcount = lldiv(size, bytesperclust);
737 if (!((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1))) {
738 wsize = clustcount * bytesperclust;
739 ret = disk_write(startsect,
740 clustcount * mydata->clust_size,
742 if (ret != clustcount * mydata->clust_size) {
743 debug("Error writing data (got %d)\n", ret);
751 startsect += clustcount * mydata->clust_size;
753 for (i = 0; i < clustcount; i++) {
754 memcpy(tmpbuf_cluster, buffer, bytesperclust);
755 ret = disk_write(startsect,
758 if (ret != mydata->clust_size) {
759 debug("Error writing data (got %d)\n",
764 size -= bytesperclust;
765 buffer += bytesperclust;
766 *gotsize += bytesperclust;
768 startsect += mydata->clust_size;
773 /* partial write at end */
776 ret = disk_read(startsect, mydata->clust_size, tmpbuf_cluster);
777 if (ret != mydata->clust_size) {
778 debug("Error reading data (got %d)\n", ret);
781 memcpy(tmpbuf_cluster, buffer, wsize);
782 ret = disk_write(startsect, mydata->clust_size, tmpbuf_cluster);
783 if (ret != mydata->clust_size) {
784 debug("Error writing data (got %d)\n", ret);
798 * Find the first empty cluster
800 static int find_empty_cluster(fsdata *mydata)
802 __u32 fat_val, entry = 3;
805 fat_val = get_fatent(mydata, entry);
815 * new_dir_table() - allocate a cluster for additional directory entries
817 * @itr: directory iterator
818 * Return: 0 on success, -EIO otherwise
820 static int new_dir_table(fat_itr *itr)
822 fsdata *mydata = itr->fsdata;
823 int dir_newclust = 0;
824 int dir_oldclust = itr->clust;
825 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
827 dir_newclust = find_empty_cluster(mydata);
830 * Flush before updating FAT to ensure valid directory structure
831 * in case of failure.
833 itr->clust = dir_newclust;
834 itr->next_clust = dir_newclust;
835 memset(itr->block, 0x00, bytesperclust);
839 set_fatent_value(mydata, dir_oldclust, dir_newclust);
840 if (mydata->fatsize == 32)
841 set_fatent_value(mydata, dir_newclust, 0xffffff8);
842 else if (mydata->fatsize == 16)
843 set_fatent_value(mydata, dir_newclust, 0xfff8);
844 else if (mydata->fatsize == 12)
845 set_fatent_value(mydata, dir_newclust, 0xff8);
847 if (flush_dirty_fat_buffer(mydata) < 0)
850 itr->dent = (dir_entry *)itr->block;
851 itr->last_cluster = 1;
852 itr->remaining = bytesperclust / sizeof(dir_entry) - 1;
858 * Set empty cluster from 'entry' to the end of a file
860 static int clear_fatent(fsdata *mydata, __u32 entry)
864 while (!CHECK_CLUST(entry, mydata->fatsize)) {
865 fat_val = get_fatent(mydata, entry);
867 set_fatent_value(mydata, entry, 0);
874 /* Flush fat buffer */
875 if (flush_dirty_fat_buffer(mydata) < 0)
882 * Set start cluster in directory entry
884 static void set_start_cluster(const fsdata *mydata, dir_entry *dentptr,
887 if (mydata->fatsize == 32)
889 cpu_to_le16((start_cluster & 0xffff0000) >> 16);
890 dentptr->start = cpu_to_le16(start_cluster & 0xffff);
894 * Check whether adding a file makes the file system to
895 * exceed the size of the block device
896 * Return -1 when overflow occurs, otherwise return 0
898 static int check_overflow(fsdata *mydata, __u32 clustnum, loff_t size)
900 __u32 startsect, sect_num, offset;
903 startsect = clust_to_sect(mydata, clustnum);
905 startsect = mydata->rootdir_sect;
907 sect_num = div_u64_rem(size, mydata->sect_size, &offset);
912 if (startsect + sect_num > total_sector)
918 * Write at most 'maxsize' bytes from 'buffer' into
919 * the file associated with 'dentptr'
920 * Update the number of bytes written in *gotsize and return 0
921 * or return -1 on fatal errors.
924 set_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos, __u8 *buffer,
925 loff_t maxsize, loff_t *gotsize)
927 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
928 __u32 curclust = START(dentptr);
929 __u32 endclust = 0, newclust = 0;
930 u64 cur_pos, filesize;
931 loff_t offset, actsize, wsize;
934 filesize = pos + maxsize;
936 debug("%llu bytes\n", filesize);
941 if (!CHECK_CLUST(curclust, mydata->fatsize) ||
942 IS_LAST_CLUST(curclust, mydata->fatsize)) {
943 clear_fatent(mydata, curclust);
944 set_start_cluster(mydata, dentptr, 0);
947 debug("curclust: 0x%x\n", curclust);
948 debug("Invalid FAT entry\n");
957 /* go to cluster at pos */
958 cur_pos = bytesperclust;
962 if (IS_LAST_CLUST(curclust, mydata->fatsize))
965 newclust = get_fatent(mydata, curclust);
966 if (!IS_LAST_CLUST(newclust, mydata->fatsize) &&
967 CHECK_CLUST(newclust, mydata->fatsize)) {
968 debug("curclust: 0x%x\n", curclust);
969 debug("Invalid FAT entry\n");
973 cur_pos += bytesperclust;
976 if (IS_LAST_CLUST(curclust, mydata->fatsize)) {
977 assert(pos == cur_pos);
981 assert(pos < cur_pos);
982 cur_pos -= bytesperclust;
985 assert(IS_LAST_CLUST(curclust, mydata->fatsize) ||
986 !CHECK_CLUST(curclust, mydata->fatsize));
989 /* search for allocated consecutive clusters */
990 actsize = bytesperclust;
993 if (filesize <= (cur_pos + actsize))
996 newclust = get_fatent(mydata, endclust);
998 if (newclust != endclust + 1)
1000 if (IS_LAST_CLUST(newclust, mydata->fatsize))
1002 if (CHECK_CLUST(newclust, mydata->fatsize)) {
1003 debug("curclust: 0x%x\n", curclust);
1004 debug("Invalid FAT entry\n");
1008 actsize += bytesperclust;
1009 endclust = newclust;
1012 /* overwrite to <curclust..endclust> */
1016 offset = pos - cur_pos;
1017 wsize = min_t(unsigned long long, actsize, filesize - cur_pos);
1020 if (get_set_cluster(mydata, curclust, offset,
1021 buffer, wsize, &actsize)) {
1022 printf("Error get-and-setting cluster\n");
1027 cur_pos += offset + wsize;
1029 if (filesize <= cur_pos)
1032 if (IS_LAST_CLUST(newclust, mydata->fatsize))
1033 /* no more clusters */
1036 curclust = newclust;
1039 if (filesize <= cur_pos) {
1041 newclust = get_fatent(mydata, endclust);
1042 if (!IS_LAST_CLUST(newclust, mydata->fatsize)) {
1043 /* truncate the rest */
1044 clear_fatent(mydata, newclust);
1046 /* Mark end of file in FAT */
1047 if (mydata->fatsize == 12)
1049 else if (mydata->fatsize == 16)
1051 else if (mydata->fatsize == 32)
1052 newclust = 0xfffffff;
1053 set_fatent_value(mydata, endclust, newclust);
1059 curclust = endclust;
1060 filesize -= cur_pos;
1061 assert(!do_div(cur_pos, bytesperclust));
1064 /* allocate and write */
1067 /* Assure that curclust is valid */
1069 curclust = find_empty_cluster(mydata);
1070 set_start_cluster(mydata, dentptr, curclust);
1072 newclust = get_fatent(mydata, curclust);
1074 if (IS_LAST_CLUST(newclust, mydata->fatsize)) {
1075 newclust = determine_fatent(mydata, curclust);
1076 set_fatent_value(mydata, curclust, newclust);
1077 curclust = newclust;
1079 debug("error: something wrong\n");
1084 /* TODO: already partially written */
1085 if (check_overflow(mydata, curclust, filesize)) {
1086 printf("Error: no space left: %llu\n", filesize);
1090 actsize = bytesperclust;
1091 endclust = curclust;
1093 /* search for consecutive clusters */
1094 while (actsize < filesize) {
1095 newclust = determine_fatent(mydata, endclust);
1097 if ((newclust - 1) != endclust)
1098 /* write to <curclust..endclust> */
1101 if (CHECK_CLUST(newclust, mydata->fatsize)) {
1102 debug("newclust: 0x%x\n", newclust);
1103 debug("Invalid FAT entry\n");
1106 endclust = newclust;
1107 actsize += bytesperclust;
1110 /* set remaining bytes */
1112 if (set_cluster(mydata, curclust, buffer, (u32)actsize) != 0) {
1113 debug("error: writing cluster\n");
1116 *gotsize += actsize;
1118 /* Mark end of file in FAT */
1119 if (mydata->fatsize == 12)
1121 else if (mydata->fatsize == 16)
1123 else if (mydata->fatsize == 32)
1124 newclust = 0xfffffff;
1125 set_fatent_value(mydata, endclust, newclust);
1129 if (set_cluster(mydata, curclust, buffer, (u32)actsize) != 0) {
1130 debug("error: writing cluster\n");
1133 *gotsize += actsize;
1134 filesize -= actsize;
1137 if (CHECK_CLUST(newclust, mydata->fatsize)) {
1138 debug("newclust: 0x%x\n", newclust);
1139 debug("Invalid FAT entry\n");
1142 actsize = bytesperclust;
1143 curclust = endclust = newclust;
1150 * fill_dentry() - fill directory entry with shortname
1152 * @mydata: private filesystem parameters
1153 * @dentptr: directory entry
1154 * @shortname: chosen short name
1155 * @start_cluster: first cluster of file
1157 * @attr: file attributes
1159 static void fill_dentry(fsdata *mydata, dir_entry *dentptr,
1160 const char *shortname, __u32 start_cluster, __u32 size, __u8 attr)
1162 memset(dentptr, 0, sizeof(*dentptr));
1164 set_start_cluster(mydata, dentptr, start_cluster);
1165 dentptr->size = cpu_to_le32(size);
1167 dentptr->attr = attr;
1169 memcpy(&dentptr->nameext, shortname, SHORT_NAME_SIZE);
1173 * find_directory_entry() - find a directory entry by filename
1175 * @itr: directory iterator
1176 * @filename: name of file to find
1177 * Return: directory entry or NULL
1179 static dir_entry *find_directory_entry(fat_itr *itr, char *filename)
1183 while (fat_itr_next(itr)) {
1184 /* check both long and short name: */
1185 if (!strcasecmp(filename, itr->name))
1187 else if (itr->name != itr->s_name &&
1188 !strcasecmp(filename, itr->s_name))
1194 if (itr->dent->nameext.name[0] == '\0')
1203 static int split_filename(char *filename, char **dirname, char **basename)
1205 char *p, *last_slash, *last_slash_cont;
1210 last_slash_cont = NULL;
1212 if (ISDIRDELIM(*p)) {
1214 last_slash_cont = p;
1215 /* continuous slashes */
1216 while (ISDIRDELIM(*p))
1217 last_slash_cont = p++;
1225 if (last_slash_cont == (filename + strlen(filename) - 1)) {
1226 /* remove trailing slashes */
1231 if (last_slash == filename) {
1232 /* avoid ""(null) directory */
1236 *dirname = filename;
1239 *last_slash_cont = '\0';
1240 filename = last_slash_cont + 1;
1242 *dirname = "/"; /* root by default */
1246 * The FAT32 File System Specification v1.03 requires leading and
1247 * trailing spaces as well as trailing periods to be ignored.
1249 for (; *filename == ' '; ++filename)
1252 /* Keep special entries '.' and '..' */
1253 if (filename[0] == '.' &&
1254 (!filename[1] || (filename[1] == '.' && !filename[2])))
1257 /* Remove trailing periods and spaces */
1258 for (p = filename + strlen(filename) - 1; p >= filename; --p) {
1270 *basename = filename;
1276 * normalize_longname() - check long file name and convert to lower case
1278 * We assume here that the FAT file system is using an 8bit code page.
1279 * Linux typically uses CP437, EDK2 assumes CP1250.
1281 * @l_filename: preallocated buffer receiving the normalized name
1282 * @filename: filename to normalize
1283 * Return: 0 on success, -1 on failure
1285 static int normalize_longname(char *l_filename, const char *filename)
1287 const char *p, illegal[] = "<>:\"/\\|?*";
1290 len = strlen(filename);
1291 if (!len || len >= VFAT_MAXLEN_BYTES || filename[len - 1] == '.')
1294 for (p = filename; *p; ++p) {
1295 if ((unsigned char)*p < 0x20)
1297 if (strchr(illegal, *p))
1301 strcpy(l_filename, filename);
1302 downcase(l_filename, VFAT_MAXLEN_BYTES);
1307 int file_fat_write_at(const char *filename, loff_t pos, void *buffer,
1308 loff_t size, loff_t *actwrite)
1311 fsdata datablock = { .fatbuf = NULL, };
1312 fsdata *mydata = &datablock;
1313 fat_itr *itr = NULL;
1315 char *filename_copy, *parent, *basename;
1316 char l_filename[VFAT_MAXLEN_BYTES];
1318 debug("writing %s\n", filename);
1320 filename_copy = strdup(filename);
1324 split_filename(filename_copy, &parent, &basename);
1325 if (!strlen(basename)) {
1330 if (normalize_longname(l_filename, basename)) {
1331 printf("FAT: illegal filename (%s)\n", basename);
1336 itr = malloc_cache_aligned(sizeof(fat_itr));
1342 ret = fat_itr_root(itr, &datablock);
1346 total_sector = datablock.total_sect;
1348 ret = fat_itr_resolve(itr, parent, TYPE_DIR);
1350 printf("%s: doesn't exist (%d)\n", parent, ret);
1354 retdent = find_directory_entry(itr, l_filename);
1357 if (fat_itr_isdir(itr)) {
1364 /* Append to the end */
1365 pos = FAT2CPU32(retdent->size);
1366 if (pos > retdent->size) {
1367 /* No hole allowed */
1372 /* Update file size in a directory entry */
1373 retdent->size = cpu_to_le32(pos + size);
1375 /* Create a new file */
1376 char shortname[SHORT_NAME_SIZE];
1380 /* No hole allowed */
1385 /* Check if long name is needed */
1386 ndent = set_name(itr, basename, shortname);
1391 ret = fat_find_empty_dentries(itr, ndent);
1395 /* Set long name entries */
1396 ret = fill_dir_slot(itr, basename, shortname);
1401 /* Set short name entry */
1402 fill_dentry(itr->fsdata, itr->dent, shortname, 0, size,
1405 retdent = itr->dent;
1408 ret = set_contents(mydata, retdent, pos, buffer, size, actwrite);
1410 printf("Error: writing contents\n");
1414 debug("attempt to write 0x%llx bytes\n", *actwrite);
1416 /* Flush fat buffer */
1417 ret = flush_dirty_fat_buffer(mydata);
1419 printf("Error: flush fat buffer\n");
1424 /* Write directory table to device */
1425 ret = flush_dir(itr);
1428 free(filename_copy);
1429 free(mydata->fatbuf);
1434 int file_fat_write(const char *filename, void *buffer, loff_t offset,
1435 loff_t maxsize, loff_t *actwrite)
1437 return file_fat_write_at(filename, offset, buffer, maxsize, actwrite);
1440 static int fat_dir_entries(fat_itr *itr)
1443 fsdata fsdata = { .fatbuf = NULL, }, *mydata = &fsdata;
1444 /* for FATBUFSIZE */
1447 dirs = malloc_cache_aligned(sizeof(fat_itr));
1449 debug("Error: allocating memory\n");
1454 /* duplicate fsdata */
1455 fat_itr_child(dirs, itr);
1456 fsdata = *dirs->fsdata;
1458 /* allocate local fat buffer */
1459 fsdata.fatbuf = malloc_cache_aligned(FATBUFSIZE);
1460 if (!fsdata.fatbuf) {
1461 debug("Error: allocating memory\n");
1465 fsdata.fatbufnum = -1;
1466 dirs->fsdata = &fsdata;
1468 for (count = 0; fat_itr_next(dirs); count++)
1472 free(fsdata.fatbuf);
1478 * delete_single_dentry() - delete a single directory entry
1480 * @itr: directory iterator
1481 * Return: 0 for success
1483 static int delete_single_dentry(fat_itr *itr)
1485 struct dir_entry *dent = itr->dent;
1487 memset(dent, 0, sizeof(*dent));
1488 dent->nameext.name[0] = DELETED_FLAG;
1490 if (!itr->remaining)
1491 return flush_dir(itr);
1496 * delete_long_name() - delete long name directory entries
1498 * @itr: directory iterator
1499 * Return: 0 for success
1501 static int delete_long_name(fat_itr *itr)
1503 int seqn = itr->dent->nameext.name[0] & ~LAST_LONG_ENTRY_MASK;
1506 struct dir_entry *dent;
1509 ret = delete_single_dentry(itr);
1512 dent = next_dent(itr);
1520 * delete_dentry_long() - remove directory entry
1522 * @itr: directory iterator
1523 * Return: 0 for success
1525 static int delete_dentry_long(fat_itr *itr)
1527 fsdata *mydata = itr->fsdata;
1528 dir_entry *dent = itr->dent;
1530 /* free cluster blocks */
1531 clear_fatent(mydata, START(dent));
1532 if (flush_dirty_fat_buffer(mydata) < 0) {
1533 printf("Error: flush fat buffer\n");
1536 /* Position to first directory entry for long name */
1537 if (itr->clust != itr->dent_clust) {
1540 ret = fat_move_to_cluster(itr, itr->dent_clust);
1544 itr->dent = itr->dent_start;
1545 itr->remaining = itr->dent_rem;
1546 dent = itr->dent_start;
1547 /* Delete long name */
1548 if ((dent->attr & ATTR_VFAT) == ATTR_VFAT &&
1549 (dent->nameext.name[0] & LAST_LONG_ENTRY_MASK)) {
1552 ret = delete_long_name(itr);
1556 /* Delete short name */
1557 delete_single_dentry(itr);
1558 return flush_dir(itr);
1561 int fat_unlink(const char *filename)
1563 fsdata fsdata = { .fatbuf = NULL, };
1564 fat_itr *itr = NULL;
1566 char *filename_copy, *dirname, *basename;
1568 filename_copy = strdup(filename);
1569 if (!filename_copy) {
1570 printf("Error: allocating memory\n");
1574 split_filename(filename_copy, &dirname, &basename);
1576 if (!strcmp(dirname, "/") && !strcmp(basename, "")) {
1577 printf("Error: cannot remove root\n");
1582 itr = malloc_cache_aligned(sizeof(fat_itr));
1584 printf("Error: allocating memory\n");
1589 ret = fat_itr_root(itr, &fsdata);
1593 total_sector = fsdata.total_sect;
1595 ret = fat_itr_resolve(itr, dirname, TYPE_DIR);
1597 printf("%s: doesn't exist (%d)\n", dirname, ret);
1602 if (!find_directory_entry(itr, basename)) {
1603 printf("%s: doesn't exist\n", basename);
1608 if (fat_itr_isdir(itr)) {
1609 n_entries = fat_dir_entries(itr);
1610 if (n_entries < 0) {
1614 if (n_entries > 2) {
1615 printf("Error: directory is not empty: %d\n",
1622 ret = delete_dentry_long(itr);
1625 free(fsdata.fatbuf);
1627 free(filename_copy);
1632 int fat_mkdir(const char *dirname)
1635 fsdata datablock = { .fatbuf = NULL, };
1636 fsdata *mydata = &datablock;
1637 fat_itr *itr = NULL;
1638 char *dirname_copy, *parent, *basename;
1639 char l_dirname[VFAT_MAXLEN_BYTES];
1642 unsigned int bytesperclust;
1643 dir_entry *dotdent = NULL;
1645 dirname_copy = strdup(dirname);
1649 split_filename(dirname_copy, &parent, &basename);
1650 if (!strlen(basename)) {
1655 if (normalize_longname(l_dirname, basename)) {
1656 printf("FAT: illegal filename (%s)\n", basename);
1661 itr = malloc_cache_aligned(sizeof(fat_itr));
1667 ret = fat_itr_root(itr, &datablock);
1671 total_sector = datablock.total_sect;
1673 ret = fat_itr_resolve(itr, parent, TYPE_DIR);
1675 printf("%s: doesn't exist (%d)\n", parent, ret);
1679 retdent = find_directory_entry(itr, l_dirname);
1682 printf("%s: already exists\n", l_dirname);
1686 char shortname[SHORT_NAME_SIZE];
1690 /* root dir cannot have "." or ".." */
1691 if (!strcmp(l_dirname, ".") ||
1692 !strcmp(l_dirname, "..")) {
1698 /* Check if long name is needed */
1699 ndent = set_name(itr, basename, shortname);
1704 ret = fat_find_empty_dentries(itr, ndent);
1708 /* Set long name entries */
1709 ret = fill_dir_slot(itr, basename, shortname);
1714 /* Set attribute as archive for regular file */
1715 fill_dentry(itr->fsdata, itr->dent, shortname, 0, 0,
1716 ATTR_DIR | ATTR_ARCH);
1718 retdent = itr->dent;
1721 /* Default entries */
1722 bytesperclust = mydata->clust_size * mydata->sect_size;
1723 dotdent = malloc_cache_aligned(bytesperclust);
1728 memset(dotdent, 0, bytesperclust);
1730 memcpy(&dotdent[0].nameext, ". ", 11);
1731 dotdent[0].attr = ATTR_DIR | ATTR_ARCH;
1733 memcpy(&dotdent[1].nameext, ".. ", 11);
1734 dotdent[1].attr = ATTR_DIR | ATTR_ARCH;
1737 set_start_cluster(mydata, &dotdent[1], 0);
1739 set_start_cluster(mydata, &dotdent[1], itr->start_clust);
1741 ret = set_contents(mydata, retdent, 0, (__u8 *)dotdent,
1742 bytesperclust, &actwrite);
1744 printf("Error: writing contents\n");
1747 /* Write twice for "." */
1748 set_start_cluster(mydata, &dotdent[0], START(retdent));
1749 ret = set_contents(mydata, retdent, 0, (__u8 *)dotdent,
1750 bytesperclust, &actwrite);
1752 printf("Error: writing contents\n");
1756 /* Flush fat buffer */
1757 ret = flush_dirty_fat_buffer(mydata);
1759 printf("Error: flush fat buffer\n");
1764 /* Write directory table to device */
1765 ret = flush_dir(itr);
1769 free(mydata->fatbuf);