fs: fat: refactor write interface for a file offset
[platform/kernel/u-boot.git] / fs / fat / fat_write.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * fat_write.c
4  *
5  * R/W (V)FAT 12/16/32 filesystem implementation by Donggeun Kim
6  */
7
8 #include <common.h>
9 #include <command.h>
10 #include <config.h>
11 #include <fat.h>
12 #include <asm/byteorder.h>
13 #include <part.h>
14 #include <linux/ctype.h>
15 #include <div64.h>
16 #include <linux/math64.h>
17 #include "fat.c"
18
19 static void uppercase(char *str, int len)
20 {
21         int i;
22
23         for (i = 0; i < len; i++) {
24                 *str = toupper(*str);
25                 str++;
26         }
27 }
28
29 static int total_sector;
30 static int disk_write(__u32 block, __u32 nr_blocks, void *buf)
31 {
32         ulong ret;
33
34         if (!cur_dev)
35                 return -1;
36
37         if (cur_part_info.start + block + nr_blocks >
38                 cur_part_info.start + total_sector) {
39                 printf("error: overflow occurs\n");
40                 return -1;
41         }
42
43         ret = blk_dwrite(cur_dev, cur_part_info.start + block, nr_blocks, buf);
44         if (nr_blocks && ret == 0)
45                 return -1;
46
47         return ret;
48 }
49
50 /*
51  * Set short name in directory entry
52  */
53 static void set_name(dir_entry *dirent, const char *filename)
54 {
55         char s_name[VFAT_MAXLEN_BYTES];
56         char *period;
57         int period_location, len, i, ext_num;
58
59         if (filename == NULL)
60                 return;
61
62         len = strlen(filename);
63         if (len == 0)
64                 return;
65
66         strcpy(s_name, filename);
67         uppercase(s_name, len);
68
69         period = strchr(s_name, '.');
70         if (period == NULL) {
71                 period_location = len;
72                 ext_num = 0;
73         } else {
74                 period_location = period - s_name;
75                 ext_num = len - period_location - 1;
76         }
77
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);
85         } else {
86                 memcpy(dirent->name, s_name, 6);
87                 dirent->name[6] = '~';
88                 dirent->name[7] = '1';
89         }
90
91         if (ext_num < 3) {
92                 memcpy(dirent->ext, s_name + period_location + 1, ext_num);
93                 for (i = ext_num; i < 3; i++)
94                         dirent->ext[i] = ' ';
95         } else
96                 memcpy(dirent->ext, s_name + period_location + 1, 3);
97
98         debug("name : %s\n", dirent->name);
99         debug("ext : %s\n", dirent->ext);
100 }
101
102 /*
103  * Write fat buffer into block device
104  */
105 static int flush_dirty_fat_buffer(fsdata *mydata)
106 {
107         int getsize = FATBUFBLOCKS;
108         __u32 fatlength = mydata->fatlength;
109         __u8 *bufptr = mydata->fatbuf;
110         __u32 startblock = mydata->fatbufnum * FATBUFBLOCKS;
111
112         debug("debug: evicting %d, dirty: %d\n", mydata->fatbufnum,
113               (int)mydata->fat_dirty);
114
115         if ((!mydata->fat_dirty) || (mydata->fatbufnum == -1))
116                 return 0;
117
118         /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
119         if (startblock + getsize > fatlength)
120                 getsize = fatlength - startblock;
121
122         startblock += mydata->fat_sect;
123
124         /* Write FAT buf */
125         if (disk_write(startblock, getsize, bufptr) < 0) {
126                 debug("error: writing FAT blocks\n");
127                 return -1;
128         }
129
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");
135                         return -1;
136                 }
137         }
138         mydata->fat_dirty = 0;
139
140         return 0;
141 }
142
143 /*
144  * Set the file name information from 'name' into 'slotptr',
145  */
146 static int str2slot(dir_slot *slotptr, const char *name, int *idx)
147 {
148         int j, end_idx = 0;
149
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;
154                         end_idx++;
155                         goto name0_4;
156                 }
157                 slotptr->name0_4[j] = name[*idx];
158                 (*idx)++;
159                 end_idx++;
160         }
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;
165                         end_idx++;
166                         goto name5_10;
167                 }
168                 slotptr->name5_10[j] = name[*idx];
169                 (*idx)++;
170                 end_idx++;
171         }
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;
176                         end_idx++;
177                         goto name11_12;
178                 }
179                 slotptr->name11_12[j] = name[*idx];
180                 (*idx)++;
181                 end_idx++;
182         }
183
184         if (name[*idx] == 0x00)
185                 return 1;
186
187         return 0;
188 /* Not used characters are filled with 0xff 0xff */
189 name0_4:
190         for (; end_idx < 5; end_idx++) {
191                 slotptr->name0_4[end_idx * 2] = 0xff;
192                 slotptr->name0_4[end_idx * 2 + 1] = 0xff;
193         }
194         end_idx = 5;
195 name5_10:
196         end_idx -= 5;
197         for (; end_idx < 6; end_idx++) {
198                 slotptr->name5_10[end_idx * 2] = 0xff;
199                 slotptr->name5_10[end_idx * 2 + 1] = 0xff;
200         }
201         end_idx = 11;
202 name11_12:
203         end_idx -= 11;
204         for (; end_idx < 2; end_idx++) {
205                 slotptr->name11_12[end_idx * 2] = 0xff;
206                 slotptr->name11_12[end_idx * 2 + 1] = 0xff;
207         }
208
209         return 1;
210 }
211
212 static int flush_dir_table(fat_itr *itr);
213
214 /*
215  * Fill dir_slot entries with appropriate name, id, and attr
216  * 'itr' will point to a next entry
217  */
218 static int
219 fill_dir_slot(fat_itr *itr, const char *l_name)
220 {
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;
224         int idx = 0, ret;
225
226         /* Get short file name checksum value */
227         checksum = mkcksum(itr->dent->name, itr->dent->ext);
228
229         do {
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;
235                 slotptr++;
236         } while (ret == 0);
237
238         slotptr--;
239         slotptr->id |= LAST_LONG_ENTRY_MASK;
240
241         while (counter >= 1) {
242                 memcpy(itr->dent, slotptr, sizeof(dir_slot));
243                 slotptr--;
244                 counter--;
245                 if (!fat_itr_next(itr))
246                         if (!itr->dent && !itr->is_root && flush_dir_table(itr))
247                                 return -1;
248         }
249
250         if (!itr->dent && !itr->is_root)
251                 /*
252                  * don't care return value here because we have already
253                  * finished completing an entry with name, only ending up
254                  * no more entry left
255                  */
256                 flush_dir_table(itr);
257
258         return 0;
259 }
260
261 /*
262  * Set the entry at index 'entry' in a FAT (12/16/32) table.
263  */
264 static int set_fatent_value(fsdata *mydata, __u32 entry, __u32 entry_value)
265 {
266         __u32 bufnum, offset, off16;
267         __u16 val1, val2;
268
269         switch (mydata->fatsize) {
270         case 32:
271                 bufnum = entry / FAT32BUFSIZE;
272                 offset = entry - bufnum * FAT32BUFSIZE;
273                 break;
274         case 16:
275                 bufnum = entry / FAT16BUFSIZE;
276                 offset = entry - bufnum * FAT16BUFSIZE;
277                 break;
278         case 12:
279                 bufnum = entry / FAT12BUFSIZE;
280                 offset = entry - bufnum * FAT12BUFSIZE;
281                 break;
282         default:
283                 /* Unsupported FAT size */
284                 return -1;
285         }
286
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;
293
294                 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
295                 if (startblock + getsize > fatlength)
296                         getsize = fatlength - startblock;
297
298                 if (flush_dirty_fat_buffer(mydata) < 0)
299                         return -1;
300
301                 startblock += mydata->fat_sect;
302
303                 if (disk_read(startblock, getsize, bufptr) < 0) {
304                         debug("Error reading FAT blocks\n");
305                         return -1;
306                 }
307                 mydata->fatbufnum = bufnum;
308         }
309
310         /* Mark as dirty */
311         mydata->fat_dirty = 1;
312
313         /* Set the actual entry */
314         switch (mydata->fatsize) {
315         case 32:
316                 ((__u32 *) mydata->fatbuf)[offset] = cpu_to_le32(entry_value);
317                 break;
318         case 16:
319                 ((__u16 *) mydata->fatbuf)[offset] = cpu_to_le16(entry_value);
320                 break;
321         case 12:
322                 off16 = (offset * 3) / 4;
323
324                 switch (offset & 0x3) {
325                 case 0:
326                         val1 = cpu_to_le16(entry_value) & 0xfff;
327                         ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff;
328                         ((__u16 *)mydata->fatbuf)[off16] |= val1;
329                         break;
330                 case 1:
331                         val1 = cpu_to_le16(entry_value) & 0xf;
332                         val2 = (cpu_to_le16(entry_value) >> 4) & 0xff;
333
334                         ((__u16 *)mydata->fatbuf)[off16] &= ~0xf000;
335                         ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 12);
336
337                         ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xff;
338                         ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
339                         break;
340                 case 2:
341                         val1 = cpu_to_le16(entry_value) & 0xff;
342                         val2 = (cpu_to_le16(entry_value) >> 8) & 0xf;
343
344                         ((__u16 *)mydata->fatbuf)[off16] &= ~0xff00;
345                         ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 8);
346
347                         ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xf;
348                         ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
349                         break;
350                 case 3:
351                         val1 = cpu_to_le16(entry_value) & 0xfff;
352                         ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff0;
353                         ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 4);
354                         break;
355                 default:
356                         break;
357                 }
358
359                 break;
360         default:
361                 return -1;
362         }
363
364         return 0;
365 }
366
367 /*
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.
370  */
371 static __u32 determine_fatent(fsdata *mydata, __u32 entry)
372 {
373         __u32 next_fat, next_entry = entry + 1;
374
375         while (1) {
376                 next_fat = get_fatent(mydata, next_entry);
377                 if (next_fat == 0) {
378                         /* found free entry, link to entry */
379                         set_fatent_value(mydata, entry, next_entry);
380                         break;
381                 }
382                 next_entry++;
383         }
384         debug("FAT%d: entry: %08x, entry_value: %04x\n",
385                mydata->fatsize, entry, next_entry);
386
387         return next_entry;
388 }
389
390 /*
391  * Write at most 'size' bytes from 'buffer' into the specified cluster.
392  * Return 0 on success, -1 otherwise.
393  */
394 static int
395 set_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer,
396              unsigned long size)
397 {
398         __u32 idx = 0;
399         __u32 startsect;
400         int ret;
401
402         if (clustnum > 0)
403                 startsect = clust_to_sect(mydata, clustnum);
404         else
405                 startsect = mydata->rootdir_sect;
406
407         debug("clustnum: %d, startsect: %d\n", clustnum, startsect);
408
409         if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
410                 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
411
412                 printf("FAT: Misaligned buffer address (%p)\n", buffer);
413
414                 while (size >= mydata->sect_size) {
415                         memcpy(tmpbuf, buffer, mydata->sect_size);
416                         ret = disk_write(startsect++, 1, tmpbuf);
417                         if (ret != 1) {
418                                 debug("Error writing data (got %d)\n", ret);
419                                 return -1;
420                         }
421
422                         buffer += mydata->sect_size;
423                         size -= mydata->sect_size;
424                 }
425         } else if (size >= mydata->sect_size) {
426                 idx = size / mydata->sect_size;
427                 ret = disk_write(startsect, idx, buffer);
428                 if (ret != idx) {
429                         debug("Error writing data (got %d)\n", ret);
430                         return -1;
431                 }
432
433                 startsect += idx;
434                 idx *= mydata->sect_size;
435                 buffer += idx;
436                 size -= idx;
437         }
438
439         if (size) {
440                 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
441
442                 memcpy(tmpbuf, buffer, size);
443                 ret = disk_write(startsect, 1, tmpbuf);
444                 if (ret != 1) {
445                         debug("Error writing data (got %d)\n", ret);
446                         return -1;
447                 }
448         }
449
450         return 0;
451 }
452
453 /*
454  * Find the first empty cluster
455  */
456 static int find_empty_cluster(fsdata *mydata)
457 {
458         __u32 fat_val, entry = 3;
459
460         while (1) {
461                 fat_val = get_fatent(mydata, entry);
462                 if (fat_val == 0)
463                         break;
464                 entry++;
465         }
466
467         return entry;
468 }
469
470 /*
471  * Write directory entries in itr's buffer to block device
472  */
473 static int flush_dir_table(fat_itr *itr)
474 {
475         fsdata *mydata = itr->fsdata;
476         int dir_newclust = 0;
477         unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
478
479         if (set_cluster(mydata, itr->clust, itr->block, bytesperclust) != 0) {
480                 printf("error: writing directory entry\n");
481                 return -1;
482         }
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);
491
492         itr->clust = dir_newclust;
493         itr->next_clust = dir_newclust;
494
495         if (flush_dirty_fat_buffer(mydata) < 0)
496                 return -1;
497
498         memset(itr->block, 0x00, bytesperclust);
499
500         itr->dent = (dir_entry *)itr->block;
501         itr->last_cluster = 1;
502         itr->remaining = bytesperclust / sizeof(dir_entry) - 1;
503
504         return 0;
505 }
506
507 /*
508  * Set empty cluster from 'entry' to the end of a file
509  */
510 static int clear_fatent(fsdata *mydata, __u32 entry)
511 {
512         __u32 fat_val;
513
514         while (!CHECK_CLUST(entry, mydata->fatsize)) {
515                 fat_val = get_fatent(mydata, entry);
516                 if (fat_val != 0)
517                         set_fatent_value(mydata, entry, 0);
518                 else
519                         break;
520
521                 entry = fat_val;
522         }
523
524         /* Flush fat buffer */
525         if (flush_dirty_fat_buffer(mydata) < 0)
526                 return -1;
527
528         return 0;
529 }
530
531 /*
532  * Set start cluster in directory entry
533  */
534 static void set_start_cluster(const fsdata *mydata, dir_entry *dentptr,
535                               __u32 start_cluster)
536 {
537         if (mydata->fatsize == 32)
538                 dentptr->starthi =
539                         cpu_to_le16((start_cluster & 0xffff0000) >> 16);
540         dentptr->start = cpu_to_le16(start_cluster & 0xffff);
541 }
542
543 /*
544  * Check whether adding a file makes the file system to
545  * exceed the size of the block device
546  * Return -1 when overflow occurs, otherwise return 0
547  */
548 static int check_overflow(fsdata *mydata, __u32 clustnum, loff_t size)
549 {
550         __u32 startsect, sect_num, offset;
551
552         if (clustnum > 0)
553                 startsect = clust_to_sect(mydata, clustnum);
554         else
555                 startsect = mydata->rootdir_sect;
556
557         sect_num = div_u64_rem(size, mydata->sect_size, &offset);
558
559         if (offset != 0)
560                 sect_num++;
561
562         if (startsect + sect_num > total_sector)
563                 return -1;
564         return 0;
565 }
566
567 /*
568  * Write at most 'maxsize' bytes from 'buffer' into
569  * the file associated with 'dentptr'
570  * Update the number of bytes written in *gotsize and return 0
571  * or return -1 on fatal errors.
572  */
573 static int
574 set_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos, __u8 *buffer,
575              loff_t maxsize, loff_t *gotsize)
576 {
577         loff_t filesize;
578         unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
579         __u32 curclust = START(dentptr);
580         __u32 endclust = 0, newclust = 0;
581         loff_t actsize;
582
583         *gotsize = 0;
584         filesize = maxsize;
585
586         debug("%llu bytes\n", filesize);
587
588         if (curclust) {
589                 /*
590                  * release already-allocated clusters anyway
591                  */
592                 if (clear_fatent(mydata, curclust)) {
593                         printf("Error: clearing FAT entries\n");
594                         return -1;
595                 }
596         }
597
598         curclust = find_empty_cluster(mydata);
599         set_start_cluster(mydata, dentptr, curclust);
600
601         if (check_overflow(mydata, curclust, filesize)) {
602                 printf("Error: no space left: %llu\n", filesize);
603                 return -1;
604         }
605
606         actsize = bytesperclust;
607         endclust = curclust;
608         do {
609                 /* search for consecutive clusters */
610                 while (actsize < filesize) {
611                         newclust = determine_fatent(mydata, endclust);
612
613                         if ((newclust - 1) != endclust)
614                                 /* write to <curclust..endclust> */
615                                 goto getit;
616
617                         if (CHECK_CLUST(newclust, mydata->fatsize)) {
618                                 debug("newclust: 0x%x\n", newclust);
619                                 debug("Invalid FAT entry\n");
620                                 return 0;
621                         }
622                         endclust = newclust;
623                         actsize += bytesperclust;
624                 }
625
626                 /* set remaining bytes */
627                 actsize = filesize;
628                 if (set_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
629                         debug("error: writing cluster\n");
630                         return -1;
631                 }
632                 *gotsize += actsize;
633
634                 /* Mark end of file in FAT */
635                 if (mydata->fatsize == 12)
636                         newclust = 0xfff;
637                 else if (mydata->fatsize == 16)
638                         newclust = 0xffff;
639                 else if (mydata->fatsize == 32)
640                         newclust = 0xfffffff;
641                 set_fatent_value(mydata, endclust, newclust);
642
643                 return 0;
644 getit:
645                 if (set_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
646                         debug("error: writing cluster\n");
647                         return -1;
648                 }
649                 *gotsize += actsize;
650                 filesize -= actsize;
651                 buffer += actsize;
652
653                 if (CHECK_CLUST(newclust, mydata->fatsize)) {
654                         debug("newclust: 0x%x\n", newclust);
655                         debug("Invalid FAT entry\n");
656                         return 0;
657                 }
658                 actsize = bytesperclust;
659                 curclust = endclust = newclust;
660         } while (1);
661
662         return 0;
663 }
664
665 /*
666  * Fill dir_entry
667  */
668 static void fill_dentry(fsdata *mydata, dir_entry *dentptr,
669         const char *filename, __u32 start_cluster, __u32 size, __u8 attr)
670 {
671         set_start_cluster(mydata, dentptr, start_cluster);
672         dentptr->size = cpu_to_le32(size);
673
674         dentptr->attr = attr;
675
676         set_name(dentptr, filename);
677 }
678
679 /*
680  * Find a directory entry based on filename or start cluster number
681  * If the directory entry is not found,
682  * the new position for writing a directory entry will be returned
683  */
684 static dir_entry *find_directory_entry(fat_itr *itr, char *filename)
685 {
686         int match = 0;
687
688         while (fat_itr_next(itr)) {
689                 /* check both long and short name: */
690                 if (!strcasecmp(filename, itr->name))
691                         match = 1;
692                 else if (itr->name != itr->s_name &&
693                          !strcasecmp(filename, itr->s_name))
694                         match = 1;
695
696                 if (!match)
697                         continue;
698
699                 if (itr->dent->name[0] == '\0')
700                         return NULL;
701                 else
702                         return itr->dent;
703         }
704
705         if (!itr->dent && !itr->is_root && flush_dir_table(itr))
706                 /* indicate that allocating dent failed */
707                 itr->dent = NULL;
708
709         return NULL;
710 }
711
712 static int split_filename(char *filename, char **dirname, char **basename)
713 {
714         char *p, *last_slash, *last_slash_cont;
715
716 again:
717         p = filename;
718         last_slash = NULL;
719         last_slash_cont = NULL;
720         while (*p) {
721                 if (ISDIRDELIM(*p)) {
722                         last_slash = p;
723                         last_slash_cont = p;
724                         /* continuous slashes */
725                         while (ISDIRDELIM(*p))
726                                 last_slash_cont = p++;
727                         if (!*p)
728                                 break;
729                 }
730                 p++;
731         }
732
733         if (last_slash) {
734                 if (last_slash_cont == (filename + strlen(filename) - 1)) {
735                         /* remove trailing slashes */
736                         *last_slash = '\0';
737                         goto again;
738                 }
739
740                 if (last_slash == filename) {
741                         /* avoid ""(null) directory */
742                         *dirname = "/";
743                 } else {
744                         *last_slash = '\0';
745                         *dirname = filename;
746                 }
747
748                 *last_slash_cont = '\0';
749                 *basename = last_slash_cont + 1;
750         } else {
751                 *dirname = "/"; /* root by default */
752                 *basename = filename;
753         }
754
755         return 0;
756 }
757
758 static int normalize_longname(char *l_filename, const char *filename)
759 {
760         const char *p, legal[] = "!#$%&\'()-.@^`_{}~";
761         char c;
762         int name_len;
763
764         /* Check that the filename is valid */
765         for (p = filename; p < filename + strlen(filename); p++) {
766                 c = *p;
767
768                 if (('0' <= c) && (c <= '9'))
769                         continue;
770                 if (('A' <= c) && (c <= 'Z'))
771                         continue;
772                 if (('a' <= c) && (c <= 'z'))
773                         continue;
774                 if (strchr(legal, c))
775                         continue;
776                 /* extended code */
777                 if ((0x80 <= c) && (c <= 0xff))
778                         continue;
779
780                 return -1;
781         }
782
783         /* Normalize it */
784         name_len = strlen(filename);
785         if (name_len >= VFAT_MAXLEN_BYTES)
786                 /* should return an error? */
787                 name_len = VFAT_MAXLEN_BYTES - 1;
788
789         memcpy(l_filename, filename, name_len);
790         l_filename[name_len] = 0; /* terminate the string */
791         downcase(l_filename, INT_MAX);
792
793         return 0;
794 }
795
796 int file_fat_write_at(const char *filename, loff_t pos, void *buffer,
797                       loff_t size, loff_t *actwrite)
798 {
799         dir_entry *retdent;
800         fsdata datablock = { .fatbuf = NULL, };
801         fsdata *mydata = &datablock;
802         fat_itr *itr = NULL;
803         int ret = -1;
804         char *filename_copy, *parent, *basename;
805         char l_filename[VFAT_MAXLEN_BYTES];
806
807         debug("writing %s\n", filename);
808
809         filename_copy = strdup(filename);
810         if (!filename_copy)
811                 return -ENOMEM;
812
813         split_filename(filename_copy, &parent, &basename);
814         if (!strlen(basename)) {
815                 ret = -EINVAL;
816                 goto exit;
817         }
818
819         filename = basename;
820         if (normalize_longname(l_filename, filename)) {
821                 printf("FAT: illegal filename (%s)\n", filename);
822                 ret = -EINVAL;
823                 goto exit;
824         }
825
826         itr = malloc_cache_aligned(sizeof(fat_itr));
827         if (!itr) {
828                 ret = -ENOMEM;
829                 goto exit;
830         }
831
832         ret = fat_itr_root(itr, &datablock);
833         if (ret)
834                 goto exit;
835
836         total_sector = datablock.total_sect;
837
838         ret = fat_itr_resolve(itr, parent, TYPE_DIR);
839         if (ret) {
840                 printf("%s: doesn't exist (%d)\n", parent, ret);
841                 goto exit;
842         }
843
844         retdent = find_directory_entry(itr, l_filename);
845
846         if (retdent) {
847                 if (fat_itr_isdir(itr)) {
848                         ret = -EISDIR;
849                         goto exit;
850                 }
851
852                 /* Update file size in a directory entry */
853                 retdent->size = cpu_to_le32(pos + size);
854         } else {
855                 /* Create a new file */
856
857                 if (itr->is_root) {
858                         /* root dir cannot have "." or ".." */
859                         if (!strcmp(l_filename, ".") ||
860                             !strcmp(l_filename, "..")) {
861                                 ret = -EINVAL;
862                                 goto exit;
863                         }
864                 }
865
866                 if (!itr->dent) {
867                         printf("Error: allocating new dir entry\n");
868                         ret = -EIO;
869                         goto exit;
870                 }
871
872                 memset(itr->dent, 0, sizeof(*itr->dent));
873
874                 /* Set short name to set alias checksum field in dir_slot */
875                 set_name(itr->dent, filename);
876                 if (fill_dir_slot(itr, filename)) {
877                         ret = -EIO;
878                         goto exit;
879                 }
880
881                 /* Set attribute as archive for regular file */
882                 fill_dentry(itr->fsdata, itr->dent, filename, 0, size, 0x20);
883
884                 retdent = itr->dent;
885         }
886
887         ret = set_contents(mydata, retdent, pos, buffer, size, actwrite);
888         if (ret < 0) {
889                 printf("Error: writing contents\n");
890                 ret = -EIO;
891                 goto exit;
892         }
893         debug("attempt to write 0x%llx bytes\n", *actwrite);
894
895         /* Flush fat buffer */
896         ret = flush_dirty_fat_buffer(mydata);
897         if (ret) {
898                 printf("Error: flush fat buffer\n");
899                 ret = -EIO;
900                 goto exit;
901         }
902
903         /* Write directory table to device */
904         ret = set_cluster(mydata, itr->clust, itr->block,
905                           mydata->clust_size * mydata->sect_size);
906         if (ret) {
907                 printf("Error: writing directory entry\n");
908                 ret = -EIO;
909         }
910
911 exit:
912         free(filename_copy);
913         free(mydata->fatbuf);
914         free(itr);
915         return ret;
916 }
917
918 int file_fat_write(const char *filename, void *buffer, loff_t offset,
919                    loff_t maxsize, loff_t *actwrite)
920 {
921         if (offset != 0) {
922                 printf("Error: non zero offset is currently not supported.\n");
923                 return -EINVAL;
924         }
925
926         return file_fat_write_at(filename, offset, buffer, maxsize, actwrite);
927 }