fat: fatwrite: fix the command for FAT12
[platform/kernel/u-boot.git] / fs / fat / fat_write.c
1 /*
2  * fat_write.c
3  *
4  * R/W (V)FAT 12/16/32 filesystem implementation by Donggeun Kim
5  *
6  * SPDX-License-Identifier:     GPL-2.0+
7  */
8
9 #include <common.h>
10 #include <command.h>
11 #include <config.h>
12 #include <fat.h>
13 #include <asm/byteorder.h>
14 #include <part.h>
15 #include <linux/ctype.h>
16 #include <div64.h>
17 #include <linux/math64.h>
18 #include "fat.c"
19
20 static void uppercase(char *str, int len)
21 {
22         int i;
23
24         for (i = 0; i < len; i++) {
25                 *str = toupper(*str);
26                 str++;
27         }
28 }
29
30 static int total_sector;
31 static int disk_write(__u32 block, __u32 nr_blocks, void *buf)
32 {
33         ulong ret;
34
35         if (!cur_dev)
36                 return -1;
37
38         if (cur_part_info.start + block + nr_blocks >
39                 cur_part_info.start + total_sector) {
40                 printf("error: overflow occurs\n");
41                 return -1;
42         }
43
44         ret = blk_dwrite(cur_dev, cur_part_info.start + block, nr_blocks, buf);
45         if (nr_blocks && ret == 0)
46                 return -1;
47
48         return ret;
49 }
50
51 /*
52  * Set short name in directory entry
53  */
54 static void set_name(dir_entry *dirent, const char *filename)
55 {
56         char s_name[VFAT_MAXLEN_BYTES];
57         char *period;
58         int period_location, len, i, ext_num;
59
60         if (filename == NULL)
61                 return;
62
63         len = strlen(filename);
64         if (len == 0)
65                 return;
66
67         strcpy(s_name, filename);
68         uppercase(s_name, len);
69
70         period = strchr(s_name, '.');
71         if (period == NULL) {
72                 period_location = len;
73                 ext_num = 0;
74         } else {
75                 period_location = period - s_name;
76                 ext_num = len - period_location - 1;
77         }
78
79         /* Pad spaces when the length of file name is shorter than eight */
80         if (period_location < 8) {
81                 memcpy(dirent->name, s_name, period_location);
82                 for (i = period_location; i < 8; i++)
83                         dirent->name[i] = ' ';
84         } else if (period_location == 8) {
85                 memcpy(dirent->name, s_name, period_location);
86         } else {
87                 memcpy(dirent->name, s_name, 6);
88                 dirent->name[6] = '~';
89                 dirent->name[7] = '1';
90         }
91
92         if (ext_num < 3) {
93                 memcpy(dirent->ext, s_name + period_location + 1, ext_num);
94                 for (i = ext_num; i < 3; i++)
95                         dirent->ext[i] = ' ';
96         } else
97                 memcpy(dirent->ext, s_name + period_location + 1, 3);
98
99         debug("name : %s\n", dirent->name);
100         debug("ext : %s\n", dirent->ext);
101 }
102
103 static __u8 num_of_fats;
104 /*
105  * Write fat buffer into block device
106  */
107 static int flush_dirty_fat_buffer(fsdata *mydata)
108 {
109         int getsize = FATBUFBLOCKS;
110         __u32 fatlength = mydata->fatlength;
111         __u8 *bufptr = mydata->fatbuf;
112         __u32 startblock = mydata->fatbufnum * FATBUFBLOCKS;
113
114         debug("debug: evicting %d, dirty: %d\n", mydata->fatbufnum,
115               (int)mydata->fat_dirty);
116
117         if ((!mydata->fat_dirty) || (mydata->fatbufnum == -1))
118                 return 0;
119
120         startblock += mydata->fat_sect;
121
122         if (getsize > fatlength)
123                 getsize = fatlength;
124
125         /* Write FAT buf */
126         if (disk_write(startblock, getsize, bufptr) < 0) {
127                 debug("error: writing FAT blocks\n");
128                 return -1;
129         }
130
131         if (num_of_fats == 2) {
132                 /* Update corresponding second FAT blocks */
133                 startblock += mydata->fatlength;
134                 if (disk_write(startblock, getsize, bufptr) < 0) {
135                         debug("error: writing second FAT blocks\n");
136                         return -1;
137                 }
138         }
139         mydata->fat_dirty = 0;
140
141         return 0;
142 }
143
144 /*
145  * Get the entry at index 'entry' in a FAT (12/16/32) table.
146  * On failure 0x00 is returned.
147  * When bufnum is changed, write back the previous fatbuf to the disk.
148  */
149 static __u32 get_fatent_value(fsdata *mydata, __u32 entry)
150 {
151         __u32 bufnum;
152         __u32 off16, offset;
153         __u32 ret = 0x00;
154         __u16 val1, val2;
155
156         if (CHECK_CLUST(entry, mydata->fatsize)) {
157                 printf("Error: Invalid FAT entry: 0x%08x\n", entry);
158                 return ret;
159         }
160
161         switch (mydata->fatsize) {
162         case 32:
163                 bufnum = entry / FAT32BUFSIZE;
164                 offset = entry - bufnum * FAT32BUFSIZE;
165                 break;
166         case 16:
167                 bufnum = entry / FAT16BUFSIZE;
168                 offset = entry - bufnum * FAT16BUFSIZE;
169                 break;
170         case 12:
171                 bufnum = entry / FAT12BUFSIZE;
172                 offset = entry - bufnum * FAT12BUFSIZE;
173                 break;
174
175         default:
176                 /* Unsupported FAT size */
177                 return ret;
178         }
179
180         debug("FAT%d: entry: 0x%04x = %d, offset: 0x%04x = %d\n",
181                mydata->fatsize, entry, entry, offset, offset);
182
183         /* Read a new block of FAT entries into the cache. */
184         if (bufnum != mydata->fatbufnum) {
185                 int getsize = FATBUFBLOCKS;
186                 __u8 *bufptr = mydata->fatbuf;
187                 __u32 fatlength = mydata->fatlength;
188                 __u32 startblock = bufnum * FATBUFBLOCKS;
189
190                 if (getsize > fatlength)
191                         getsize = fatlength;
192
193                 startblock += mydata->fat_sect; /* Offset from start of disk */
194
195                 /* Write back the fatbuf to the disk */
196                 if (flush_dirty_fat_buffer(mydata) < 0)
197                         return -1;
198
199                 if (disk_read(startblock, getsize, bufptr) < 0) {
200                         debug("Error reading FAT blocks\n");
201                         return ret;
202                 }
203                 mydata->fatbufnum = bufnum;
204         }
205
206         /* Get the actual entry from the table */
207         switch (mydata->fatsize) {
208         case 32:
209                 ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]);
210                 break;
211         case 16:
212                 ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]);
213                 break;
214         case 12:
215                 off16 = (offset * 3) / 4;
216
217                 switch (offset & 0x3) {
218                 case 0:
219                         ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[off16]);
220                         ret &= 0xfff;
221                         break;
222                 case 1:
223                         val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
224                         val1 &= 0xf000;
225                         val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]);
226                         val2 &= 0x00ff;
227                         ret = (val2 << 4) | (val1 >> 12);
228                         break;
229                 case 2:
230                         val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
231                         val1 &= 0xff00;
232                         val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]);
233                         val2 &= 0x000f;
234                         ret = (val2 << 8) | (val1 >> 8);
235                         break;
236                 case 3:
237                         ret = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
238                         ret = (ret & 0xfff0) >> 4;
239                         break;
240                 default:
241                         break;
242                 }
243                 break;
244         }
245         debug("FAT%d: ret: %08x, entry: %08x, offset: %04x\n",
246                mydata->fatsize, ret, entry, offset);
247
248         return ret;
249 }
250
251 /*
252  * Set the file name information from 'name' into 'slotptr',
253  */
254 static int str2slot(dir_slot *slotptr, const char *name, int *idx)
255 {
256         int j, end_idx = 0;
257
258         for (j = 0; j <= 8; j += 2) {
259                 if (name[*idx] == 0x00) {
260                         slotptr->name0_4[j] = 0;
261                         slotptr->name0_4[j + 1] = 0;
262                         end_idx++;
263                         goto name0_4;
264                 }
265                 slotptr->name0_4[j] = name[*idx];
266                 (*idx)++;
267                 end_idx++;
268         }
269         for (j = 0; j <= 10; j += 2) {
270                 if (name[*idx] == 0x00) {
271                         slotptr->name5_10[j] = 0;
272                         slotptr->name5_10[j + 1] = 0;
273                         end_idx++;
274                         goto name5_10;
275                 }
276                 slotptr->name5_10[j] = name[*idx];
277                 (*idx)++;
278                 end_idx++;
279         }
280         for (j = 0; j <= 2; j += 2) {
281                 if (name[*idx] == 0x00) {
282                         slotptr->name11_12[j] = 0;
283                         slotptr->name11_12[j + 1] = 0;
284                         end_idx++;
285                         goto name11_12;
286                 }
287                 slotptr->name11_12[j] = name[*idx];
288                 (*idx)++;
289                 end_idx++;
290         }
291
292         if (name[*idx] == 0x00)
293                 return 1;
294
295         return 0;
296 /* Not used characters are filled with 0xff 0xff */
297 name0_4:
298         for (; end_idx < 5; end_idx++) {
299                 slotptr->name0_4[end_idx * 2] = 0xff;
300                 slotptr->name0_4[end_idx * 2 + 1] = 0xff;
301         }
302         end_idx = 5;
303 name5_10:
304         end_idx -= 5;
305         for (; end_idx < 6; end_idx++) {
306                 slotptr->name5_10[end_idx * 2] = 0xff;
307                 slotptr->name5_10[end_idx * 2 + 1] = 0xff;
308         }
309         end_idx = 11;
310 name11_12:
311         end_idx -= 11;
312         for (; end_idx < 2; end_idx++) {
313                 slotptr->name11_12[end_idx * 2] = 0xff;
314                 slotptr->name11_12[end_idx * 2 + 1] = 0xff;
315         }
316
317         return 1;
318 }
319
320 static int is_next_clust(fsdata *mydata, dir_entry *dentptr);
321 static void flush_dir_table(fsdata *mydata, dir_entry **dentptr);
322
323 /*
324  * Fill dir_slot entries with appropriate name, id, and attr
325  * The real directory entry is returned by 'dentptr'
326  */
327 static void
328 fill_dir_slot(fsdata *mydata, dir_entry **dentptr, const char *l_name)
329 {
330         __u8 temp_dir_slot_buffer[MAX_LFN_SLOT * sizeof(dir_slot)];
331         dir_slot *slotptr = (dir_slot *)temp_dir_slot_buffer;
332         __u8 counter = 0, checksum;
333         int idx = 0, ret;
334
335         /* Get short file name checksum value */
336         checksum = mkcksum((*dentptr)->name, (*dentptr)->ext);
337
338         do {
339                 memset(slotptr, 0x00, sizeof(dir_slot));
340                 ret = str2slot(slotptr, l_name, &idx);
341                 slotptr->id = ++counter;
342                 slotptr->attr = ATTR_VFAT;
343                 slotptr->alias_checksum = checksum;
344                 slotptr++;
345         } while (ret == 0);
346
347         slotptr--;
348         slotptr->id |= LAST_LONG_ENTRY_MASK;
349
350         while (counter >= 1) {
351                 if (is_next_clust(mydata, *dentptr)) {
352                         /* A new cluster is allocated for directory table */
353                         flush_dir_table(mydata, dentptr);
354                 }
355                 memcpy(*dentptr, slotptr, sizeof(dir_slot));
356                 (*dentptr)++;
357                 slotptr--;
358                 counter--;
359         }
360
361         if (is_next_clust(mydata, *dentptr)) {
362                 /* A new cluster is allocated for directory table */
363                 flush_dir_table(mydata, dentptr);
364         }
365 }
366
367 static __u32 dir_curclust;
368
369 /*
370  * Extract the full long filename starting at 'retdent' (which is really
371  * a slot) into 'l_name'. If successful also copy the real directory entry
372  * into 'retdent'
373  * If additional adjacent cluster for directory entries is read into memory,
374  * then 'get_contents_vfatname_block' is copied into 'get_dentfromdir_block' and
375  * the location of the real directory entry is returned by 'retdent'
376  * Return 0 on success, -1 otherwise.
377  */
378 static int
379 get_long_file_name(fsdata *mydata, int curclust, __u8 *cluster,
380               dir_entry **retdent, char *l_name)
381 {
382         dir_entry *realdent;
383         dir_slot *slotptr = (dir_slot *)(*retdent);
384         dir_slot *slotptr2 = NULL;
385         __u8 *buflimit = cluster + mydata->sect_size * ((curclust == 0) ?
386                                                         PREFETCH_BLOCKS :
387                                                         mydata->clust_size);
388         __u8 counter = (slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff;
389         int idx = 0, cur_position = 0;
390
391         if (counter > VFAT_MAXSEQ) {
392                 debug("Error: VFAT name is too long\n");
393                 return -1;
394         }
395
396         while ((__u8 *)slotptr < buflimit) {
397                 if (counter == 0)
398                         break;
399                 if (((slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff) != counter)
400                         return -1;
401                 slotptr++;
402                 counter--;
403         }
404
405         if ((__u8 *)slotptr >= buflimit) {
406                 if (curclust == 0)
407                         return -1;
408                 curclust = get_fatent_value(mydata, dir_curclust);
409                 if (CHECK_CLUST(curclust, mydata->fatsize)) {
410                         debug("curclust: 0x%x\n", curclust);
411                         printf("Invalid FAT entry\n");
412                         return -1;
413                 }
414
415                 dir_curclust = curclust;
416
417                 if (get_cluster(mydata, curclust, get_contents_vfatname_block,
418                                 mydata->clust_size * mydata->sect_size) != 0) {
419                         debug("Error: reading directory block\n");
420                         return -1;
421                 }
422
423                 slotptr2 = (dir_slot *)get_contents_vfatname_block;
424                 while (counter > 0) {
425                         if (((slotptr2->id & ~LAST_LONG_ENTRY_MASK)
426                             & 0xff) != counter)
427                                 return -1;
428                         slotptr2++;
429                         counter--;
430                 }
431
432                 /* Save the real directory entry */
433                 realdent = (dir_entry *)slotptr2;
434                 while ((__u8 *)slotptr2 > get_contents_vfatname_block) {
435                         slotptr2--;
436                         slot2str(slotptr2, l_name, &idx);
437                 }
438         } else {
439                 /* Save the real directory entry */
440                 realdent = (dir_entry *)slotptr;
441         }
442
443         do {
444                 slotptr--;
445                 if (slot2str(slotptr, l_name, &idx))
446                         break;
447         } while (!(slotptr->id & LAST_LONG_ENTRY_MASK));
448
449         l_name[idx] = '\0';
450         if (*l_name == DELETED_FLAG)
451                 *l_name = '\0';
452         else if (*l_name == aRING)
453                 *l_name = DELETED_FLAG;
454         downcase(l_name);
455
456         /* Return the real directory entry */
457         *retdent = realdent;
458
459         if (slotptr2) {
460                 memcpy(get_dentfromdir_block, get_contents_vfatname_block,
461                         mydata->clust_size * mydata->sect_size);
462                 cur_position = (__u8 *)realdent - get_contents_vfatname_block;
463                 *retdent = (dir_entry *) &get_dentfromdir_block[cur_position];
464         }
465
466         return 0;
467 }
468
469 /*
470  * Set the entry at index 'entry' in a FAT (12/16/32) table.
471  */
472 static int set_fatent_value(fsdata *mydata, __u32 entry, __u32 entry_value)
473 {
474         __u32 bufnum, offset, off16;
475         __u16 val1, val2;
476
477         switch (mydata->fatsize) {
478         case 32:
479                 bufnum = entry / FAT32BUFSIZE;
480                 offset = entry - bufnum * FAT32BUFSIZE;
481                 break;
482         case 16:
483                 bufnum = entry / FAT16BUFSIZE;
484                 offset = entry - bufnum * FAT16BUFSIZE;
485                 break;
486         case 12:
487                 bufnum = entry / FAT12BUFSIZE;
488                 offset = entry - bufnum * FAT12BUFSIZE;
489                 break;
490         default:
491                 /* Unsupported FAT size */
492                 return -1;
493         }
494
495         /* Read a new block of FAT entries into the cache. */
496         if (bufnum != mydata->fatbufnum) {
497                 int getsize = FATBUFBLOCKS;
498                 __u8 *bufptr = mydata->fatbuf;
499                 __u32 fatlength = mydata->fatlength;
500                 __u32 startblock = bufnum * FATBUFBLOCKS;
501
502                 fatlength *= mydata->sect_size;
503                 startblock += mydata->fat_sect;
504
505                 if (getsize > fatlength)
506                         getsize = fatlength;
507
508                 if (flush_dirty_fat_buffer(mydata) < 0)
509                         return -1;
510
511                 if (disk_read(startblock, getsize, bufptr) < 0) {
512                         debug("Error reading FAT blocks\n");
513                         return -1;
514                 }
515                 mydata->fatbufnum = bufnum;
516         }
517
518         /* Mark as dirty */
519         mydata->fat_dirty = 1;
520
521         /* Set the actual entry */
522         switch (mydata->fatsize) {
523         case 32:
524                 ((__u32 *) mydata->fatbuf)[offset] = cpu_to_le32(entry_value);
525                 break;
526         case 16:
527                 ((__u16 *) mydata->fatbuf)[offset] = cpu_to_le16(entry_value);
528                 break;
529         case 12:
530                 off16 = (offset * 3) / 4;
531
532                 switch (offset & 0x3) {
533                 case 0:
534                         val1 = cpu_to_le16(entry_value) & 0xfff;
535                         ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff;
536                         ((__u16 *)mydata->fatbuf)[off16] |= val1;
537                         break;
538                 case 1:
539                         val1 = cpu_to_le16(entry_value) & 0xf;
540                         val2 = (cpu_to_le16(entry_value) >> 4) & 0xff;
541
542                         ((__u16 *)mydata->fatbuf)[off16] &= ~0xf000;
543                         ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 12);
544
545                         ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xff;
546                         ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
547                         break;
548                 case 2:
549                         val1 = cpu_to_le16(entry_value) & 0xff;
550                         val2 = (cpu_to_le16(entry_value) >> 8) & 0xf;
551
552                         ((__u16 *)mydata->fatbuf)[off16] &= ~0xff00;
553                         ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 8);
554
555                         ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xf;
556                         ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
557                         break;
558                 case 3:
559                         val1 = cpu_to_le16(entry_value) & 0xfff;
560                         ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff0;
561                         ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 4);
562                         break;
563                 default:
564                         break;
565                 }
566
567                 break;
568         default:
569                 return -1;
570         }
571
572         return 0;
573 }
574
575 /*
576  * Determine the next free cluster after 'entry' in a FAT (12/16/32) table
577  * and link it to 'entry'. EOC marker is not set on returned entry.
578  */
579 static __u32 determine_fatent(fsdata *mydata, __u32 entry)
580 {
581         __u32 next_fat, next_entry = entry + 1;
582
583         while (1) {
584                 next_fat = get_fatent_value(mydata, next_entry);
585                 if (next_fat == 0) {
586                         /* found free entry, link to entry */
587                         set_fatent_value(mydata, entry, next_entry);
588                         break;
589                 }
590                 next_entry++;
591         }
592         debug("FAT%d: entry: %08x, entry_value: %04x\n",
593                mydata->fatsize, entry, next_entry);
594
595         return next_entry;
596 }
597
598 /*
599  * Write at most 'size' bytes from 'buffer' into the specified cluster.
600  * Return 0 on success, -1 otherwise.
601  */
602 static int
603 set_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer,
604              unsigned long size)
605 {
606         __u32 idx = 0;
607         __u32 startsect;
608         int ret;
609
610         if (clustnum > 0)
611                 startsect = mydata->data_begin +
612                                 clustnum * mydata->clust_size;
613         else
614                 startsect = mydata->rootdir_sect;
615
616         debug("clustnum: %d, startsect: %d\n", clustnum, startsect);
617
618         if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
619                 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
620
621                 printf("FAT: Misaligned buffer address (%p)\n", buffer);
622
623                 while (size >= mydata->sect_size) {
624                         memcpy(tmpbuf, buffer, mydata->sect_size);
625                         ret = disk_write(startsect++, 1, tmpbuf);
626                         if (ret != 1) {
627                                 debug("Error writing data (got %d)\n", ret);
628                                 return -1;
629                         }
630
631                         buffer += mydata->sect_size;
632                         size -= mydata->sect_size;
633                 }
634         } else if (size >= mydata->sect_size) {
635                 idx = size / mydata->sect_size;
636                 ret = disk_write(startsect, idx, buffer);
637                 if (ret != idx) {
638                         debug("Error writing data (got %d)\n", ret);
639                         return -1;
640                 }
641
642                 startsect += idx;
643                 idx *= mydata->sect_size;
644                 buffer += idx;
645                 size -= idx;
646         }
647
648         if (size) {
649                 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
650
651                 memcpy(tmpbuf, buffer, size);
652                 ret = disk_write(startsect, 1, tmpbuf);
653                 if (ret != 1) {
654                         debug("Error writing data (got %d)\n", ret);
655                         return -1;
656                 }
657         }
658
659         return 0;
660 }
661
662 /*
663  * Find the first empty cluster
664  */
665 static int find_empty_cluster(fsdata *mydata)
666 {
667         __u32 fat_val, entry = 3;
668
669         while (1) {
670                 fat_val = get_fatent_value(mydata, entry);
671                 if (fat_val == 0)
672                         break;
673                 entry++;
674         }
675
676         return entry;
677 }
678
679 /*
680  * Write directory entries in 'get_dentfromdir_block' to block device
681  */
682 static void flush_dir_table(fsdata *mydata, dir_entry **dentptr)
683 {
684         int dir_newclust = 0;
685
686         if (set_cluster(mydata, dir_curclust,
687                     get_dentfromdir_block,
688                     mydata->clust_size * mydata->sect_size) != 0) {
689                 printf("error: wrinting directory entry\n");
690                 return;
691         }
692         dir_newclust = find_empty_cluster(mydata);
693         set_fatent_value(mydata, dir_curclust, dir_newclust);
694         if (mydata->fatsize == 32)
695                 set_fatent_value(mydata, dir_newclust, 0xffffff8);
696         else if (mydata->fatsize == 16)
697                 set_fatent_value(mydata, dir_newclust, 0xfff8);
698         else if (mydata->fatsize == 12)
699                 set_fatent_value(mydata, dir_newclust, 0xff8);
700
701         dir_curclust = dir_newclust;
702
703         if (flush_dirty_fat_buffer(mydata) < 0)
704                 return;
705
706         memset(get_dentfromdir_block, 0x00,
707                 mydata->clust_size * mydata->sect_size);
708
709         *dentptr = (dir_entry *) get_dentfromdir_block;
710 }
711
712 /*
713  * Set empty cluster from 'entry' to the end of a file
714  */
715 static int clear_fatent(fsdata *mydata, __u32 entry)
716 {
717         __u32 fat_val;
718
719         while (!CHECK_CLUST(entry, mydata->fatsize)) {
720                 fat_val = get_fatent_value(mydata, entry);
721                 if (fat_val != 0)
722                         set_fatent_value(mydata, entry, 0);
723                 else
724                         break;
725
726                 entry = fat_val;
727         }
728
729         /* Flush fat buffer */
730         if (flush_dirty_fat_buffer(mydata) < 0)
731                 return -1;
732
733         return 0;
734 }
735
736 /*
737  * Write at most 'maxsize' bytes from 'buffer' into
738  * the file associated with 'dentptr'
739  * Update the number of bytes written in *gotsize and return 0
740  * or return -1 on fatal errors.
741  */
742 static int
743 set_contents(fsdata *mydata, dir_entry *dentptr, __u8 *buffer,
744               loff_t maxsize, loff_t *gotsize)
745 {
746         loff_t filesize = FAT2CPU32(dentptr->size);
747         unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
748         __u32 curclust = START(dentptr);
749         __u32 endclust = 0, newclust = 0;
750         loff_t actsize;
751
752         *gotsize = 0;
753         debug("Filesize: %llu bytes\n", filesize);
754
755         if (maxsize > 0 && filesize > maxsize)
756                 filesize = maxsize;
757
758         debug("%llu bytes\n", filesize);
759
760         if (!curclust) {
761                 if (filesize) {
762                         debug("error: nonempty clusterless file!\n");
763                         return -1;
764                 }
765                 return 0;
766         }
767
768         actsize = bytesperclust;
769         endclust = curclust;
770         do {
771                 /* search for consecutive clusters */
772                 while (actsize < filesize) {
773                         newclust = determine_fatent(mydata, endclust);
774
775                         if ((newclust - 1) != endclust)
776                                 goto getit;
777
778                         if (CHECK_CLUST(newclust, mydata->fatsize)) {
779                                 debug("newclust: 0x%x\n", newclust);
780                                 debug("Invalid FAT entry\n");
781                                 return 0;
782                         }
783                         endclust = newclust;
784                         actsize += bytesperclust;
785                 }
786
787                 /* set remaining bytes */
788                 actsize = filesize;
789                 if (set_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
790                         debug("error: writing cluster\n");
791                         return -1;
792                 }
793                 *gotsize += actsize;
794
795                 /* Mark end of file in FAT */
796                 if (mydata->fatsize == 12)
797                         newclust = 0xfff;
798                 else if (mydata->fatsize == 16)
799                         newclust = 0xffff;
800                 else if (mydata->fatsize == 32)
801                         newclust = 0xfffffff;
802                 set_fatent_value(mydata, endclust, newclust);
803
804                 return 0;
805 getit:
806                 if (set_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
807                         debug("error: writing cluster\n");
808                         return -1;
809                 }
810                 *gotsize += actsize;
811                 filesize -= actsize;
812                 buffer += actsize;
813
814                 if (CHECK_CLUST(newclust, mydata->fatsize)) {
815                         debug("newclust: 0x%x\n", newclust);
816                         debug("Invalid FAT entry\n");
817                         return 0;
818                 }
819                 actsize = bytesperclust;
820                 curclust = endclust = newclust;
821         } while (1);
822 }
823
824 /*
825  * Set start cluster in directory entry
826  */
827 static void set_start_cluster(const fsdata *mydata, dir_entry *dentptr,
828                                 __u32 start_cluster)
829 {
830         if (mydata->fatsize == 32)
831                 dentptr->starthi =
832                         cpu_to_le16((start_cluster & 0xffff0000) >> 16);
833         dentptr->start = cpu_to_le16(start_cluster & 0xffff);
834 }
835
836 /*
837  * Fill dir_entry
838  */
839 static void fill_dentry(fsdata *mydata, dir_entry *dentptr,
840         const char *filename, __u32 start_cluster, __u32 size, __u8 attr)
841 {
842         set_start_cluster(mydata, dentptr, start_cluster);
843         dentptr->size = cpu_to_le32(size);
844
845         dentptr->attr = attr;
846
847         set_name(dentptr, filename);
848 }
849
850 /*
851  * Check whether adding a file makes the file system to
852  * exceed the size of the block device
853  * Return -1 when overflow occurs, otherwise return 0
854  */
855 static int check_overflow(fsdata *mydata, __u32 clustnum, loff_t size)
856 {
857         __u32 startsect, sect_num, offset;
858
859         if (clustnum > 0) {
860                 startsect = mydata->data_begin +
861                                 clustnum * mydata->clust_size;
862         } else {
863                 startsect = mydata->rootdir_sect;
864         }
865
866         sect_num = div_u64_rem(size, mydata->sect_size, &offset);
867
868         if (offset != 0)
869                 sect_num++;
870
871         if (startsect + sect_num > cur_part_info.start + total_sector)
872                 return -1;
873         return 0;
874 }
875
876 /*
877  * Check if adding several entries exceed one cluster boundary
878  */
879 static int is_next_clust(fsdata *mydata, dir_entry *dentptr)
880 {
881         int cur_position;
882
883         cur_position = (__u8 *)dentptr - get_dentfromdir_block;
884
885         if (cur_position >= mydata->clust_size * mydata->sect_size)
886                 return 1;
887         else
888                 return 0;
889 }
890
891 static dir_entry *empty_dentptr;
892 /*
893  * Find a directory entry based on filename or start cluster number
894  * If the directory entry is not found,
895  * the new position for writing a directory entry will be returned
896  */
897 static dir_entry *find_directory_entry(fsdata *mydata, int startsect,
898         char *filename, dir_entry *retdent, __u32 start)
899 {
900         __u32 curclust = (startsect - mydata->data_begin) / mydata->clust_size;
901
902         debug("get_dentfromdir: %s\n", filename);
903
904         while (1) {
905                 dir_entry *dentptr;
906
907                 int i;
908
909                 if (get_cluster(mydata, curclust, get_dentfromdir_block,
910                             mydata->clust_size * mydata->sect_size) != 0) {
911                         printf("Error: reading directory block\n");
912                         return NULL;
913                 }
914
915                 dentptr = (dir_entry *)get_dentfromdir_block;
916
917                 dir_curclust = curclust;
918
919                 for (i = 0; i < DIRENTSPERCLUST; i++) {
920                         char s_name[14], l_name[VFAT_MAXLEN_BYTES];
921
922                         l_name[0] = '\0';
923                         if (dentptr->name[0] == DELETED_FLAG) {
924                                 dentptr++;
925                                 if (is_next_clust(mydata, dentptr))
926                                         break;
927                                 continue;
928                         }
929                         if ((dentptr->attr & ATTR_VOLUME)) {
930                                 if (vfat_enabled &&
931                                     (dentptr->attr & ATTR_VFAT) &&
932                                     (dentptr->name[0] & LAST_LONG_ENTRY_MASK)) {
933                                         get_long_file_name(mydata, curclust,
934                                                      get_dentfromdir_block,
935                                                      &dentptr, l_name);
936                                         debug("vfatname: |%s|\n", l_name);
937                                 } else {
938                                         /* Volume label or VFAT entry */
939                                         dentptr++;
940                                         if (is_next_clust(mydata, dentptr))
941                                                 break;
942                                         continue;
943                                 }
944                         }
945                         if (dentptr->name[0] == 0) {
946                                 debug("Dentname == NULL - %d\n", i);
947                                 empty_dentptr = dentptr;
948                                 return NULL;
949                         }
950
951                         get_name(dentptr, s_name);
952
953                         if (strcmp(filename, s_name)
954                             && strcmp(filename, l_name)) {
955                                 debug("Mismatch: |%s|%s|\n",
956                                         s_name, l_name);
957                                 dentptr++;
958                                 if (is_next_clust(mydata, dentptr))
959                                         break;
960                                 continue;
961                         }
962
963                         memcpy(retdent, dentptr, sizeof(dir_entry));
964
965                         debug("DentName: %s", s_name);
966                         debug(", start: 0x%x", START(dentptr));
967                         debug(", size:  0x%x %s\n",
968                               FAT2CPU32(dentptr->size),
969                               (dentptr->attr & ATTR_DIR) ?
970                               "(DIR)" : "");
971
972                         return dentptr;
973                 }
974
975                 /*
976                  * In FAT16/12, the root dir is locate before data area, shows
977                  * in following:
978                  * -------------------------------------------------------------
979                  * | Boot | FAT1 & 2 | Root dir | Data (start from cluster #2) |
980                  * -------------------------------------------------------------
981                  *
982                  * As a result if curclust is in Root dir, it is a negative
983                  * number or 0, 1.
984                  *
985                  */
986                 if (mydata->fatsize != 32 && (int)curclust <= 1) {
987                         /* Current clust is in root dir, set to next clust */
988                         curclust++;
989                         if ((int)curclust <= 1)
990                                 continue;       /* continue to find */
991
992                         /* Reach the end of root dir */
993                         empty_dentptr = dentptr;
994                         return NULL;
995                 }
996
997                 curclust = get_fatent_value(mydata, dir_curclust);
998                 if (IS_LAST_CLUST(curclust, mydata->fatsize)) {
999                         empty_dentptr = dentptr;
1000                         return NULL;
1001                 }
1002                 if (CHECK_CLUST(curclust, mydata->fatsize)) {
1003                         debug("curclust: 0x%x\n", curclust);
1004                         debug("Invalid FAT entry\n");
1005                         return NULL;
1006                 }
1007         }
1008
1009         return NULL;
1010 }
1011
1012 static int do_fat_write(const char *filename, void *buffer, loff_t size,
1013                         loff_t *actwrite)
1014 {
1015         dir_entry *dentptr, *retdent;
1016         __u32 startsect;
1017         __u32 start_cluster;
1018         boot_sector bs;
1019         volume_info volinfo;
1020         fsdata datablock;
1021         fsdata *mydata = &datablock;
1022         int cursect;
1023         int ret = -1, name_len;
1024         char l_filename[VFAT_MAXLEN_BYTES];
1025
1026         *actwrite = size;
1027         dir_curclust = 0;
1028
1029         if (read_bootsectandvi(&bs, &volinfo, &mydata->fatsize)) {
1030                 debug("error: reading boot sector\n");
1031                 return -1;
1032         }
1033
1034         total_sector = bs.total_sect;
1035         if (total_sector == 0)
1036                 total_sector = (int)cur_part_info.size; /* cast of lbaint_t */
1037
1038         if (mydata->fatsize == 32)
1039                 mydata->fatlength = bs.fat32_length;
1040         else
1041                 mydata->fatlength = bs.fat_length;
1042
1043         mydata->fat_sect = bs.reserved;
1044
1045         cursect = mydata->rootdir_sect
1046                 = mydata->fat_sect + mydata->fatlength * bs.fats;
1047         num_of_fats = bs.fats;
1048
1049         mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0];
1050         mydata->clust_size = bs.cluster_size;
1051
1052         if (mydata->fatsize == 32) {
1053                 mydata->data_begin = mydata->rootdir_sect -
1054                                         (mydata->clust_size * 2);
1055         } else {
1056                 int rootdir_size;
1057
1058                 rootdir_size = ((bs.dir_entries[1]  * (int)256 +
1059                                  bs.dir_entries[0]) *
1060                                  sizeof(dir_entry)) /
1061                                  mydata->sect_size;
1062                 mydata->data_begin = mydata->rootdir_sect +
1063                                         rootdir_size -
1064                                         (mydata->clust_size * 2);
1065         }
1066
1067         mydata->fatbufnum = -1;
1068         mydata->fat_dirty = 0;
1069         mydata->fatbuf = memalign(ARCH_DMA_MINALIGN, FATBUFSIZE);
1070         if (mydata->fatbuf == NULL) {
1071                 debug("Error: allocating memory\n");
1072                 return -1;
1073         }
1074
1075         if (disk_read(cursect,
1076                 (mydata->fatsize == 32) ?
1077                 (mydata->clust_size) :
1078                 PREFETCH_BLOCKS, do_fat_read_at_block) < 0) {
1079                 debug("Error: reading rootdir block\n");
1080                 goto exit;
1081         }
1082         dentptr = (dir_entry *) do_fat_read_at_block;
1083
1084         name_len = strlen(filename);
1085         if (name_len >= VFAT_MAXLEN_BYTES)
1086                 name_len = VFAT_MAXLEN_BYTES - 1;
1087
1088         memcpy(l_filename, filename, name_len);
1089         l_filename[name_len] = 0; /* terminate the string */
1090         downcase(l_filename);
1091
1092         startsect = mydata->rootdir_sect;
1093         retdent = find_directory_entry(mydata, startsect,
1094                                 l_filename, dentptr, 0);
1095         if (retdent) {
1096                 /* Update file size and start_cluster in a directory entry */
1097                 retdent->size = cpu_to_le32(size);
1098                 start_cluster = START(retdent);
1099
1100                 if (start_cluster) {
1101                         if (size) {
1102                                 ret = check_overflow(mydata, start_cluster,
1103                                                         size);
1104                                 if (ret) {
1105                                         printf("Error: %llu overflow\n", size);
1106                                         goto exit;
1107                                 }
1108                         }
1109
1110                         ret = clear_fatent(mydata, start_cluster);
1111                         if (ret) {
1112                                 printf("Error: clearing FAT entries\n");
1113                                 goto exit;
1114                         }
1115
1116                         if (!size)
1117                                 set_start_cluster(mydata, retdent, 0);
1118                 } else if (size) {
1119                         ret = start_cluster = find_empty_cluster(mydata);
1120                         if (ret < 0) {
1121                                 printf("Error: finding empty cluster\n");
1122                                 goto exit;
1123                         }
1124
1125                         ret = check_overflow(mydata, start_cluster, size);
1126                         if (ret) {
1127                                 printf("Error: %llu overflow\n", size);
1128                                 goto exit;
1129                         }
1130
1131                         set_start_cluster(mydata, retdent, start_cluster);
1132                 }
1133         } else {
1134                 /* Set short name to set alias checksum field in dir_slot */
1135                 set_name(empty_dentptr, filename);
1136                 fill_dir_slot(mydata, &empty_dentptr, filename);
1137
1138                 if (size) {
1139                         ret = start_cluster = find_empty_cluster(mydata);
1140                         if (ret < 0) {
1141                                 printf("Error: finding empty cluster\n");
1142                                 goto exit;
1143                         }
1144
1145                         ret = check_overflow(mydata, start_cluster, size);
1146                         if (ret) {
1147                                 printf("Error: %llu overflow\n", size);
1148                                 goto exit;
1149                         }
1150                 } else {
1151                         start_cluster = 0;
1152                 }
1153
1154                 /* Set attribute as archieve for regular file */
1155                 fill_dentry(mydata, empty_dentptr, filename,
1156                         start_cluster, size, 0x20);
1157
1158                 retdent = empty_dentptr;
1159         }
1160
1161         ret = set_contents(mydata, retdent, buffer, size, actwrite);
1162         if (ret < 0) {
1163                 printf("Error: writing contents\n");
1164                 goto exit;
1165         }
1166         debug("attempt to write 0x%llx bytes\n", *actwrite);
1167
1168         /* Flush fat buffer */
1169         ret = flush_dirty_fat_buffer(mydata);
1170         if (ret) {
1171                 printf("Error: flush fat buffer\n");
1172                 goto exit;
1173         }
1174
1175         /* Write directory table to device */
1176         ret = set_cluster(mydata, dir_curclust, get_dentfromdir_block,
1177                         mydata->clust_size * mydata->sect_size);
1178         if (ret)
1179                 printf("Error: writing directory entry\n");
1180
1181 exit:
1182         free(mydata->fatbuf);
1183         return ret;
1184 }
1185
1186 int file_fat_write(const char *filename, void *buffer, loff_t offset,
1187                    loff_t maxsize, loff_t *actwrite)
1188 {
1189         if (offset != 0) {
1190                 printf("Error: non zero offset is currently not supported.\n");
1191                 return -1;
1192         }
1193
1194         printf("writing %s\n", filename);
1195         return do_fat_write(filename, buffer, maxsize, actwrite);
1196 }