1 // SPDX-License-Identifier: GPL-2.0+
5 * R/W (V)FAT 12/16/32 filesystem implementation by Donggeun Kim
12 #include <asm/byteorder.h>
14 #include <linux/ctype.h>
16 #include <linux/math64.h>
19 static void uppercase(char *str, int len)
23 for (i = 0; i < len; i++) {
29 static int total_sector;
30 static int disk_write(__u32 block, __u32 nr_blocks, void *buf)
37 if (cur_part_info.start + block + nr_blocks >
38 cur_part_info.start + total_sector) {
39 printf("error: overflow occurs\n");
43 ret = blk_dwrite(cur_dev, cur_part_info.start + block, nr_blocks, buf);
44 if (nr_blocks && ret == 0)
51 * Set short name in directory entry
53 static void set_name(dir_entry *dirent, const char *filename)
55 char s_name[VFAT_MAXLEN_BYTES];
57 int period_location, len, i, ext_num;
62 len = strlen(filename);
66 strcpy(s_name, filename);
67 uppercase(s_name, len);
69 period = strchr(s_name, '.');
71 period_location = len;
74 period_location = period - s_name;
75 ext_num = len - period_location - 1;
78 /* Pad spaces when the length of file name is shorter than eight */
79 if (period_location < 8) {
80 memcpy(dirent->name, s_name, period_location);
81 for (i = period_location; i < 8; i++)
82 dirent->name[i] = ' ';
83 } else if (period_location == 8) {
84 memcpy(dirent->name, s_name, period_location);
86 memcpy(dirent->name, s_name, 6);
87 dirent->name[6] = '~';
88 dirent->name[7] = '1';
92 memcpy(dirent->ext, s_name + period_location + 1, ext_num);
93 for (i = ext_num; i < 3; i++)
96 memcpy(dirent->ext, s_name + period_location + 1, 3);
98 debug("name : %s\n", dirent->name);
99 debug("ext : %s\n", dirent->ext);
103 * Write fat buffer into block device
105 static int flush_dirty_fat_buffer(fsdata *mydata)
107 int getsize = FATBUFBLOCKS;
108 __u32 fatlength = mydata->fatlength;
109 __u8 *bufptr = mydata->fatbuf;
110 __u32 startblock = mydata->fatbufnum * FATBUFBLOCKS;
112 debug("debug: evicting %d, dirty: %d\n", mydata->fatbufnum,
113 (int)mydata->fat_dirty);
115 if ((!mydata->fat_dirty) || (mydata->fatbufnum == -1))
118 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
119 if (startblock + getsize > fatlength)
120 getsize = fatlength - startblock;
122 startblock += mydata->fat_sect;
125 if (disk_write(startblock, getsize, bufptr) < 0) {
126 debug("error: writing FAT blocks\n");
130 if (mydata->fats == 2) {
131 /* Update corresponding second FAT blocks */
132 startblock += mydata->fatlength;
133 if (disk_write(startblock, getsize, bufptr) < 0) {
134 debug("error: writing second FAT blocks\n");
138 mydata->fat_dirty = 0;
144 * Set the file name information from 'name' into 'slotptr',
146 static int str2slot(dir_slot *slotptr, const char *name, int *idx)
150 for (j = 0; j <= 8; j += 2) {
151 if (name[*idx] == 0x00) {
152 slotptr->name0_4[j] = 0;
153 slotptr->name0_4[j + 1] = 0;
157 slotptr->name0_4[j] = name[*idx];
161 for (j = 0; j <= 10; j += 2) {
162 if (name[*idx] == 0x00) {
163 slotptr->name5_10[j] = 0;
164 slotptr->name5_10[j + 1] = 0;
168 slotptr->name5_10[j] = name[*idx];
172 for (j = 0; j <= 2; j += 2) {
173 if (name[*idx] == 0x00) {
174 slotptr->name11_12[j] = 0;
175 slotptr->name11_12[j + 1] = 0;
179 slotptr->name11_12[j] = name[*idx];
184 if (name[*idx] == 0x00)
188 /* Not used characters are filled with 0xff 0xff */
190 for (; end_idx < 5; end_idx++) {
191 slotptr->name0_4[end_idx * 2] = 0xff;
192 slotptr->name0_4[end_idx * 2 + 1] = 0xff;
197 for (; end_idx < 6; end_idx++) {
198 slotptr->name5_10[end_idx * 2] = 0xff;
199 slotptr->name5_10[end_idx * 2 + 1] = 0xff;
204 for (; end_idx < 2; end_idx++) {
205 slotptr->name11_12[end_idx * 2] = 0xff;
206 slotptr->name11_12[end_idx * 2 + 1] = 0xff;
212 static int flush_dir_table(fat_itr *itr);
215 * Fill dir_slot entries with appropriate name, id, and attr
216 * 'itr' will point to a next entry
219 fill_dir_slot(fat_itr *itr, const char *l_name)
221 __u8 temp_dir_slot_buffer[MAX_LFN_SLOT * sizeof(dir_slot)];
222 dir_slot *slotptr = (dir_slot *)temp_dir_slot_buffer;
223 __u8 counter = 0, checksum;
226 /* Get short file name checksum value */
227 checksum = mkcksum(itr->dent->name, itr->dent->ext);
230 memset(slotptr, 0x00, sizeof(dir_slot));
231 ret = str2slot(slotptr, l_name, &idx);
232 slotptr->id = ++counter;
233 slotptr->attr = ATTR_VFAT;
234 slotptr->alias_checksum = checksum;
239 slotptr->id |= LAST_LONG_ENTRY_MASK;
241 while (counter >= 1) {
242 memcpy(itr->dent, slotptr, sizeof(dir_slot));
245 if (!fat_itr_next(itr))
246 if (!itr->dent && !itr->is_root && flush_dir_table(itr))
250 if (!itr->dent && !itr->is_root)
252 * don't care return value here because we have already
253 * finished completing an entry with name, only ending up
256 flush_dir_table(itr);
262 * Set the entry at index 'entry' in a FAT (12/16/32) table.
264 static int set_fatent_value(fsdata *mydata, __u32 entry, __u32 entry_value)
266 __u32 bufnum, offset, off16;
269 switch (mydata->fatsize) {
271 bufnum = entry / FAT32BUFSIZE;
272 offset = entry - bufnum * FAT32BUFSIZE;
275 bufnum = entry / FAT16BUFSIZE;
276 offset = entry - bufnum * FAT16BUFSIZE;
279 bufnum = entry / FAT12BUFSIZE;
280 offset = entry - bufnum * FAT12BUFSIZE;
283 /* Unsupported FAT size */
287 /* Read a new block of FAT entries into the cache. */
288 if (bufnum != mydata->fatbufnum) {
289 int getsize = FATBUFBLOCKS;
290 __u8 *bufptr = mydata->fatbuf;
291 __u32 fatlength = mydata->fatlength;
292 __u32 startblock = bufnum * FATBUFBLOCKS;
294 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
295 if (startblock + getsize > fatlength)
296 getsize = fatlength - startblock;
298 if (flush_dirty_fat_buffer(mydata) < 0)
301 startblock += mydata->fat_sect;
303 if (disk_read(startblock, getsize, bufptr) < 0) {
304 debug("Error reading FAT blocks\n");
307 mydata->fatbufnum = bufnum;
311 mydata->fat_dirty = 1;
313 /* Set the actual entry */
314 switch (mydata->fatsize) {
316 ((__u32 *) mydata->fatbuf)[offset] = cpu_to_le32(entry_value);
319 ((__u16 *) mydata->fatbuf)[offset] = cpu_to_le16(entry_value);
322 off16 = (offset * 3) / 4;
324 switch (offset & 0x3) {
326 val1 = cpu_to_le16(entry_value) & 0xfff;
327 ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff;
328 ((__u16 *)mydata->fatbuf)[off16] |= val1;
331 val1 = cpu_to_le16(entry_value) & 0xf;
332 val2 = (cpu_to_le16(entry_value) >> 4) & 0xff;
334 ((__u16 *)mydata->fatbuf)[off16] &= ~0xf000;
335 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 12);
337 ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xff;
338 ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
341 val1 = cpu_to_le16(entry_value) & 0xff;
342 val2 = (cpu_to_le16(entry_value) >> 8) & 0xf;
344 ((__u16 *)mydata->fatbuf)[off16] &= ~0xff00;
345 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 8);
347 ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xf;
348 ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
351 val1 = cpu_to_le16(entry_value) & 0xfff;
352 ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff0;
353 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 4);
368 * Determine the next free cluster after 'entry' in a FAT (12/16/32) table
369 * and link it to 'entry'. EOC marker is not set on returned entry.
371 static __u32 determine_fatent(fsdata *mydata, __u32 entry)
373 __u32 next_fat, next_entry = entry + 1;
376 next_fat = get_fatent(mydata, next_entry);
378 /* found free entry, link to entry */
379 set_fatent_value(mydata, entry, next_entry);
384 debug("FAT%d: entry: %08x, entry_value: %04x\n",
385 mydata->fatsize, entry, next_entry);
391 * Write at most 'size' bytes from 'buffer' into the specified cluster.
392 * Return 0 on success, -1 otherwise.
395 set_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer,
403 startsect = clust_to_sect(mydata, clustnum);
405 startsect = mydata->rootdir_sect;
407 debug("clustnum: %d, startsect: %d\n", clustnum, startsect);
409 if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
410 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
412 printf("FAT: Misaligned buffer address (%p)\n", buffer);
414 while (size >= mydata->sect_size) {
415 memcpy(tmpbuf, buffer, mydata->sect_size);
416 ret = disk_write(startsect++, 1, tmpbuf);
418 debug("Error writing data (got %d)\n", ret);
422 buffer += mydata->sect_size;
423 size -= mydata->sect_size;
425 } else if (size >= mydata->sect_size) {
426 idx = size / mydata->sect_size;
427 ret = disk_write(startsect, idx, buffer);
429 debug("Error writing data (got %d)\n", ret);
434 idx *= mydata->sect_size;
440 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
442 memcpy(tmpbuf, buffer, size);
443 ret = disk_write(startsect, 1, tmpbuf);
445 debug("Error writing data (got %d)\n", ret);
454 * Find the first empty cluster
456 static int find_empty_cluster(fsdata *mydata)
458 __u32 fat_val, entry = 3;
461 fat_val = get_fatent(mydata, entry);
471 * Write directory entries in itr's buffer to block device
473 static int flush_dir_table(fat_itr *itr)
475 fsdata *mydata = itr->fsdata;
476 int dir_newclust = 0;
477 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
479 if (set_cluster(mydata, itr->clust, itr->block, bytesperclust) != 0) {
480 printf("error: writing directory entry\n");
483 dir_newclust = find_empty_cluster(mydata);
484 set_fatent_value(mydata, itr->clust, dir_newclust);
485 if (mydata->fatsize == 32)
486 set_fatent_value(mydata, dir_newclust, 0xffffff8);
487 else if (mydata->fatsize == 16)
488 set_fatent_value(mydata, dir_newclust, 0xfff8);
489 else if (mydata->fatsize == 12)
490 set_fatent_value(mydata, dir_newclust, 0xff8);
492 itr->clust = dir_newclust;
493 itr->next_clust = dir_newclust;
495 if (flush_dirty_fat_buffer(mydata) < 0)
498 memset(itr->block, 0x00, bytesperclust);
500 itr->dent = (dir_entry *)itr->block;
501 itr->last_cluster = 1;
502 itr->remaining = bytesperclust / sizeof(dir_entry) - 1;
508 * Set empty cluster from 'entry' to the end of a file
510 static int clear_fatent(fsdata *mydata, __u32 entry)
514 while (!CHECK_CLUST(entry, mydata->fatsize)) {
515 fat_val = get_fatent(mydata, entry);
517 set_fatent_value(mydata, entry, 0);
524 /* Flush fat buffer */
525 if (flush_dirty_fat_buffer(mydata) < 0)
532 * Write at most 'maxsize' bytes from 'buffer' into
533 * the file associated with 'dentptr'
534 * Update the number of bytes written in *gotsize and return 0
535 * or return -1 on fatal errors.
538 set_contents(fsdata *mydata, dir_entry *dentptr, __u8 *buffer,
539 loff_t maxsize, loff_t *gotsize)
541 loff_t filesize = FAT2CPU32(dentptr->size);
542 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
543 __u32 curclust = START(dentptr);
544 __u32 endclust = 0, newclust = 0;
548 debug("Filesize: %llu bytes\n", filesize);
550 if (maxsize > 0 && filesize > maxsize)
553 debug("%llu bytes\n", filesize);
557 debug("error: nonempty clusterless file!\n");
563 actsize = bytesperclust;
566 /* search for consecutive clusters */
567 while (actsize < filesize) {
568 newclust = determine_fatent(mydata, endclust);
570 if ((newclust - 1) != endclust)
573 if (CHECK_CLUST(newclust, mydata->fatsize)) {
574 debug("newclust: 0x%x\n", newclust);
575 debug("Invalid FAT entry\n");
579 actsize += bytesperclust;
582 /* set remaining bytes */
584 if (set_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
585 debug("error: writing cluster\n");
590 /* Mark end of file in FAT */
591 if (mydata->fatsize == 12)
593 else if (mydata->fatsize == 16)
595 else if (mydata->fatsize == 32)
596 newclust = 0xfffffff;
597 set_fatent_value(mydata, endclust, newclust);
601 if (set_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
602 debug("error: writing cluster\n");
609 if (CHECK_CLUST(newclust, mydata->fatsize)) {
610 debug("newclust: 0x%x\n", newclust);
611 debug("Invalid FAT entry\n");
614 actsize = bytesperclust;
615 curclust = endclust = newclust;
620 * Set start cluster in directory entry
622 static void set_start_cluster(const fsdata *mydata, dir_entry *dentptr,
625 if (mydata->fatsize == 32)
627 cpu_to_le16((start_cluster & 0xffff0000) >> 16);
628 dentptr->start = cpu_to_le16(start_cluster & 0xffff);
634 static void fill_dentry(fsdata *mydata, dir_entry *dentptr,
635 const char *filename, __u32 start_cluster, __u32 size, __u8 attr)
637 set_start_cluster(mydata, dentptr, start_cluster);
638 dentptr->size = cpu_to_le32(size);
640 dentptr->attr = attr;
642 set_name(dentptr, filename);
646 * Check whether adding a file makes the file system to
647 * exceed the size of the block device
648 * Return -1 when overflow occurs, otherwise return 0
650 static int check_overflow(fsdata *mydata, __u32 clustnum, loff_t size)
652 __u32 startsect, sect_num, offset;
655 startsect = clust_to_sect(mydata, clustnum);
657 startsect = mydata->rootdir_sect;
660 sect_num = div_u64_rem(size, mydata->sect_size, &offset);
665 if (startsect + sect_num > total_sector)
671 * Find a directory entry based on filename or start cluster number
672 * If the directory entry is not found,
673 * the new position for writing a directory entry will be returned
675 static dir_entry *find_directory_entry(fat_itr *itr, char *filename)
679 while (fat_itr_next(itr)) {
680 /* check both long and short name: */
681 if (!strcasecmp(filename, itr->name))
683 else if (itr->name != itr->s_name &&
684 !strcasecmp(filename, itr->s_name))
690 if (itr->dent->name[0] == '\0')
696 if (!itr->dent && !itr->is_root && flush_dir_table(itr))
697 /* indicate that allocating dent failed */
703 static int split_filename(char *filename, char **dirname, char **basename)
705 char *p, *last_slash, *last_slash_cont;
710 last_slash_cont = NULL;
712 if (ISDIRDELIM(*p)) {
715 /* continuous slashes */
716 while (ISDIRDELIM(*p))
717 last_slash_cont = p++;
725 if (last_slash_cont == (filename + strlen(filename) - 1)) {
726 /* remove trailing slashes */
731 if (last_slash == filename) {
732 /* avoid ""(null) directory */
739 *last_slash_cont = '\0';
740 *basename = last_slash_cont + 1;
742 *dirname = "/"; /* root by default */
743 *basename = filename;
749 static int normalize_longname(char *l_filename, const char *filename)
751 const char *p, legal[] = "!#$%&\'()-.@^`_{}~";
755 /* Check that the filename is valid */
756 for (p = filename; p < filename + strlen(filename); p++) {
759 if (('0' <= c) && (c <= '9'))
761 if (('A' <= c) && (c <= 'Z'))
763 if (('a' <= c) && (c <= 'z'))
765 if (strchr(legal, c))
768 if ((0x80 <= c) && (c <= 0xff))
775 name_len = strlen(filename);
776 if (name_len >= VFAT_MAXLEN_BYTES)
777 /* should return an error? */
778 name_len = VFAT_MAXLEN_BYTES - 1;
780 memcpy(l_filename, filename, name_len);
781 l_filename[name_len] = 0; /* terminate the string */
782 downcase(l_filename, INT_MAX);
787 static int do_fat_write(const char *filename, void *buffer, loff_t size,
792 fsdata datablock = { .fatbuf = NULL, };
793 fsdata *mydata = &datablock;
796 char *filename_copy, *parent, *basename;
797 char l_filename[VFAT_MAXLEN_BYTES];
799 filename_copy = strdup(filename);
803 split_filename(filename_copy, &parent, &basename);
804 if (!strlen(basename)) {
810 if (normalize_longname(l_filename, filename)) {
811 printf("FAT: illegal filename (%s)\n", filename);
816 itr = malloc_cache_aligned(sizeof(fat_itr));
822 ret = fat_itr_root(itr, &datablock);
826 total_sector = datablock.total_sect;
828 ret = fat_itr_resolve(itr, parent, TYPE_DIR);
830 printf("%s: doesn't exist (%d)\n", parent, ret);
834 retdent = find_directory_entry(itr, l_filename);
837 if (fat_itr_isdir(itr)) {
842 /* Update file size and start_cluster in a directory entry */
843 retdent->size = cpu_to_le32(size);
844 start_cluster = START(retdent);
848 ret = check_overflow(mydata, start_cluster,
851 printf("Error: %llu overflow\n", size);
857 ret = clear_fatent(mydata, start_cluster);
859 printf("Error: clearing FAT entries\n");
865 set_start_cluster(mydata, retdent, 0);
867 ret = start_cluster = find_empty_cluster(mydata);
869 printf("Error: finding empty cluster\n");
874 ret = check_overflow(mydata, start_cluster, size);
876 printf("Error: %llu overflow\n", size);
881 set_start_cluster(mydata, retdent, start_cluster);
884 /* Create a new file */
887 /* root dir cannot have "." or ".." */
888 if (!strcmp(l_filename, ".") ||
889 !strcmp(l_filename, "..")) {
896 printf("Error: allocating new dir entry\n");
901 memset(itr->dent, 0, sizeof(*itr->dent));
903 /* Set short name to set alias checksum field in dir_slot */
904 set_name(itr->dent, filename);
905 if (fill_dir_slot(itr, filename)) {
911 ret = start_cluster = find_empty_cluster(mydata);
913 printf("Error: finding empty cluster\n");
918 ret = check_overflow(mydata, start_cluster, size);
920 printf("Error: %llu overflow\n", size);
928 /* Set attribute as archive for regular file */
929 fill_dentry(itr->fsdata, itr->dent, filename,
930 start_cluster, size, 0x20);
935 ret = set_contents(mydata, retdent, buffer, size, actwrite);
937 printf("Error: writing contents\n");
941 debug("attempt to write 0x%llx bytes\n", *actwrite);
943 /* Flush fat buffer */
944 ret = flush_dirty_fat_buffer(mydata);
946 printf("Error: flush fat buffer\n");
951 /* Write directory table to device */
952 ret = set_cluster(mydata, itr->clust, itr->block,
953 mydata->clust_size * mydata->sect_size);
955 printf("Error: writing directory entry\n");
961 free(mydata->fatbuf);
966 int file_fat_write(const char *filename, void *buffer, loff_t offset,
967 loff_t maxsize, loff_t *actwrite)
970 printf("Error: non zero offset is currently not supported.\n");
974 printf("writing %s\n", filename);
975 return do_fat_write(filename, buffer, maxsize, actwrite);