5ea15fab3af6f00a7ef2ee79095c4ba2f0ef93fd
[project/bcm63xx/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 new_dir_table(fat_itr *itr);
213 static int flush_dir(fat_itr *itr);
214
215 /*
216 * Fill dir_slot entries with appropriate name, id, and attr
217 * 'itr' will point to a next entry
218 */
219 static int
220 fill_dir_slot(fat_itr *itr, const char *l_name)
221 {
222 __u8 temp_dir_slot_buffer[MAX_LFN_SLOT * sizeof(dir_slot)];
223 dir_slot *slotptr = (dir_slot *)temp_dir_slot_buffer;
224 __u8 counter = 0, checksum;
225 int idx = 0, ret;
226
227 /* Get short file name checksum value */
228 checksum = mkcksum(itr->dent->name, itr->dent->ext);
229
230 do {
231 memset(slotptr, 0x00, sizeof(dir_slot));
232 ret = str2slot(slotptr, l_name, &idx);
233 slotptr->id = ++counter;
234 slotptr->attr = ATTR_VFAT;
235 slotptr->alias_checksum = checksum;
236 slotptr++;
237 } while (ret == 0);
238
239 slotptr--;
240 slotptr->id |= LAST_LONG_ENTRY_MASK;
241
242 while (counter >= 1) {
243 memcpy(itr->dent, slotptr, sizeof(dir_slot));
244 slotptr--;
245 counter--;
246
247 if (itr->remaining == 0)
248 flush_dir(itr);
249
250 if (!fat_itr_next(itr))
251 if (!itr->dent && !itr->is_root && new_dir_table(itr))
252 return -1;
253 }
254
255 return 0;
256 }
257
258 /*
259 * Set the entry at index 'entry' in a FAT (12/16/32) table.
260 */
261 static int set_fatent_value(fsdata *mydata, __u32 entry, __u32 entry_value)
262 {
263 __u32 bufnum, offset, off16;
264 __u16 val1, val2;
265
266 switch (mydata->fatsize) {
267 case 32:
268 bufnum = entry / FAT32BUFSIZE;
269 offset = entry - bufnum * FAT32BUFSIZE;
270 break;
271 case 16:
272 bufnum = entry / FAT16BUFSIZE;
273 offset = entry - bufnum * FAT16BUFSIZE;
274 break;
275 case 12:
276 bufnum = entry / FAT12BUFSIZE;
277 offset = entry - bufnum * FAT12BUFSIZE;
278 break;
279 default:
280 /* Unsupported FAT size */
281 return -1;
282 }
283
284 /* Read a new block of FAT entries into the cache. */
285 if (bufnum != mydata->fatbufnum) {
286 int getsize = FATBUFBLOCKS;
287 __u8 *bufptr = mydata->fatbuf;
288 __u32 fatlength = mydata->fatlength;
289 __u32 startblock = bufnum * FATBUFBLOCKS;
290
291 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
292 if (startblock + getsize > fatlength)
293 getsize = fatlength - startblock;
294
295 if (flush_dirty_fat_buffer(mydata) < 0)
296 return -1;
297
298 startblock += mydata->fat_sect;
299
300 if (disk_read(startblock, getsize, bufptr) < 0) {
301 debug("Error reading FAT blocks\n");
302 return -1;
303 }
304 mydata->fatbufnum = bufnum;
305 }
306
307 /* Mark as dirty */
308 mydata->fat_dirty = 1;
309
310 /* Set the actual entry */
311 switch (mydata->fatsize) {
312 case 32:
313 ((__u32 *) mydata->fatbuf)[offset] = cpu_to_le32(entry_value);
314 break;
315 case 16:
316 ((__u16 *) mydata->fatbuf)[offset] = cpu_to_le16(entry_value);
317 break;
318 case 12:
319 off16 = (offset * 3) / 4;
320
321 switch (offset & 0x3) {
322 case 0:
323 val1 = cpu_to_le16(entry_value) & 0xfff;
324 ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff;
325 ((__u16 *)mydata->fatbuf)[off16] |= val1;
326 break;
327 case 1:
328 val1 = cpu_to_le16(entry_value) & 0xf;
329 val2 = (cpu_to_le16(entry_value) >> 4) & 0xff;
330
331 ((__u16 *)mydata->fatbuf)[off16] &= ~0xf000;
332 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 12);
333
334 ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xff;
335 ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
336 break;
337 case 2:
338 val1 = cpu_to_le16(entry_value) & 0xff;
339 val2 = (cpu_to_le16(entry_value) >> 8) & 0xf;
340
341 ((__u16 *)mydata->fatbuf)[off16] &= ~0xff00;
342 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 8);
343
344 ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xf;
345 ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
346 break;
347 case 3:
348 val1 = cpu_to_le16(entry_value) & 0xfff;
349 ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff0;
350 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 4);
351 break;
352 default:
353 break;
354 }
355
356 break;
357 default:
358 return -1;
359 }
360
361 return 0;
362 }
363
364 /*
365 * Determine the next free cluster after 'entry' in a FAT (12/16/32) table
366 * and link it to 'entry'. EOC marker is not set on returned entry.
367 */
368 static __u32 determine_fatent(fsdata *mydata, __u32 entry)
369 {
370 __u32 next_fat, next_entry = entry + 1;
371
372 while (1) {
373 next_fat = get_fatent(mydata, next_entry);
374 if (next_fat == 0) {
375 /* found free entry, link to entry */
376 set_fatent_value(mydata, entry, next_entry);
377 break;
378 }
379 next_entry++;
380 }
381 debug("FAT%d: entry: %08x, entry_value: %04x\n",
382 mydata->fatsize, entry, next_entry);
383
384 return next_entry;
385 }
386
387 /**
388 * set_sectors() - write data to sectors
389 *
390 * Write 'size' bytes from 'buffer' into the specified sector.
391 *
392 * @mydata: data to be written
393 * @startsect: sector to be written to
394 * @buffer: data to be written
395 * @size: bytes to be written (but not more than the size of a cluster)
396 * Return: 0 on success, -1 otherwise
397 */
398 static int
399 set_sectors(fsdata *mydata, u32 startsect, u8 *buffer, u32 size)
400 {
401 u32 nsects = 0;
402 int ret;
403
404 debug("startsect: %d\n", startsect);
405
406 if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
407 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
408
409 debug("FAT: Misaligned buffer address (%p)\n", buffer);
410
411 while (size >= mydata->sect_size) {
412 memcpy(tmpbuf, buffer, mydata->sect_size);
413 ret = disk_write(startsect++, 1, tmpbuf);
414 if (ret != 1) {
415 debug("Error writing data (got %d)\n", ret);
416 return -1;
417 }
418
419 buffer += mydata->sect_size;
420 size -= mydata->sect_size;
421 }
422 } else if (size >= mydata->sect_size) {
423 nsects = size / mydata->sect_size;
424 ret = disk_write(startsect, nsects, buffer);
425 if (ret != nsects) {
426 debug("Error writing data (got %d)\n", ret);
427 return -1;
428 }
429
430 startsect += nsects;
431 buffer += nsects * mydata->sect_size;
432 size -= nsects * mydata->sect_size;
433 }
434
435 if (size) {
436 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
437 /* Do not leak content of stack */
438 memset(tmpbuf, 0, mydata->sect_size);
439 memcpy(tmpbuf, buffer, size);
440 ret = disk_write(startsect, 1, tmpbuf);
441 if (ret != 1) {
442 debug("Error writing data (got %d)\n", ret);
443 return -1;
444 }
445 }
446
447 return 0;
448 }
449
450 /**
451 * set_cluster() - write data to cluster
452 *
453 * Write 'size' bytes from 'buffer' into the specified cluster.
454 *
455 * @mydata: data to be written
456 * @clustnum: cluster to be written to
457 * @buffer: data to be written
458 * @size: bytes to be written (but not more than the size of a cluster)
459 * Return: 0 on success, -1 otherwise
460 */
461 static int
462 set_cluster(fsdata *mydata, u32 clustnum, u8 *buffer, u32 size)
463 {
464 return set_sectors(mydata, clust_to_sect(mydata, clustnum),
465 buffer, size);
466 }
467
468 static int
469 flush_dir(fat_itr *itr)
470 {
471 fsdata *mydata = itr->fsdata;
472 u32 startsect, sect_offset, nsects;
473
474 if (!itr->is_root || mydata->fatsize == 32)
475 return set_cluster(mydata, itr->clust, itr->block,
476 mydata->clust_size * mydata->sect_size);
477
478 sect_offset = itr->clust * mydata->clust_size;
479 startsect = mydata->rootdir_sect + sect_offset;
480 /* do not write past the end of rootdir */
481 nsects = min_t(u32, mydata->clust_size,
482 mydata->rootdir_size - sect_offset);
483
484 return set_sectors(mydata, startsect, itr->block,
485 nsects * mydata->sect_size);
486 }
487
488 static __u8 tmpbuf_cluster[MAX_CLUSTSIZE] __aligned(ARCH_DMA_MINALIGN);
489
490 /*
491 * Read and modify data on existing and consecutive cluster blocks
492 */
493 static int
494 get_set_cluster(fsdata *mydata, __u32 clustnum, loff_t pos, __u8 *buffer,
495 loff_t size, loff_t *gotsize)
496 {
497 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
498 __u32 startsect;
499 loff_t wsize;
500 int clustcount, i, ret;
501
502 *gotsize = 0;
503 if (!size)
504 return 0;
505
506 assert(pos < bytesperclust);
507 startsect = clust_to_sect(mydata, clustnum);
508
509 debug("clustnum: %d, startsect: %d, pos: %lld\n",
510 clustnum, startsect, pos);
511
512 /* partial write at beginning */
513 if (pos) {
514 wsize = min(bytesperclust - pos, size);
515 ret = disk_read(startsect, mydata->clust_size, tmpbuf_cluster);
516 if (ret != mydata->clust_size) {
517 debug("Error reading data (got %d)\n", ret);
518 return -1;
519 }
520
521 memcpy(tmpbuf_cluster + pos, buffer, wsize);
522 ret = disk_write(startsect, mydata->clust_size, tmpbuf_cluster);
523 if (ret != mydata->clust_size) {
524 debug("Error writing data (got %d)\n", ret);
525 return -1;
526 }
527
528 size -= wsize;
529 buffer += wsize;
530 *gotsize += wsize;
531
532 startsect += mydata->clust_size;
533
534 if (!size)
535 return 0;
536 }
537
538 /* full-cluster write */
539 if (size >= bytesperclust) {
540 clustcount = lldiv(size, bytesperclust);
541
542 if (!((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1))) {
543 wsize = clustcount * bytesperclust;
544 ret = disk_write(startsect,
545 clustcount * mydata->clust_size,
546 buffer);
547 if (ret != clustcount * mydata->clust_size) {
548 debug("Error writing data (got %d)\n", ret);
549 return -1;
550 }
551
552 size -= wsize;
553 buffer += wsize;
554 *gotsize += wsize;
555
556 startsect += clustcount * mydata->clust_size;
557 } else {
558 for (i = 0; i < clustcount; i++) {
559 memcpy(tmpbuf_cluster, buffer, bytesperclust);
560 ret = disk_write(startsect,
561 mydata->clust_size,
562 tmpbuf_cluster);
563 if (ret != mydata->clust_size) {
564 debug("Error writing data (got %d)\n",
565 ret);
566 return -1;
567 }
568
569 size -= bytesperclust;
570 buffer += bytesperclust;
571 *gotsize += bytesperclust;
572
573 startsect += mydata->clust_size;
574 }
575 }
576 }
577
578 /* partial write at end */
579 if (size) {
580 wsize = size;
581 ret = disk_read(startsect, mydata->clust_size, tmpbuf_cluster);
582 if (ret != mydata->clust_size) {
583 debug("Error reading data (got %d)\n", ret);
584 return -1;
585 }
586 memcpy(tmpbuf_cluster, buffer, wsize);
587 ret = disk_write(startsect, mydata->clust_size, tmpbuf_cluster);
588 if (ret != mydata->clust_size) {
589 debug("Error writing data (got %d)\n", ret);
590 return -1;
591 }
592
593 size -= wsize;
594 buffer += wsize;
595 *gotsize += wsize;
596 }
597
598 assert(!size);
599
600 return 0;
601 }
602
603 /*
604 * Find the first empty cluster
605 */
606 static int find_empty_cluster(fsdata *mydata)
607 {
608 __u32 fat_val, entry = 3;
609
610 while (1) {
611 fat_val = get_fatent(mydata, entry);
612 if (fat_val == 0)
613 break;
614 entry++;
615 }
616
617 return entry;
618 }
619
620 /*
621 * Allocate a cluster for additional directory entries
622 */
623 static int new_dir_table(fat_itr *itr)
624 {
625 fsdata *mydata = itr->fsdata;
626 int dir_newclust = 0;
627 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
628
629 dir_newclust = find_empty_cluster(mydata);
630 set_fatent_value(mydata, itr->clust, dir_newclust);
631 if (mydata->fatsize == 32)
632 set_fatent_value(mydata, dir_newclust, 0xffffff8);
633 else if (mydata->fatsize == 16)
634 set_fatent_value(mydata, dir_newclust, 0xfff8);
635 else if (mydata->fatsize == 12)
636 set_fatent_value(mydata, dir_newclust, 0xff8);
637
638 itr->clust = dir_newclust;
639 itr->next_clust = dir_newclust;
640
641 if (flush_dirty_fat_buffer(mydata) < 0)
642 return -1;
643
644 memset(itr->block, 0x00, bytesperclust);
645
646 itr->dent = (dir_entry *)itr->block;
647 itr->last_cluster = 1;
648 itr->remaining = bytesperclust / sizeof(dir_entry) - 1;
649
650 return 0;
651 }
652
653 /*
654 * Set empty cluster from 'entry' to the end of a file
655 */
656 static int clear_fatent(fsdata *mydata, __u32 entry)
657 {
658 __u32 fat_val;
659
660 while (!CHECK_CLUST(entry, mydata->fatsize)) {
661 fat_val = get_fatent(mydata, entry);
662 if (fat_val != 0)
663 set_fatent_value(mydata, entry, 0);
664 else
665 break;
666
667 entry = fat_val;
668 }
669
670 /* Flush fat buffer */
671 if (flush_dirty_fat_buffer(mydata) < 0)
672 return -1;
673
674 return 0;
675 }
676
677 /*
678 * Set start cluster in directory entry
679 */
680 static void set_start_cluster(const fsdata *mydata, dir_entry *dentptr,
681 __u32 start_cluster)
682 {
683 if (mydata->fatsize == 32)
684 dentptr->starthi =
685 cpu_to_le16((start_cluster & 0xffff0000) >> 16);
686 dentptr->start = cpu_to_le16(start_cluster & 0xffff);
687 }
688
689 /*
690 * Check whether adding a file makes the file system to
691 * exceed the size of the block device
692 * Return -1 when overflow occurs, otherwise return 0
693 */
694 static int check_overflow(fsdata *mydata, __u32 clustnum, loff_t size)
695 {
696 __u32 startsect, sect_num, offset;
697
698 if (clustnum > 0)
699 startsect = clust_to_sect(mydata, clustnum);
700 else
701 startsect = mydata->rootdir_sect;
702
703 sect_num = div_u64_rem(size, mydata->sect_size, &offset);
704
705 if (offset != 0)
706 sect_num++;
707
708 if (startsect + sect_num > total_sector)
709 return -1;
710 return 0;
711 }
712
713 /*
714 * Write at most 'maxsize' bytes from 'buffer' into
715 * the file associated with 'dentptr'
716 * Update the number of bytes written in *gotsize and return 0
717 * or return -1 on fatal errors.
718 */
719 static int
720 set_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos, __u8 *buffer,
721 loff_t maxsize, loff_t *gotsize)
722 {
723 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
724 __u32 curclust = START(dentptr);
725 __u32 endclust = 0, newclust = 0;
726 u64 cur_pos, filesize;
727 loff_t offset, actsize, wsize;
728
729 *gotsize = 0;
730 filesize = pos + maxsize;
731
732 debug("%llu bytes\n", filesize);
733
734 if (!filesize) {
735 if (!curclust)
736 return 0;
737 if (!CHECK_CLUST(curclust, mydata->fatsize) ||
738 IS_LAST_CLUST(curclust, mydata->fatsize)) {
739 clear_fatent(mydata, curclust);
740 set_start_cluster(mydata, dentptr, 0);
741 return 0;
742 }
743 debug("curclust: 0x%x\n", curclust);
744 debug("Invalid FAT entry\n");
745 return -1;
746 }
747
748 if (!curclust) {
749 assert(pos == 0);
750 goto set_clusters;
751 }
752
753 /* go to cluster at pos */
754 cur_pos = bytesperclust;
755 while (1) {
756 if (pos <= cur_pos)
757 break;
758 if (IS_LAST_CLUST(curclust, mydata->fatsize))
759 break;
760
761 newclust = get_fatent(mydata, curclust);
762 if (!IS_LAST_CLUST(newclust, mydata->fatsize) &&
763 CHECK_CLUST(newclust, mydata->fatsize)) {
764 debug("curclust: 0x%x\n", curclust);
765 debug("Invalid FAT entry\n");
766 return -1;
767 }
768
769 cur_pos += bytesperclust;
770 curclust = newclust;
771 }
772 if (IS_LAST_CLUST(curclust, mydata->fatsize)) {
773 assert(pos == cur_pos);
774 goto set_clusters;
775 }
776
777 assert(pos < cur_pos);
778 cur_pos -= bytesperclust;
779
780 /* overwrite */
781 assert(IS_LAST_CLUST(curclust, mydata->fatsize) ||
782 !CHECK_CLUST(curclust, mydata->fatsize));
783
784 while (1) {
785 /* search for allocated consecutive clusters */
786 actsize = bytesperclust;
787 endclust = curclust;
788 while (1) {
789 if (filesize <= (cur_pos + actsize))
790 break;
791
792 newclust = get_fatent(mydata, endclust);
793
794 if (IS_LAST_CLUST(newclust, mydata->fatsize))
795 break;
796 if (CHECK_CLUST(newclust, mydata->fatsize)) {
797 debug("curclust: 0x%x\n", curclust);
798 debug("Invalid FAT entry\n");
799 return -1;
800 }
801
802 actsize += bytesperclust;
803 endclust = newclust;
804 }
805
806 /* overwrite to <curclust..endclust> */
807 if (pos < cur_pos)
808 offset = 0;
809 else
810 offset = pos - cur_pos;
811 wsize = min(cur_pos + actsize, filesize) - pos;
812 if (get_set_cluster(mydata, curclust, offset,
813 buffer, wsize, &actsize)) {
814 printf("Error get-and-setting cluster\n");
815 return -1;
816 }
817 buffer += wsize;
818 *gotsize += wsize;
819 cur_pos += offset + wsize;
820
821 if (filesize <= cur_pos)
822 break;
823
824 /* CHECK: newclust = get_fatent(mydata, endclust); */
825
826 if (IS_LAST_CLUST(newclust, mydata->fatsize))
827 /* no more clusters */
828 break;
829
830 curclust = newclust;
831 }
832
833 if (filesize <= cur_pos) {
834 /* no more write */
835 newclust = get_fatent(mydata, endclust);
836 if (!IS_LAST_CLUST(newclust, mydata->fatsize)) {
837 /* truncate the rest */
838 clear_fatent(mydata, newclust);
839
840 /* Mark end of file in FAT */
841 if (mydata->fatsize == 12)
842 newclust = 0xfff;
843 else if (mydata->fatsize == 16)
844 newclust = 0xffff;
845 else if (mydata->fatsize == 32)
846 newclust = 0xfffffff;
847 set_fatent_value(mydata, endclust, newclust);
848 }
849
850 return 0;
851 }
852
853 curclust = endclust;
854 filesize -= cur_pos;
855 assert(!do_div(cur_pos, bytesperclust));
856
857 set_clusters:
858 /* allocate and write */
859 assert(!pos);
860
861 /* Assure that curclust is valid */
862 if (!curclust) {
863 curclust = find_empty_cluster(mydata);
864 set_start_cluster(mydata, dentptr, curclust);
865 } else {
866 newclust = get_fatent(mydata, curclust);
867
868 if (IS_LAST_CLUST(newclust, mydata->fatsize)) {
869 newclust = determine_fatent(mydata, curclust);
870 set_fatent_value(mydata, curclust, newclust);
871 curclust = newclust;
872 } else {
873 debug("error: something wrong\n");
874 return -1;
875 }
876 }
877
878 /* TODO: already partially written */
879 if (check_overflow(mydata, curclust, filesize)) {
880 printf("Error: no space left: %llu\n", filesize);
881 return -1;
882 }
883
884 actsize = bytesperclust;
885 endclust = curclust;
886 do {
887 /* search for consecutive clusters */
888 while (actsize < filesize) {
889 newclust = determine_fatent(mydata, endclust);
890
891 if ((newclust - 1) != endclust)
892 /* write to <curclust..endclust> */
893 goto getit;
894
895 if (CHECK_CLUST(newclust, mydata->fatsize)) {
896 debug("newclust: 0x%x\n", newclust);
897 debug("Invalid FAT entry\n");
898 return 0;
899 }
900 endclust = newclust;
901 actsize += bytesperclust;
902 }
903
904 /* set remaining bytes */
905 actsize = filesize;
906 if (set_cluster(mydata, curclust, buffer, (u32)actsize) != 0) {
907 debug("error: writing cluster\n");
908 return -1;
909 }
910 *gotsize += actsize;
911
912 /* Mark end of file in FAT */
913 if (mydata->fatsize == 12)
914 newclust = 0xfff;
915 else if (mydata->fatsize == 16)
916 newclust = 0xffff;
917 else if (mydata->fatsize == 32)
918 newclust = 0xfffffff;
919 set_fatent_value(mydata, endclust, newclust);
920
921 return 0;
922 getit:
923 if (set_cluster(mydata, curclust, buffer, (u32)actsize) != 0) {
924 debug("error: writing cluster\n");
925 return -1;
926 }
927 *gotsize += actsize;
928 filesize -= actsize;
929 buffer += actsize;
930
931 if (CHECK_CLUST(newclust, mydata->fatsize)) {
932 debug("newclust: 0x%x\n", newclust);
933 debug("Invalid FAT entry\n");
934 return 0;
935 }
936 actsize = bytesperclust;
937 curclust = endclust = newclust;
938 } while (1);
939
940 return 0;
941 }
942
943 /*
944 * Fill dir_entry
945 */
946 static void fill_dentry(fsdata *mydata, dir_entry *dentptr,
947 const char *filename, __u32 start_cluster, __u32 size, __u8 attr)
948 {
949 set_start_cluster(mydata, dentptr, start_cluster);
950 dentptr->size = cpu_to_le32(size);
951
952 dentptr->attr = attr;
953
954 set_name(dentptr, filename);
955 }
956
957 /*
958 * Find a directory entry based on filename or start cluster number
959 * If the directory entry is not found,
960 * the new position for writing a directory entry will be returned
961 */
962 static dir_entry *find_directory_entry(fat_itr *itr, char *filename)
963 {
964 int match = 0;
965
966 while (fat_itr_next(itr)) {
967 /* check both long and short name: */
968 if (!strcasecmp(filename, itr->name))
969 match = 1;
970 else if (itr->name != itr->s_name &&
971 !strcasecmp(filename, itr->s_name))
972 match = 1;
973
974 if (!match)
975 continue;
976
977 if (itr->dent->name[0] == '\0')
978 return NULL;
979 else
980 return itr->dent;
981 }
982
983 if (!itr->dent && !itr->is_root && new_dir_table(itr))
984 /* indicate that allocating dent failed */
985 itr->dent = NULL;
986
987 return NULL;
988 }
989
990 static int split_filename(char *filename, char **dirname, char **basename)
991 {
992 char *p, *last_slash, *last_slash_cont;
993
994 again:
995 p = filename;
996 last_slash = NULL;
997 last_slash_cont = NULL;
998 while (*p) {
999 if (ISDIRDELIM(*p)) {
1000 last_slash = p;
1001 last_slash_cont = p;
1002 /* continuous slashes */
1003 while (ISDIRDELIM(*p))
1004 last_slash_cont = p++;
1005 if (!*p)
1006 break;
1007 }
1008 p++;
1009 }
1010
1011 if (last_slash) {
1012 if (last_slash_cont == (filename + strlen(filename) - 1)) {
1013 /* remove trailing slashes */
1014 *last_slash = '\0';
1015 goto again;
1016 }
1017
1018 if (last_slash == filename) {
1019 /* avoid ""(null) directory */
1020 *dirname = "/";
1021 } else {
1022 *last_slash = '\0';
1023 *dirname = filename;
1024 }
1025
1026 *last_slash_cont = '\0';
1027 *basename = last_slash_cont + 1;
1028 } else {
1029 *dirname = "/"; /* root by default */
1030 *basename = filename;
1031 }
1032
1033 return 0;
1034 }
1035
1036 /**
1037 * normalize_longname() - check long file name and convert to lower case
1038 *
1039 * We assume here that the FAT file system is using an 8bit code page.
1040 * Linux typically uses CP437, EDK2 assumes CP1250.
1041 *
1042 * @l_filename: preallocated buffer receiving the normalized name
1043 * @filename: filename to normalize
1044 * Return: 0 on success, -1 on failure
1045 */
1046 static int normalize_longname(char *l_filename, const char *filename)
1047 {
1048 const char *p, illegal[] = "<>:\"/\\|?*";
1049
1050 if (strlen(filename) >= VFAT_MAXLEN_BYTES)
1051 return -1;
1052
1053 for (p = filename; *p; ++p) {
1054 if ((unsigned char)*p < 0x20)
1055 return -1;
1056 if (strchr(illegal, *p))
1057 return -1;
1058 }
1059
1060 strcpy(l_filename, filename);
1061 downcase(l_filename, VFAT_MAXLEN_BYTES);
1062
1063 return 0;
1064 }
1065
1066 int file_fat_write_at(const char *filename, loff_t pos, void *buffer,
1067 loff_t size, loff_t *actwrite)
1068 {
1069 dir_entry *retdent;
1070 fsdata datablock = { .fatbuf = NULL, };
1071 fsdata *mydata = &datablock;
1072 fat_itr *itr = NULL;
1073 int ret = -1;
1074 char *filename_copy, *parent, *basename;
1075 char l_filename[VFAT_MAXLEN_BYTES];
1076
1077 debug("writing %s\n", filename);
1078
1079 filename_copy = strdup(filename);
1080 if (!filename_copy)
1081 return -ENOMEM;
1082
1083 split_filename(filename_copy, &parent, &basename);
1084 if (!strlen(basename)) {
1085 ret = -EINVAL;
1086 goto exit;
1087 }
1088
1089 filename = basename;
1090 if (normalize_longname(l_filename, filename)) {
1091 printf("FAT: illegal filename (%s)\n", filename);
1092 ret = -EINVAL;
1093 goto exit;
1094 }
1095
1096 itr = malloc_cache_aligned(sizeof(fat_itr));
1097 if (!itr) {
1098 ret = -ENOMEM;
1099 goto exit;
1100 }
1101
1102 ret = fat_itr_root(itr, &datablock);
1103 if (ret)
1104 goto exit;
1105
1106 total_sector = datablock.total_sect;
1107
1108 ret = fat_itr_resolve(itr, parent, TYPE_DIR);
1109 if (ret) {
1110 printf("%s: doesn't exist (%d)\n", parent, ret);
1111 goto exit;
1112 }
1113
1114 retdent = find_directory_entry(itr, l_filename);
1115
1116 if (retdent) {
1117 if (fat_itr_isdir(itr)) {
1118 ret = -EISDIR;
1119 goto exit;
1120 }
1121
1122 /* A file exists */
1123 if (pos == -1)
1124 /* Append to the end */
1125 pos = FAT2CPU32(retdent->size);
1126 if (pos > retdent->size) {
1127 /* No hole allowed */
1128 ret = -EINVAL;
1129 goto exit;
1130 }
1131
1132 /* Update file size in a directory entry */
1133 retdent->size = cpu_to_le32(pos + size);
1134 } else {
1135 /* Create a new file */
1136
1137 if (itr->is_root) {
1138 /* root dir cannot have "." or ".." */
1139 if (!strcmp(l_filename, ".") ||
1140 !strcmp(l_filename, "..")) {
1141 ret = -EINVAL;
1142 goto exit;
1143 }
1144 }
1145
1146 if (!itr->dent) {
1147 printf("Error: allocating new dir entry\n");
1148 ret = -EIO;
1149 goto exit;
1150 }
1151
1152 if (pos) {
1153 /* No hole allowed */
1154 ret = -EINVAL;
1155 goto exit;
1156 }
1157
1158 memset(itr->dent, 0, sizeof(*itr->dent));
1159
1160 /* Calculate checksum for short name */
1161 set_name(itr->dent, filename);
1162
1163 /* Set long name entries */
1164 if (fill_dir_slot(itr, filename)) {
1165 ret = -EIO;
1166 goto exit;
1167 }
1168
1169 /* Set short name entry */
1170 fill_dentry(itr->fsdata, itr->dent, filename, 0, size, 0x20);
1171
1172 retdent = itr->dent;
1173 }
1174
1175 ret = set_contents(mydata, retdent, pos, buffer, size, actwrite);
1176 if (ret < 0) {
1177 printf("Error: writing contents\n");
1178 ret = -EIO;
1179 goto exit;
1180 }
1181 debug("attempt to write 0x%llx bytes\n", *actwrite);
1182
1183 /* Flush fat buffer */
1184 ret = flush_dirty_fat_buffer(mydata);
1185 if (ret) {
1186 printf("Error: flush fat buffer\n");
1187 ret = -EIO;
1188 goto exit;
1189 }
1190
1191 /* Write directory table to device */
1192 ret = flush_dir(itr);
1193 if (ret) {
1194 printf("Error: writing directory entry\n");
1195 ret = -EIO;
1196 }
1197
1198 exit:
1199 free(filename_copy);
1200 free(mydata->fatbuf);
1201 free(itr);
1202 return ret;
1203 }
1204
1205 int file_fat_write(const char *filename, void *buffer, loff_t offset,
1206 loff_t maxsize, loff_t *actwrite)
1207 {
1208 return file_fat_write_at(filename, offset, buffer, maxsize, actwrite);
1209 }
1210
1211 static int fat_dir_entries(fat_itr *itr)
1212 {
1213 fat_itr *dirs;
1214 fsdata fsdata = { .fatbuf = NULL, }, *mydata = &fsdata;
1215 /* for FATBUFSIZE */
1216 int count;
1217
1218 dirs = malloc_cache_aligned(sizeof(fat_itr));
1219 if (!dirs) {
1220 debug("Error: allocating memory\n");
1221 count = -ENOMEM;
1222 goto exit;
1223 }
1224
1225 /* duplicate fsdata */
1226 fat_itr_child(dirs, itr);
1227 fsdata = *dirs->fsdata;
1228
1229 /* allocate local fat buffer */
1230 fsdata.fatbuf = malloc_cache_aligned(FATBUFSIZE);
1231 if (!fsdata.fatbuf) {
1232 debug("Error: allocating memory\n");
1233 count = -ENOMEM;
1234 goto exit;
1235 }
1236 fsdata.fatbufnum = -1;
1237 dirs->fsdata = &fsdata;
1238
1239 for (count = 0; fat_itr_next(dirs); count++)
1240 ;
1241
1242 exit:
1243 free(fsdata.fatbuf);
1244 free(dirs);
1245 return count;
1246 }
1247
1248 static int delete_dentry(fat_itr *itr)
1249 {
1250 fsdata *mydata = itr->fsdata;
1251 dir_entry *dentptr = itr->dent;
1252
1253 /* free cluster blocks */
1254 clear_fatent(mydata, START(dentptr));
1255 if (flush_dirty_fat_buffer(mydata) < 0) {
1256 printf("Error: flush fat buffer\n");
1257 return -EIO;
1258 }
1259
1260 /*
1261 * update a directory entry
1262 * TODO:
1263 * - long file name support
1264 * - find and mark the "new" first invalid entry as name[0]=0x00
1265 */
1266 memset(dentptr, 0, sizeof(*dentptr));
1267 dentptr->name[0] = 0xe5;
1268
1269 if (flush_dir(itr)) {
1270 printf("error: writing directory entry\n");
1271 return -EIO;
1272 }
1273
1274 return 0;
1275 }
1276
1277 int fat_unlink(const char *filename)
1278 {
1279 fsdata fsdata = { .fatbuf = NULL, };
1280 fat_itr *itr = NULL;
1281 int n_entries, ret;
1282 char *filename_copy, *dirname, *basename;
1283
1284 filename_copy = strdup(filename);
1285 if (!filename_copy) {
1286 printf("Error: allocating memory\n");
1287 ret = -ENOMEM;
1288 goto exit;
1289 }
1290 split_filename(filename_copy, &dirname, &basename);
1291
1292 if (!strcmp(dirname, "/") && !strcmp(basename, "")) {
1293 printf("Error: cannot remove root\n");
1294 ret = -EINVAL;
1295 goto exit;
1296 }
1297
1298 itr = malloc_cache_aligned(sizeof(fat_itr));
1299 if (!itr) {
1300 printf("Error: allocating memory\n");
1301 ret = -ENOMEM;
1302 goto exit;
1303 }
1304
1305 ret = fat_itr_root(itr, &fsdata);
1306 if (ret)
1307 goto exit;
1308
1309 total_sector = fsdata.total_sect;
1310
1311 ret = fat_itr_resolve(itr, dirname, TYPE_DIR);
1312 if (ret) {
1313 printf("%s: doesn't exist (%d)\n", dirname, ret);
1314 ret = -ENOENT;
1315 goto exit;
1316 }
1317
1318 if (!find_directory_entry(itr, basename)) {
1319 printf("%s: doesn't exist\n", basename);
1320 ret = -ENOENT;
1321 goto exit;
1322 }
1323
1324 if (fat_itr_isdir(itr)) {
1325 n_entries = fat_dir_entries(itr);
1326 if (n_entries < 0) {
1327 ret = n_entries;
1328 goto exit;
1329 }
1330 if (n_entries > 2) {
1331 printf("Error: directory is not empty: %d\n",
1332 n_entries);
1333 ret = -EINVAL;
1334 goto exit;
1335 }
1336 }
1337
1338 ret = delete_dentry(itr);
1339
1340 exit:
1341 free(fsdata.fatbuf);
1342 free(itr);
1343 free(filename_copy);
1344
1345 return ret;
1346 }
1347
1348 int fat_mkdir(const char *new_dirname)
1349 {
1350 dir_entry *retdent;
1351 fsdata datablock = { .fatbuf = NULL, };
1352 fsdata *mydata = &datablock;
1353 fat_itr *itr = NULL;
1354 char *dirname_copy, *parent, *dirname;
1355 char l_dirname[VFAT_MAXLEN_BYTES];
1356 int ret = -1;
1357 loff_t actwrite;
1358 unsigned int bytesperclust;
1359 dir_entry *dotdent = NULL;
1360
1361 dirname_copy = strdup(new_dirname);
1362 if (!dirname_copy)
1363 goto exit;
1364
1365 split_filename(dirname_copy, &parent, &dirname);
1366 if (!strlen(dirname)) {
1367 ret = -EINVAL;
1368 goto exit;
1369 }
1370
1371 if (normalize_longname(l_dirname, dirname)) {
1372 printf("FAT: illegal filename (%s)\n", dirname);
1373 ret = -EINVAL;
1374 goto exit;
1375 }
1376
1377 itr = malloc_cache_aligned(sizeof(fat_itr));
1378 if (!itr) {
1379 ret = -ENOMEM;
1380 goto exit;
1381 }
1382
1383 ret = fat_itr_root(itr, &datablock);
1384 if (ret)
1385 goto exit;
1386
1387 total_sector = datablock.total_sect;
1388
1389 ret = fat_itr_resolve(itr, parent, TYPE_DIR);
1390 if (ret) {
1391 printf("%s: doesn't exist (%d)\n", parent, ret);
1392 goto exit;
1393 }
1394
1395 retdent = find_directory_entry(itr, l_dirname);
1396
1397 if (retdent) {
1398 printf("%s: already exists\n", l_dirname);
1399 ret = -EEXIST;
1400 goto exit;
1401 } else {
1402 if (itr->is_root) {
1403 /* root dir cannot have "." or ".." */
1404 if (!strcmp(l_dirname, ".") ||
1405 !strcmp(l_dirname, "..")) {
1406 ret = -EINVAL;
1407 goto exit;
1408 }
1409 }
1410
1411 if (!itr->dent) {
1412 printf("Error: allocating new dir entry\n");
1413 ret = -EIO;
1414 goto exit;
1415 }
1416
1417 memset(itr->dent, 0, sizeof(*itr->dent));
1418
1419 /* Set short name to set alias checksum field in dir_slot */
1420 set_name(itr->dent, dirname);
1421 fill_dir_slot(itr, dirname);
1422
1423 /* Set attribute as archive for regular file */
1424 fill_dentry(itr->fsdata, itr->dent, dirname, 0, 0,
1425 ATTR_DIR | ATTR_ARCH);
1426
1427 retdent = itr->dent;
1428 }
1429
1430 /* Default entries */
1431 bytesperclust = mydata->clust_size * mydata->sect_size;
1432 dotdent = malloc_cache_aligned(bytesperclust);
1433 if (!dotdent) {
1434 ret = -ENOMEM;
1435 goto exit;
1436 }
1437 memset(dotdent, 0, bytesperclust);
1438
1439 memcpy(dotdent[0].name, ". ", 8);
1440 memcpy(dotdent[0].ext, " ", 3);
1441 dotdent[0].attr = ATTR_DIR | ATTR_ARCH;
1442
1443 memcpy(dotdent[1].name, ".. ", 8);
1444 memcpy(dotdent[1].ext, " ", 3);
1445 dotdent[1].attr = ATTR_DIR | ATTR_ARCH;
1446 set_start_cluster(mydata, &dotdent[1], itr->start_clust);
1447
1448 ret = set_contents(mydata, retdent, 0, (__u8 *)dotdent,
1449 bytesperclust, &actwrite);
1450 if (ret < 0) {
1451 printf("Error: writing contents\n");
1452 goto exit;
1453 }
1454 /* Write twice for "." */
1455 set_start_cluster(mydata, &dotdent[0], START(retdent));
1456 ret = set_contents(mydata, retdent, 0, (__u8 *)dotdent,
1457 bytesperclust, &actwrite);
1458 if (ret < 0) {
1459 printf("Error: writing contents\n");
1460 goto exit;
1461 }
1462
1463 /* Flush fat buffer */
1464 ret = flush_dirty_fat_buffer(mydata);
1465 if (ret) {
1466 printf("Error: flush fat buffer\n");
1467 goto exit;
1468 }
1469
1470 /* Write directory table to device */
1471 ret = flush_dir(itr);
1472 if (ret)
1473 printf("Error: writing directory entry\n");
1474
1475 exit:
1476 free(dirname_copy);
1477 free(mydata->fatbuf);
1478 free(itr);
1479 free(dotdent);
1480 return ret;
1481 }