]> git.ipfire.org Git - thirdparty/u-boot.git/blame - fs/fat/fat_write.c
Merge branch 'next'
[thirdparty/u-boot.git] / fs / fat / fat_write.c
CommitLineData
83d290c5 1// SPDX-License-Identifier: GPL-2.0+
c30a15e5
DK
2/*
3 * fat_write.c
4 *
5 * R/W (V)FAT 12/16/32 filesystem implementation by Donggeun Kim
c30a15e5
DK
6 */
7
4f6daaca
SG
8#define LOG_CATEGORY LOGC_FS
9
c30a15e5
DK
10#include <common.h>
11#include <command.h>
12#include <config.h>
28cef9ca 13#include <div64.h>
c30a15e5 14#include <fat.h>
f7ae49fc 15#include <log.h>
336d4615 16#include <malloc.h>
c30a15e5 17#include <part.h>
28cef9ca
HS
18#include <rand.h>
19#include <asm/byteorder.h>
90526e9f 20#include <asm/cache.h>
fb7e16cc 21#include <linux/ctype.h>
9e374e7b 22#include <linux/math64.h>
c30a15e5
DK
23#include "fat.c"
24
3a331aee 25static dir_entry *find_directory_entry(fat_itr *itr, char *filename);
32a5f887 26static int new_dir_table(fat_itr *itr);
3a331aee 27
28cef9ca
HS
28/* Characters that may only be used in long file names */
29static const char LONG_ONLY_CHARS[] = "+,;=[]";
30
57b745e2
HS
31/* Combined size of the name and ext fields in the directory entry */
32#define SHORT_NAME_SIZE 11
33
28cef9ca
HS
34/**
35 * str2fat() - convert string to valid FAT name characters
36 *
37 * Stop when reaching end of @src or a period.
38 * Ignore spaces.
39 * Replace characters that may only be used in long names by underscores.
40 * Convert lower case characters to upper case.
41 *
42 * To avoid assumptions about the code page we do not use characters
43 * above 0x7f for the short name.
44 *
45 * @dest: destination buffer
46 * @src: source buffer
47 * @length: size of destination buffer
48 * Return: number of bytes in destination buffer
49 */
50static int str2fat(char *dest, char *src, int length)
c30a15e5
DK
51{
52 int i;
53
28cef9ca
HS
54 for (i = 0; i < length; ++src) {
55 char c = *src;
56
57 if (!c || c == '.')
58 break;
59 if (c == ' ')
60 continue;
61 if (strchr(LONG_ONLY_CHARS, c) || c > 0x7f)
62 c = '_';
63 else if (c >= 'a' && c <= 'z')
64 c &= 0xdf;
65 dest[i] = c;
66 ++i;
67 }
68 return i;
69}
70
3a331aee
HS
71/**
72 * fat_move_to_cluster() - position to first directory entry in cluster
73 *
74 * @itr: directory iterator
75 * @cluster cluster
76 * Return: 0 for success, -EIO on error
77 */
78static int fat_move_to_cluster(fat_itr *itr, unsigned int cluster)
79{
80 unsigned int nbytes;
81
82 /* position to the start of the directory */
83 itr->next_clust = cluster;
84 itr->last_cluster = 0;
85 if (!fat_next_cluster(itr, &nbytes))
86 return -EIO;
87 itr->dent = (dir_entry *)itr->block;
88 itr->remaining = nbytes / sizeof(dir_entry) - 1;
89 return 0;
90}
91
28cef9ca
HS
92/**
93 * set_name() - set short name in directory entry
94 *
95 * The function determines if the @filename is a valid short name.
96 * In this case no long name is needed.
97 *
98 * If a long name is needed, a short name is constructed.
99 *
3a331aee 100 * @itr: directory iterator
28cef9ca 101 * @filename: long file name
57b745e2 102 * @shortname: buffer of 11 bytes to receive chosen short name and extension
28cef9ca
HS
103 * Return: number of directory entries needed, negative on error
104 */
3a331aee 105static int set_name(fat_itr *itr, const char *filename, char *shortname)
28cef9ca
HS
106{
107 char *period;
108 char *pos;
109 int period_location;
110 char buf[13];
111 int i;
57b745e2 112 int ret;
41ac28c6 113 struct nameext dirent;
28cef9ca
HS
114
115 if (!filename)
116 return -EIO;
117
57b745e2
HS
118 /* Initialize buffer */
119 memset(&dirent, ' ', sizeof(dirent));
28cef9ca
HS
120
121 /* Convert filename to upper case short name */
122 period = strrchr(filename, '.');
123 pos = (char *)filename;
124 if (*pos == '.') {
125 pos = period + 1;
126 period = 0;
127 }
128 if (period)
57b745e2
HS
129 str2fat(dirent.ext, period + 1, sizeof(dirent.ext));
130 period_location = str2fat(dirent.name, pos, sizeof(dirent.name));
28cef9ca
HS
131 if (period_location < 0)
132 return period_location;
57b745e2
HS
133 if (*dirent.name == ' ')
134 *dirent.name = '_';
28cef9ca 135 /* 0xe5 signals a deleted directory entry. Replace it by 0x05. */
57b745e2
HS
136 if (*dirent.name == 0xe5)
137 *dirent.name = 0x05;
28cef9ca
HS
138
139 /* If filename and short name are the same, quit. */
57b745e2
HS
140 sprintf(buf, "%.*s.%.3s", period_location, dirent.name, dirent.ext);
141 if (!strcmp(buf, filename)) {
142 ret = 1;
143 goto out;
fefd9491
SH
144 } else if (!strcasecmp(buf, filename)) {
145 goto out_ret;
57b745e2 146 }
28cef9ca
HS
147
148 /* Construct an indexed short name */
149 for (i = 1; i < 0x200000; ++i) {
150 int suffix_len;
151 int suffix_start;
152 int j;
153
154 /* To speed up the search use random numbers */
155 if (i < 10) {
156 j = i;
157 } else {
158 j = 30 - fls(i);
159 j = 10 + (rand() >> j);
160 }
161 sprintf(buf, "~%d", j);
162 suffix_len = strlen(buf);
163 suffix_start = 8 - suffix_len;
164 if (suffix_start > period_location)
165 suffix_start = period_location;
57b745e2
HS
166 memcpy(dirent.name + suffix_start, buf, suffix_len);
167 if (*dirent.ext != ' ')
28cef9ca 168 sprintf(buf, "%.*s.%.3s", suffix_start + suffix_len,
57b745e2 169 dirent.name, dirent.ext);
28cef9ca
HS
170 else
171 sprintf(buf, "%.*s", suffix_start + suffix_len,
57b745e2 172 dirent.name);
3a331aee
HS
173 debug("generated short name: %s\n", buf);
174
175 /* Check that the short name does not exist yet. */
176 ret = fat_move_to_cluster(itr, itr->start_clust);
177 if (ret)
178 return ret;
179 if (find_directory_entry(itr, buf))
180 continue;
28cef9ca 181
fefd9491 182 goto out_ret;
c30a15e5 183 }
28cef9ca 184 return -EIO;
fefd9491
SH
185out_ret:
186 debug("chosen short name: %s\n", buf);
187 /* Each long name directory entry takes 13 characters. */
188 ret = (strlen(filename) + 25) / 13;
57b745e2 189out:
41ac28c6 190 memcpy(shortname, &dirent, SHORT_NAME_SIZE);
57b745e2 191 return ret;
c30a15e5
DK
192}
193
194static int total_sector;
079df722 195static int disk_write(__u32 block, __u32 nr_blocks, void *buf)
c30a15e5 196{
0a04ed86
ŁM
197 ulong ret;
198
2a981dc2 199 if (!cur_dev)
c30a15e5
DK
200 return -1;
201
079df722
DK
202 if (cur_part_info.start + block + nr_blocks >
203 cur_part_info.start + total_sector) {
c30a15e5
DK
204 printf("error: overflow occurs\n");
205 return -1;
206 }
207
2a981dc2 208 ret = blk_dwrite(cur_dev, cur_part_info.start + block, nr_blocks, buf);
0a04ed86
ŁM
209 if (nr_blocks && ret == 0)
210 return -1;
211
212 return ret;
c30a15e5
DK
213}
214
c30a15e5
DK
215/*
216 * Write fat buffer into block device
217 */
3c0ed9c3 218static int flush_dirty_fat_buffer(fsdata *mydata)
c30a15e5
DK
219{
220 int getsize = FATBUFBLOCKS;
221 __u32 fatlength = mydata->fatlength;
222 __u8 *bufptr = mydata->fatbuf;
223 __u32 startblock = mydata->fatbufnum * FATBUFBLOCKS;
224
3c0ed9c3
SB
225 debug("debug: evicting %d, dirty: %d\n", mydata->fatbufnum,
226 (int)mydata->fat_dirty);
227
228 if ((!mydata->fat_dirty) || (mydata->fatbufnum == -1))
229 return 0;
230
6c1a8080
SB
231 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
232 if (startblock + getsize > fatlength)
233 getsize = fatlength - startblock;
c30a15e5 234
6c1a8080 235 startblock += mydata->fat_sect;
c30a15e5
DK
236
237 /* Write FAT buf */
238 if (disk_write(startblock, getsize, bufptr) < 0) {
239 debug("error: writing FAT blocks\n");
240 return -1;
241 }
242
4ced2039 243 if (mydata->fats == 2) {
627182ea
DK
244 /* Update corresponding second FAT blocks */
245 startblock += mydata->fatlength;
246 if (disk_write(startblock, getsize, bufptr) < 0) {
247 debug("error: writing second FAT blocks\n");
248 return -1;
249 }
250 }
3c0ed9c3 251 mydata->fat_dirty = 0;
627182ea 252
c30a15e5
DK
253 return 0;
254}
255
32a5f887
HS
256/**
257 * fat_find_empty_dentries() - find a sequence of available directory entries
258 *
259 * @itr: directory iterator
260 * @count: number of directory entries to find
261 * Return: 0 on success or negative error number
262 */
3049a510 263static int fat_find_empty_dentries(fat_itr *itr, int count)
32a5f887
HS
264{
265 unsigned int cluster;
266 dir_entry *dent;
267 int remaining;
268 unsigned int n = 0;
269 int ret;
270
271 ret = fat_move_to_cluster(itr, itr->start_clust);
272 if (ret)
273 return ret;
274
275 for (;;) {
276 if (!itr->dent) {
277 log_debug("Not enough directory entries available\n");
278 return -ENOSPC;
279 }
041f0af3 280 switch (itr->dent->nameext.name[0]) {
32a5f887
HS
281 case 0x00:
282 case DELETED_FLAG:
283 if (!n) {
284 /* Remember first deleted directory entry */
285 cluster = itr->clust;
286 dent = itr->dent;
287 remaining = itr->remaining;
288 }
289 ++n;
290 if (n == count)
291 goto out;
292 break;
293 default:
294 n = 0;
295 break;
296 }
297
298 next_dent(itr);
299 if (!itr->dent &&
300 (!itr->is_root || itr->fsdata->fatsize == 32) &&
301 new_dir_table(itr))
302 return -ENOSPC;
303 }
304out:
305 /* Position back to first directory entry */
306 if (itr->clust != cluster) {
307 ret = fat_move_to_cluster(itr, cluster);
308 if (ret)
309 return ret;
310 }
311 itr->dent = dent;
312 itr->remaining = remaining;
313 return 0;
314}
315
c30a15e5
DK
316/*
317 * Set the file name information from 'name' into 'slotptr',
318 */
319static int str2slot(dir_slot *slotptr, const char *name, int *idx)
320{
321 int j, end_idx = 0;
322
323 for (j = 0; j <= 8; j += 2) {
324 if (name[*idx] == 0x00) {
325 slotptr->name0_4[j] = 0;
326 slotptr->name0_4[j + 1] = 0;
327 end_idx++;
328 goto name0_4;
329 }
330 slotptr->name0_4[j] = name[*idx];
331 (*idx)++;
332 end_idx++;
333 }
334 for (j = 0; j <= 10; j += 2) {
335 if (name[*idx] == 0x00) {
336 slotptr->name5_10[j] = 0;
337 slotptr->name5_10[j + 1] = 0;
338 end_idx++;
339 goto name5_10;
340 }
341 slotptr->name5_10[j] = name[*idx];
342 (*idx)++;
343 end_idx++;
344 }
345 for (j = 0; j <= 2; j += 2) {
346 if (name[*idx] == 0x00) {
347 slotptr->name11_12[j] = 0;
348 slotptr->name11_12[j + 1] = 0;
349 end_idx++;
350 goto name11_12;
351 }
352 slotptr->name11_12[j] = name[*idx];
353 (*idx)++;
354 end_idx++;
355 }
356
357 if (name[*idx] == 0x00)
358 return 1;
359
360 return 0;
361/* Not used characters are filled with 0xff 0xff */
362name0_4:
363 for (; end_idx < 5; end_idx++) {
364 slotptr->name0_4[end_idx * 2] = 0xff;
365 slotptr->name0_4[end_idx * 2 + 1] = 0xff;
366 }
367 end_idx = 5;
368name5_10:
369 end_idx -= 5;
370 for (; end_idx < 6; end_idx++) {
371 slotptr->name5_10[end_idx * 2] = 0xff;
372 slotptr->name5_10[end_idx * 2 + 1] = 0xff;
373 }
374 end_idx = 11;
375name11_12:
376 end_idx -= 11;
377 for (; end_idx < 2; end_idx++) {
378 slotptr->name11_12[end_idx * 2] = 0xff;
379 slotptr->name11_12[end_idx * 2 + 1] = 0xff;
380 }
381
382 return 1;
383}
384
9c709c7b 385static int flush_dir(fat_itr *itr);
c30a15e5 386
a343249b
HS
387/**
388 * fill_dir_slot() - fill directory entries for long name
389 *
390 * @itr: directory iterator
391 * @l_name: long name
392 * @shortname: short name
393 * Return: 0 for success, -errno otherwise
c30a15e5 394 */
4ced2039 395static int
a343249b 396fill_dir_slot(fat_itr *itr, const char *l_name, const char *shortname)
c30a15e5 397{
7aa1a6b7
TFC
398 __u8 temp_dir_slot_buffer[MAX_LFN_SLOT * sizeof(dir_slot)];
399 dir_slot *slotptr = (dir_slot *)temp_dir_slot_buffer;
8506eb8d 400 __u8 counter = 0, checksum;
c30a15e5 401 int idx = 0, ret;
c30a15e5 402
ed76f912 403 /* Get short file name checksum value */
041f0af3 404 checksum = mkcksum((void *)shortname);
c30a15e5
DK
405
406 do {
407 memset(slotptr, 0x00, sizeof(dir_slot));
408 ret = str2slot(slotptr, l_name, &idx);
409 slotptr->id = ++counter;
410 slotptr->attr = ATTR_VFAT;
411 slotptr->alias_checksum = checksum;
412 slotptr++;
413 } while (ret == 0);
414
415 slotptr--;
416 slotptr->id |= LAST_LONG_ENTRY_MASK;
417
418 while (counter >= 1) {
4ced2039 419 memcpy(itr->dent, slotptr, sizeof(dir_slot));
c30a15e5
DK
420 slotptr--;
421 counter--;
9c709c7b 422
e97eb638
HS
423 if (!itr->remaining) {
424 /* Write directory table to device */
425 ret = flush_dir(itr);
426 if (ret)
427 return ret;
428 }
9c709c7b 429
3049a510
HS
430 next_dent(itr);
431 if (!itr->dent)
432 return -EIO;
c30a15e5
DK
433 }
434
c30a15e5
DK
435 return 0;
436}
437
c30a15e5 438/*
49abbd9c 439 * Set the entry at index 'entry' in a FAT (12/16/32) table.
c30a15e5
DK
440 */
441static int set_fatent_value(fsdata *mydata, __u32 entry, __u32 entry_value)
442{
49abbd9c
PS
443 __u32 bufnum, offset, off16;
444 __u16 val1, val2;
c30a15e5
DK
445
446 switch (mydata->fatsize) {
447 case 32:
448 bufnum = entry / FAT32BUFSIZE;
449 offset = entry - bufnum * FAT32BUFSIZE;
450 break;
451 case 16:
452 bufnum = entry / FAT16BUFSIZE;
453 offset = entry - bufnum * FAT16BUFSIZE;
454 break;
49abbd9c
PS
455 case 12:
456 bufnum = entry / FAT12BUFSIZE;
457 offset = entry - bufnum * FAT12BUFSIZE;
458 break;
c30a15e5
DK
459 default:
460 /* Unsupported FAT size */
461 return -1;
462 }
463
464 /* Read a new block of FAT entries into the cache. */
465 if (bufnum != mydata->fatbufnum) {
466 int getsize = FATBUFBLOCKS;
467 __u8 *bufptr = mydata->fatbuf;
468 __u32 fatlength = mydata->fatlength;
469 __u32 startblock = bufnum * FATBUFBLOCKS;
470
6c1a8080
SB
471 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
472 if (startblock + getsize > fatlength)
473 getsize = fatlength - startblock;
c30a15e5 474
3c0ed9c3
SB
475 if (flush_dirty_fat_buffer(mydata) < 0)
476 return -1;
c30a15e5 477
6c1a8080
SB
478 startblock += mydata->fat_sect;
479
c30a15e5
DK
480 if (disk_read(startblock, getsize, bufptr) < 0) {
481 debug("Error reading FAT blocks\n");
482 return -1;
483 }
484 mydata->fatbufnum = bufnum;
485 }
486
3c0ed9c3
SB
487 /* Mark as dirty */
488 mydata->fat_dirty = 1;
489
c30a15e5
DK
490 /* Set the actual entry */
491 switch (mydata->fatsize) {
492 case 32:
493 ((__u32 *) mydata->fatbuf)[offset] = cpu_to_le32(entry_value);
494 break;
495 case 16:
496 ((__u16 *) mydata->fatbuf)[offset] = cpu_to_le16(entry_value);
49abbd9c
PS
497 break;
498 case 12:
499 off16 = (offset * 3) / 4;
500
501 switch (offset & 0x3) {
502 case 0:
503 val1 = cpu_to_le16(entry_value) & 0xfff;
504 ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff;
505 ((__u16 *)mydata->fatbuf)[off16] |= val1;
506 break;
507 case 1:
508 val1 = cpu_to_le16(entry_value) & 0xf;
509 val2 = (cpu_to_le16(entry_value) >> 4) & 0xff;
510
511 ((__u16 *)mydata->fatbuf)[off16] &= ~0xf000;
512 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 12);
513
514 ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xff;
515 ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
516 break;
517 case 2:
518 val1 = cpu_to_le16(entry_value) & 0xff;
519 val2 = (cpu_to_le16(entry_value) >> 8) & 0xf;
520
521 ((__u16 *)mydata->fatbuf)[off16] &= ~0xff00;
522 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 8);
523
524 ((__u16 *)mydata->fatbuf)[off16 + 1] &= ~0xf;
525 ((__u16 *)mydata->fatbuf)[off16 + 1] |= val2;
526 break;
527 case 3:
528 val1 = cpu_to_le16(entry_value) & 0xfff;
529 ((__u16 *)mydata->fatbuf)[off16] &= ~0xfff0;
530 ((__u16 *)mydata->fatbuf)[off16] |= (val1 << 4);
531 break;
532 default:
533 break;
534 }
535
c30a15e5
DK
536 break;
537 default:
538 return -1;
539 }
540
541 return 0;
542}
543
544/*
49abbd9c 545 * Determine the next free cluster after 'entry' in a FAT (12/16/32) table
ae1755be 546 * and link it to 'entry'. EOC marker is not set on returned entry.
c30a15e5
DK
547 */
548static __u32 determine_fatent(fsdata *mydata, __u32 entry)
549{
550 __u32 next_fat, next_entry = entry + 1;
551
552 while (1) {
b8948d2a 553 next_fat = get_fatent(mydata, next_entry);
c30a15e5 554 if (next_fat == 0) {
ae1755be 555 /* found free entry, link to entry */
c30a15e5
DK
556 set_fatent_value(mydata, entry, next_entry);
557 break;
558 }
559 next_entry++;
560 }
561 debug("FAT%d: entry: %08x, entry_value: %04x\n",
562 mydata->fatsize, entry, next_entry);
563
564 return next_entry;
565}
566
f105fe7b 567/**
a9f6706c 568 * set_sectors() - write data to sectors
f105fe7b 569 *
a9f6706c 570 * Write 'size' bytes from 'buffer' into the specified sector.
f105fe7b
HS
571 *
572 * @mydata: data to be written
a9f6706c 573 * @startsect: sector to be written to
f105fe7b
HS
574 * @buffer: data to be written
575 * @size: bytes to be written (but not more than the size of a cluster)
576 * Return: 0 on success, -1 otherwise
c30a15e5
DK
577 */
578static int
a9f6706c 579set_sectors(fsdata *mydata, u32 startsect, u8 *buffer, u32 size)
c30a15e5 580{
8133f43d 581 int ret;
c30a15e5 582
a9f6706c 583 debug("startsect: %d\n", startsect);
c30a15e5 584
8133f43d
BT
585 if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
586 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
587
1c381ceb 588 debug("FAT: Misaligned buffer address (%p)\n", buffer);
8133f43d
BT
589
590 while (size >= mydata->sect_size) {
591 memcpy(tmpbuf, buffer, mydata->sect_size);
592 ret = disk_write(startsect++, 1, tmpbuf);
593 if (ret != 1) {
594 debug("Error writing data (got %d)\n", ret);
595 return -1;
596 }
597
598 buffer += mydata->sect_size;
599 size -= mydata->sect_size;
600 }
601 } else if (size >= mydata->sect_size) {
84ca3055
HS
602 u32 nsects;
603
a9f6706c
AT
604 nsects = size / mydata->sect_size;
605 ret = disk_write(startsect, nsects, buffer);
606 if (ret != nsects) {
8133f43d 607 debug("Error writing data (got %d)\n", ret);
6b8f185f
WJ
608 return -1;
609 }
8133f43d 610
a9f6706c
AT
611 startsect += nsects;
612 buffer += nsects * mydata->sect_size;
613 size -= nsects * mydata->sect_size;
c30a15e5
DK
614 }
615
8133f43d
BT
616 if (size) {
617 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
f105fe7b
HS
618 /* Do not leak content of stack */
619 memset(tmpbuf, 0, mydata->sect_size);
8133f43d
BT
620 memcpy(tmpbuf, buffer, size);
621 ret = disk_write(startsect, 1, tmpbuf);
622 if (ret != 1) {
623 debug("Error writing data (got %d)\n", ret);
c30a15e5
DK
624 return -1;
625 }
c30a15e5
DK
626 }
627
628 return 0;
629}
630
a9f6706c
AT
631/**
632 * set_cluster() - write data to cluster
633 *
634 * Write 'size' bytes from 'buffer' into the specified cluster.
635 *
636 * @mydata: data to be written
637 * @clustnum: cluster to be written to
638 * @buffer: data to be written
639 * @size: bytes to be written (but not more than the size of a cluster)
640 * Return: 0 on success, -1 otherwise
641 */
642static int
643set_cluster(fsdata *mydata, u32 clustnum, u8 *buffer, u32 size)
644{
645 return set_sectors(mydata, clust_to_sect(mydata, clustnum),
646 buffer, size);
647}
648
e97eb638
HS
649/**
650 * flush_dir() - flush directory
651 *
652 * @itr: directory iterator
653 * Return: 0 for success, -EIO on error
654 */
655static int flush_dir(fat_itr *itr)
a9f6706c
AT
656{
657 fsdata *mydata = itr->fsdata;
658 u32 startsect, sect_offset, nsects;
e97eb638 659 int ret;
a9f6706c 660
e97eb638
HS
661 if (!itr->is_root || mydata->fatsize == 32) {
662 ret = set_cluster(mydata, itr->clust, itr->block,
663 mydata->clust_size * mydata->sect_size);
664 goto out;
665 }
a9f6706c
AT
666
667 sect_offset = itr->clust * mydata->clust_size;
668 startsect = mydata->rootdir_sect + sect_offset;
669 /* do not write past the end of rootdir */
670 nsects = min_t(u32, mydata->clust_size,
671 mydata->rootdir_size - sect_offset);
672
e97eb638
HS
673 ret = set_sectors(mydata, startsect, itr->block,
674 nsects * mydata->sect_size);
675out:
676 if (ret) {
677 log_err("Error: writing directory entry\n");
678 return -EIO;
679 }
680 return 0;
a9f6706c
AT
681}
682
cb8af8af
AT
683/*
684 * Read and modify data on existing and consecutive cluster blocks
685 */
686static int
687get_set_cluster(fsdata *mydata, __u32 clustnum, loff_t pos, __u8 *buffer,
688 loff_t size, loff_t *gotsize)
689{
5a8d1f60 690 static u8 *tmpbuf_cluster;
cb8af8af
AT
691 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
692 __u32 startsect;
693 loff_t wsize;
694 int clustcount, i, ret;
695
696 *gotsize = 0;
697 if (!size)
698 return 0;
699
5a8d1f60
HS
700 if (!tmpbuf_cluster) {
701 tmpbuf_cluster = memalign(ARCH_DMA_MINALIGN, MAX_CLUSTSIZE);
702 if (!tmpbuf_cluster)
703 return -1;
704 }
705
cb8af8af
AT
706 assert(pos < bytesperclust);
707 startsect = clust_to_sect(mydata, clustnum);
708
709 debug("clustnum: %d, startsect: %d, pos: %lld\n",
710 clustnum, startsect, pos);
711
712 /* partial write at beginning */
713 if (pos) {
714 wsize = min(bytesperclust - pos, size);
715 ret = disk_read(startsect, mydata->clust_size, tmpbuf_cluster);
716 if (ret != mydata->clust_size) {
717 debug("Error reading data (got %d)\n", ret);
718 return -1;
719 }
720
721 memcpy(tmpbuf_cluster + pos, buffer, wsize);
722 ret = disk_write(startsect, mydata->clust_size, tmpbuf_cluster);
723 if (ret != mydata->clust_size) {
724 debug("Error writing data (got %d)\n", ret);
725 return -1;
726 }
727
728 size -= wsize;
729 buffer += wsize;
730 *gotsize += wsize;
731
732 startsect += mydata->clust_size;
733
734 if (!size)
735 return 0;
736 }
737
738 /* full-cluster write */
739 if (size >= bytesperclust) {
740 clustcount = lldiv(size, bytesperclust);
741
742 if (!((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1))) {
743 wsize = clustcount * bytesperclust;
744 ret = disk_write(startsect,
745 clustcount * mydata->clust_size,
746 buffer);
747 if (ret != clustcount * mydata->clust_size) {
748 debug("Error writing data (got %d)\n", ret);
749 return -1;
750 }
751
752 size -= wsize;
753 buffer += wsize;
754 *gotsize += wsize;
755
756 startsect += clustcount * mydata->clust_size;
757 } else {
758 for (i = 0; i < clustcount; i++) {
759 memcpy(tmpbuf_cluster, buffer, bytesperclust);
760 ret = disk_write(startsect,
761 mydata->clust_size,
762 tmpbuf_cluster);
763 if (ret != mydata->clust_size) {
764 debug("Error writing data (got %d)\n",
765 ret);
766 return -1;
767 }
768
769 size -= bytesperclust;
770 buffer += bytesperclust;
771 *gotsize += bytesperclust;
772
773 startsect += mydata->clust_size;
774 }
775 }
776 }
777
778 /* partial write at end */
779 if (size) {
780 wsize = size;
781 ret = disk_read(startsect, mydata->clust_size, tmpbuf_cluster);
782 if (ret != mydata->clust_size) {
783 debug("Error reading data (got %d)\n", ret);
784 return -1;
785 }
786 memcpy(tmpbuf_cluster, buffer, wsize);
787 ret = disk_write(startsect, mydata->clust_size, tmpbuf_cluster);
788 if (ret != mydata->clust_size) {
789 debug("Error writing data (got %d)\n", ret);
790 return -1;
791 }
792
793 size -= wsize;
cb8af8af
AT
794 *gotsize += wsize;
795 }
796
797 assert(!size);
798
799 return 0;
800}
801
c30a15e5
DK
802/*
803 * Find the first empty cluster
804 */
805static int find_empty_cluster(fsdata *mydata)
806{
807 __u32 fat_val, entry = 3;
808
809 while (1) {
b8948d2a 810 fat_val = get_fatent(mydata, entry);
c30a15e5
DK
811 if (fat_val == 0)
812 break;
813 entry++;
814 }
815
816 return entry;
817}
818
569b0e19
HS
819/**
820 * new_dir_table() - allocate a cluster for additional directory entries
821 *
822 * @itr: directory iterator
823 * Return: 0 on success, -EIO otherwise
c30a15e5 824 */
9c709c7b 825static int new_dir_table(fat_itr *itr)
c30a15e5 826{
4ced2039 827 fsdata *mydata = itr->fsdata;
c30a15e5 828 int dir_newclust = 0;
569b0e19 829 int dir_oldclust = itr->clust;
4ced2039 830 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
c30a15e5 831
c30a15e5 832 dir_newclust = find_empty_cluster(mydata);
569b0e19
HS
833
834 /*
835 * Flush before updating FAT to ensure valid directory structure
836 * in case of failure.
837 */
838 itr->clust = dir_newclust;
839 itr->next_clust = dir_newclust;
840 memset(itr->block, 0x00, bytesperclust);
841 if (flush_dir(itr))
842 return -EIO;
843
844 set_fatent_value(mydata, dir_oldclust, dir_newclust);
c30a15e5
DK
845 if (mydata->fatsize == 32)
846 set_fatent_value(mydata, dir_newclust, 0xffffff8);
847 else if (mydata->fatsize == 16)
848 set_fatent_value(mydata, dir_newclust, 0xfff8);
49abbd9c
PS
849 else if (mydata->fatsize == 12)
850 set_fatent_value(mydata, dir_newclust, 0xff8);
c30a15e5 851
3c0ed9c3 852 if (flush_dirty_fat_buffer(mydata) < 0)
569b0e19 853 return -EIO;
c30a15e5 854
4ced2039
AT
855 itr->dent = (dir_entry *)itr->block;
856 itr->last_cluster = 1;
857 itr->remaining = bytesperclust / sizeof(dir_entry) - 1;
c30a15e5 858
4ced2039 859 return 0;
c30a15e5
DK
860}
861
862/*
863 * Set empty cluster from 'entry' to the end of a file
864 */
865static int clear_fatent(fsdata *mydata, __u32 entry)
866{
867 __u32 fat_val;
868
49abbd9c 869 while (!CHECK_CLUST(entry, mydata->fatsize)) {
b8948d2a 870 fat_val = get_fatent(mydata, entry);
c30a15e5
DK
871 if (fat_val != 0)
872 set_fatent_value(mydata, entry, 0);
873 else
874 break;
875
c30a15e5
DK
876 entry = fat_val;
877 }
878
879 /* Flush fat buffer */
3c0ed9c3 880 if (flush_dirty_fat_buffer(mydata) < 0)
c30a15e5
DK
881 return -1;
882
883 return 0;
884}
885
704df6aa
AT
886/*
887 * Set start cluster in directory entry
888 */
889static void set_start_cluster(const fsdata *mydata, dir_entry *dentptr,
890 __u32 start_cluster)
891{
892 if (mydata->fatsize == 32)
893 dentptr->starthi =
894 cpu_to_le16((start_cluster & 0xffff0000) >> 16);
895 dentptr->start = cpu_to_le16(start_cluster & 0xffff);
896}
897
898/*
899 * Check whether adding a file makes the file system to
900 * exceed the size of the block device
901 * Return -1 when overflow occurs, otherwise return 0
902 */
903static int check_overflow(fsdata *mydata, __u32 clustnum, loff_t size)
904{
905 __u32 startsect, sect_num, offset;
906
907 if (clustnum > 0)
908 startsect = clust_to_sect(mydata, clustnum);
909 else
910 startsect = mydata->rootdir_sect;
911
912 sect_num = div_u64_rem(size, mydata->sect_size, &offset);
913
914 if (offset != 0)
915 sect_num++;
916
917 if (startsect + sect_num > total_sector)
918 return -1;
919 return 0;
920}
921
c30a15e5
DK
922/*
923 * Write at most 'maxsize' bytes from 'buffer' into
924 * the file associated with 'dentptr'
1ad0b98a
SR
925 * Update the number of bytes written in *gotsize and return 0
926 * or return -1 on fatal errors.
c30a15e5
DK
927 */
928static int
704df6aa
AT
929set_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos, __u8 *buffer,
930 loff_t maxsize, loff_t *gotsize)
c30a15e5 931{
c30a15e5
DK
932 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
933 __u32 curclust = START(dentptr);
934 __u32 endclust = 0, newclust = 0;
7274b763
HS
935 u64 cur_pos, filesize;
936 loff_t offset, actsize, wsize;
c30a15e5 937
1ad0b98a 938 *gotsize = 0;
cb8af8af 939 filesize = pos + maxsize;
c30a15e5 940
1ad0b98a 941 debug("%llu bytes\n", filesize);
c30a15e5 942
cb8af8af
AT
943 if (!filesize) {
944 if (!curclust)
945 return 0;
946 if (!CHECK_CLUST(curclust, mydata->fatsize) ||
947 IS_LAST_CLUST(curclust, mydata->fatsize)) {
948 clear_fatent(mydata, curclust);
949 set_start_cluster(mydata, dentptr, 0);
950 return 0;
951 }
952 debug("curclust: 0x%x\n", curclust);
953 debug("Invalid FAT entry\n");
954 return -1;
955 }
956
957 if (!curclust) {
958 assert(pos == 0);
959 goto set_clusters;
960 }
961
962 /* go to cluster at pos */
963 cur_pos = bytesperclust;
964 while (1) {
965 if (pos <= cur_pos)
966 break;
967 if (IS_LAST_CLUST(curclust, mydata->fatsize))
968 break;
969
970 newclust = get_fatent(mydata, curclust);
971 if (!IS_LAST_CLUST(newclust, mydata->fatsize) &&
972 CHECK_CLUST(newclust, mydata->fatsize)) {
973 debug("curclust: 0x%x\n", curclust);
974 debug("Invalid FAT entry\n");
1254b44a
BT
975 return -1;
976 }
cb8af8af
AT
977
978 cur_pos += bytesperclust;
979 curclust = newclust;
980 }
981 if (IS_LAST_CLUST(curclust, mydata->fatsize)) {
982 assert(pos == cur_pos);
983 goto set_clusters;
704df6aa
AT
984 }
985
cb8af8af
AT
986 assert(pos < cur_pos);
987 cur_pos -= bytesperclust;
704df6aa 988
cb8af8af
AT
989 /* overwrite */
990 assert(IS_LAST_CLUST(curclust, mydata->fatsize) ||
991 !CHECK_CLUST(curclust, mydata->fatsize));
992
993 while (1) {
994 /* search for allocated consecutive clusters */
995 actsize = bytesperclust;
996 endclust = curclust;
997 while (1) {
998 if (filesize <= (cur_pos + actsize))
999 break;
1000
1001 newclust = get_fatent(mydata, endclust);
1002
5e615b74
MS
1003 if (newclust != endclust + 1)
1004 break;
cb8af8af
AT
1005 if (IS_LAST_CLUST(newclust, mydata->fatsize))
1006 break;
1007 if (CHECK_CLUST(newclust, mydata->fatsize)) {
1008 debug("curclust: 0x%x\n", curclust);
1009 debug("Invalid FAT entry\n");
1010 return -1;
1011 }
1012
1013 actsize += bytesperclust;
1014 endclust = newclust;
1015 }
1016
1017 /* overwrite to <curclust..endclust> */
1018 if (pos < cur_pos)
1019 offset = 0;
1020 else
1021 offset = pos - cur_pos;
a54ece40
MS
1022 wsize = min_t(unsigned long long, actsize, filesize - cur_pos);
1023 wsize -= offset;
1024
cb8af8af
AT
1025 if (get_set_cluster(mydata, curclust, offset,
1026 buffer, wsize, &actsize)) {
1027 printf("Error get-and-setting cluster\n");
1028 return -1;
1029 }
1030 buffer += wsize;
1031 *gotsize += wsize;
1032 cur_pos += offset + wsize;
1033
1034 if (filesize <= cur_pos)
1035 break;
1036
cb8af8af
AT
1037 if (IS_LAST_CLUST(newclust, mydata->fatsize))
1038 /* no more clusters */
1039 break;
1040
1041 curclust = newclust;
1042 }
1043
1044 if (filesize <= cur_pos) {
1045 /* no more write */
1046 newclust = get_fatent(mydata, endclust);
1047 if (!IS_LAST_CLUST(newclust, mydata->fatsize)) {
1048 /* truncate the rest */
1049 clear_fatent(mydata, newclust);
1050
1051 /* Mark end of file in FAT */
1052 if (mydata->fatsize == 12)
1053 newclust = 0xfff;
1054 else if (mydata->fatsize == 16)
1055 newclust = 0xffff;
1056 else if (mydata->fatsize == 32)
1057 newclust = 0xfffffff;
1058 set_fatent_value(mydata, endclust, newclust);
1059 }
1060
1061 return 0;
1062 }
1063
1064 curclust = endclust;
1065 filesize -= cur_pos;
7274b763 1066 assert(!do_div(cur_pos, bytesperclust));
cb8af8af
AT
1067
1068set_clusters:
1069 /* allocate and write */
1070 assert(!pos);
1071
1072 /* Assure that curclust is valid */
1073 if (!curclust) {
1074 curclust = find_empty_cluster(mydata);
1075 set_start_cluster(mydata, dentptr, curclust);
1076 } else {
1077 newclust = get_fatent(mydata, curclust);
1078
1079 if (IS_LAST_CLUST(newclust, mydata->fatsize)) {
1080 newclust = determine_fatent(mydata, curclust);
1081 set_fatent_value(mydata, curclust, newclust);
1082 curclust = newclust;
1083 } else {
1084 debug("error: something wrong\n");
1085 return -1;
1086 }
1087 }
1088
1089 /* TODO: already partially written */
704df6aa
AT
1090 if (check_overflow(mydata, curclust, filesize)) {
1091 printf("Error: no space left: %llu\n", filesize);
1092 return -1;
1254b44a
BT
1093 }
1094
c30a15e5
DK
1095 actsize = bytesperclust;
1096 endclust = curclust;
1097 do {
1098 /* search for consecutive clusters */
1099 while (actsize < filesize) {
1100 newclust = determine_fatent(mydata, endclust);
1101
1102 if ((newclust - 1) != endclust)
704df6aa 1103 /* write to <curclust..endclust> */
c30a15e5
DK
1104 goto getit;
1105
1106 if (CHECK_CLUST(newclust, mydata->fatsize)) {
5e1a860e 1107 debug("newclust: 0x%x\n", newclust);
c30a15e5 1108 debug("Invalid FAT entry\n");
1ad0b98a 1109 return 0;
c30a15e5
DK
1110 }
1111 endclust = newclust;
1112 actsize += bytesperclust;
1113 }
c30a15e5
DK
1114
1115 /* set remaining bytes */
c30a15e5 1116 actsize = filesize;
f105fe7b 1117 if (set_cluster(mydata, curclust, buffer, (u32)actsize) != 0) {
c30a15e5
DK
1118 debug("error: writing cluster\n");
1119 return -1;
1120 }
1ad0b98a 1121 *gotsize += actsize;
c30a15e5
DK
1122
1123 /* Mark end of file in FAT */
49abbd9c
PS
1124 if (mydata->fatsize == 12)
1125 newclust = 0xfff;
1126 else if (mydata->fatsize == 16)
c30a15e5
DK
1127 newclust = 0xffff;
1128 else if (mydata->fatsize == 32)
1129 newclust = 0xfffffff;
1130 set_fatent_value(mydata, endclust, newclust);
1131
1ad0b98a 1132 return 0;
c30a15e5 1133getit:
f105fe7b 1134 if (set_cluster(mydata, curclust, buffer, (u32)actsize) != 0) {
c30a15e5
DK
1135 debug("error: writing cluster\n");
1136 return -1;
1137 }
1ad0b98a 1138 *gotsize += actsize;
c30a15e5
DK
1139 filesize -= actsize;
1140 buffer += actsize;
1141
5e1a860e
BT
1142 if (CHECK_CLUST(newclust, mydata->fatsize)) {
1143 debug("newclust: 0x%x\n", newclust);
c30a15e5 1144 debug("Invalid FAT entry\n");
1ad0b98a 1145 return 0;
c30a15e5
DK
1146 }
1147 actsize = bytesperclust;
1148 curclust = endclust = newclust;
1149 } while (1);
c30a15e5 1150
704df6aa 1151 return 0;
1254b44a
BT
1152}
1153
57b745e2
HS
1154/**
1155 * fill_dentry() - fill directory entry with shortname
1156 *
1157 * @mydata: private filesystem parameters
1158 * @dentptr: directory entry
1159 * @shortname: chosen short name
1160 * @start_cluster: first cluster of file
1161 * @size: file size
1162 * @attr: file attributes
1254b44a
BT
1163 */
1164static void fill_dentry(fsdata *mydata, dir_entry *dentptr,
57b745e2 1165 const char *shortname, __u32 start_cluster, __u32 size, __u8 attr)
1254b44a 1166{
57b745e2
HS
1167 memset(dentptr, 0, sizeof(*dentptr));
1168
1254b44a 1169 set_start_cluster(mydata, dentptr, start_cluster);
c30a15e5
DK
1170 dentptr->size = cpu_to_le32(size);
1171
1172 dentptr->attr = attr;
1173
041f0af3 1174 memcpy(&dentptr->nameext, shortname, SHORT_NAME_SIZE);
c30a15e5
DK
1175}
1176
1e51c8d6
HS
1177/**
1178 * find_directory_entry() - find a directory entry by filename
1179 *
1180 * @itr: directory iterator
1181 * @filename: name of file to find
1182 * Return: directory entry or NULL
c30a15e5 1183 */
4ced2039 1184static dir_entry *find_directory_entry(fat_itr *itr, char *filename)
c30a15e5 1185{
4ced2039 1186 int match = 0;
c30a15e5 1187
4ced2039
AT
1188 while (fat_itr_next(itr)) {
1189 /* check both long and short name: */
1190 if (!strcasecmp(filename, itr->name))
1191 match = 1;
1192 else if (itr->name != itr->s_name &&
1193 !strcasecmp(filename, itr->s_name))
1194 match = 1;
c30a15e5 1195
4ced2039
AT
1196 if (!match)
1197 continue;
c30a15e5 1198
041f0af3 1199 if (itr->dent->nameext.name[0] == '\0')
c30a15e5 1200 return NULL;
4ced2039
AT
1201 else
1202 return itr->dent;
1203 }
c30a15e5 1204
4ced2039
AT
1205 return NULL;
1206}
c30a15e5 1207
4ced2039
AT
1208static int split_filename(char *filename, char **dirname, char **basename)
1209{
1210 char *p, *last_slash, *last_slash_cont;
1211
1212again:
1213 p = filename;
1214 last_slash = NULL;
1215 last_slash_cont = NULL;
1216 while (*p) {
1217 if (ISDIRDELIM(*p)) {
1218 last_slash = p;
1219 last_slash_cont = p;
1220 /* continuous slashes */
1221 while (ISDIRDELIM(*p))
1222 last_slash_cont = p++;
1223 if (!*p)
1224 break;
c30a15e5 1225 }
4ced2039
AT
1226 p++;
1227 }
c30a15e5 1228
4ced2039
AT
1229 if (last_slash) {
1230 if (last_slash_cont == (filename + strlen(filename) - 1)) {
1231 /* remove trailing slashes */
1232 *last_slash = '\0';
1233 goto again;
dd6d7967
WJ
1234 }
1235
4ced2039
AT
1236 if (last_slash == filename) {
1237 /* avoid ""(null) directory */
1238 *dirname = "/";
1239 } else {
1240 *last_slash = '\0';
1241 *dirname = filename;
c30a15e5 1242 }
4ced2039
AT
1243
1244 *last_slash_cont = '\0';
3ecc5277 1245 filename = last_slash_cont + 1;
4ced2039
AT
1246 } else {
1247 *dirname = "/"; /* root by default */
c30a15e5
DK
1248 }
1249
3ecc5277
HS
1250 /*
1251 * The FAT32 File System Specification v1.03 requires leading and
1252 * trailing spaces as well as trailing periods to be ignored.
1253 */
1254 for (; *filename == ' '; ++filename)
1255 ;
1256
1257 /* Keep special entries '.' and '..' */
1258 if (filename[0] == '.' &&
1259 (!filename[1] || (filename[1] == '.' && !filename[2])))
1260 goto done;
1261
1262 /* Remove trailing periods and spaces */
1263 for (p = filename + strlen(filename) - 1; p >= filename; --p) {
1264 switch (*p) {
1265 case ' ':
1266 case '.':
1267 *p = 0;
1268 break;
1269 default:
1270 goto done;
1271 }
1272 }
1273
1274done:
1275 *basename = filename;
1276
4ced2039 1277 return 0;
c30a15e5
DK
1278}
1279
7b437807
HS
1280/**
1281 * normalize_longname() - check long file name and convert to lower case
1282 *
1283 * We assume here that the FAT file system is using an 8bit code page.
1284 * Linux typically uses CP437, EDK2 assumes CP1250.
1285 *
1286 * @l_filename: preallocated buffer receiving the normalized name
1287 * @filename: filename to normalize
1288 * Return: 0 on success, -1 on failure
1289 */
25bb9dab
AT
1290static int normalize_longname(char *l_filename, const char *filename)
1291{
7b437807 1292 const char *p, illegal[] = "<>:\"/\\|?*";
0be286cd 1293 size_t len;
25bb9dab 1294
0be286cd
HS
1295 len = strlen(filename);
1296 if (!len || len >= VFAT_MAXLEN_BYTES || filename[len - 1] == '.')
25bb9dab 1297 return -1;
25bb9dab 1298
7b437807
HS
1299 for (p = filename; *p; ++p) {
1300 if ((unsigned char)*p < 0x20)
1301 return -1;
1302 if (strchr(illegal, *p))
1303 return -1;
1304 }
25bb9dab 1305
7b437807
HS
1306 strcpy(l_filename, filename);
1307 downcase(l_filename, VFAT_MAXLEN_BYTES);
25bb9dab
AT
1308
1309 return 0;
1310}
1311
704df6aa
AT
1312int file_fat_write_at(const char *filename, loff_t pos, void *buffer,
1313 loff_t size, loff_t *actwrite)
c30a15e5 1314{
4ced2039 1315 dir_entry *retdent;
4ced2039 1316 fsdata datablock = { .fatbuf = NULL, };
c30a15e5 1317 fsdata *mydata = &datablock;
4ced2039 1318 fat_itr *itr = NULL;
25bb9dab 1319 int ret = -1;
4ced2039 1320 char *filename_copy, *parent, *basename;
c30a15e5
DK
1321 char l_filename[VFAT_MAXLEN_BYTES];
1322
704df6aa
AT
1323 debug("writing %s\n", filename);
1324
4ced2039
AT
1325 filename_copy = strdup(filename);
1326 if (!filename_copy)
1327 return -ENOMEM;
c30a15e5 1328
4ced2039
AT
1329 split_filename(filename_copy, &parent, &basename);
1330 if (!strlen(basename)) {
1331 ret = -EINVAL;
1332 goto exit;
c30a15e5
DK
1333 }
1334
4c4006b6
HS
1335 if (normalize_longname(l_filename, basename)) {
1336 printf("FAT: illegal filename (%s)\n", basename);
4ced2039
AT
1337 ret = -EINVAL;
1338 goto exit;
c30a15e5
DK
1339 }
1340
4ced2039
AT
1341 itr = malloc_cache_aligned(sizeof(fat_itr));
1342 if (!itr) {
1343 ret = -ENOMEM;
1344 goto exit;
c30a15e5
DK
1345 }
1346
4ced2039
AT
1347 ret = fat_itr_root(itr, &datablock);
1348 if (ret)
c30a15e5 1349 goto exit;
c30a15e5 1350
4ced2039
AT
1351 total_sector = datablock.total_sect;
1352
1353 ret = fat_itr_resolve(itr, parent, TYPE_DIR);
1354 if (ret) {
1355 printf("%s: doesn't exist (%d)\n", parent, ret);
25bb9dab
AT
1356 goto exit;
1357 }
c30a15e5 1358
4ced2039
AT
1359 retdent = find_directory_entry(itr, l_filename);
1360
c30a15e5 1361 if (retdent) {
4ced2039
AT
1362 if (fat_itr_isdir(itr)) {
1363 ret = -EISDIR;
1364 goto exit;
1365 }
1366
cb8af8af
AT
1367 /* A file exists */
1368 if (pos == -1)
1369 /* Append to the end */
1370 pos = FAT2CPU32(retdent->size);
1371 if (pos > retdent->size) {
1372 /* No hole allowed */
1373 ret = -EINVAL;
1374 goto exit;
1375 }
1376
704df6aa
AT
1377 /* Update file size in a directory entry */
1378 retdent->size = cpu_to_le32(pos + size);
c30a15e5 1379 } else {
4ced2039 1380 /* Create a new file */
57b745e2 1381 char shortname[SHORT_NAME_SIZE];
3049a510 1382 int ndent;
4ced2039 1383
cb8af8af
AT
1384 if (pos) {
1385 /* No hole allowed */
1386 ret = -EINVAL;
1387 goto exit;
1388 }
1389
28cef9ca 1390 /* Check if long name is needed */
4c4006b6 1391 ndent = set_name(itr, basename, shortname);
3049a510
HS
1392 if (ndent < 0) {
1393 ret = ndent;
1394 goto exit;
1395 }
1396 ret = fat_find_empty_dentries(itr, ndent);
1397 if (ret)
4ced2039 1398 goto exit;
3049a510 1399 if (ndent > 1) {
28cef9ca 1400 /* Set long name entries */
4c4006b6 1401 ret = fill_dir_slot(itr, basename, shortname);
28cef9ca
HS
1402 if (ret)
1403 goto exit;
4ced2039 1404 }
c30a15e5 1405
9c709c7b 1406 /* Set short name entry */
57b745e2 1407 fill_dentry(itr->fsdata, itr->dent, shortname, 0, size,
1ec29aa3 1408 ATTR_ARCH);
c30a15e5 1409
4ced2039 1410 retdent = itr->dent;
e876be4b 1411 }
c30a15e5 1412
704df6aa 1413 ret = set_contents(mydata, retdent, pos, buffer, size, actwrite);
e876be4b
BT
1414 if (ret < 0) {
1415 printf("Error: writing contents\n");
f1149cea 1416 ret = -EIO;
e876be4b
BT
1417 goto exit;
1418 }
1419 debug("attempt to write 0x%llx bytes\n", *actwrite);
c30a15e5 1420
e876be4b 1421 /* Flush fat buffer */
3c0ed9c3 1422 ret = flush_dirty_fat_buffer(mydata);
e876be4b
BT
1423 if (ret) {
1424 printf("Error: flush fat buffer\n");
f1149cea 1425 ret = -EIO;
e876be4b 1426 goto exit;
c30a15e5
DK
1427 }
1428
e876be4b 1429 /* Write directory table to device */
a9f6706c 1430 ret = flush_dir(itr);
e876be4b 1431
c30a15e5 1432exit:
4ced2039 1433 free(filename_copy);
c30a15e5 1434 free(mydata->fatbuf);
4ced2039 1435 free(itr);
1ad0b98a 1436 return ret;
c30a15e5
DK
1437}
1438
1ad0b98a
SR
1439int file_fat_write(const char *filename, void *buffer, loff_t offset,
1440 loff_t maxsize, loff_t *actwrite)
c30a15e5 1441{
704df6aa 1442 return file_fat_write_at(filename, offset, buffer, maxsize, actwrite);
c30a15e5 1443}
31a18d57 1444
f8240ce9
AT
1445static int fat_dir_entries(fat_itr *itr)
1446{
1447 fat_itr *dirs;
1448 fsdata fsdata = { .fatbuf = NULL, }, *mydata = &fsdata;
1449 /* for FATBUFSIZE */
1450 int count;
1451
1452 dirs = malloc_cache_aligned(sizeof(fat_itr));
1453 if (!dirs) {
1454 debug("Error: allocating memory\n");
1455 count = -ENOMEM;
1456 goto exit;
1457 }
1458
1459 /* duplicate fsdata */
1460 fat_itr_child(dirs, itr);
1461 fsdata = *dirs->fsdata;
1462
1463 /* allocate local fat buffer */
1464 fsdata.fatbuf = malloc_cache_aligned(FATBUFSIZE);
1465 if (!fsdata.fatbuf) {
1466 debug("Error: allocating memory\n");
1467 count = -ENOMEM;
1468 goto exit;
1469 }
1470 fsdata.fatbufnum = -1;
1471 dirs->fsdata = &fsdata;
1472
1473 for (count = 0; fat_itr_next(dirs); count++)
1474 ;
1475
1476exit:
1477 free(fsdata.fatbuf);
1478 free(dirs);
1479 return count;
1480}
1481
3d20d212
HS
1482/**
1483 * delete_single_dentry() - delete a single directory entry
1484 *
1485 * @itr: directory iterator
1486 * Return: 0 for success
1487 */
1488static int delete_single_dentry(fat_itr *itr)
1489{
1490 struct dir_entry *dent = itr->dent;
1491
1492 memset(dent, 0, sizeof(*dent));
041f0af3 1493 dent->nameext.name[0] = DELETED_FLAG;
3d20d212 1494
e97eb638
HS
1495 if (!itr->remaining)
1496 return flush_dir(itr);
3d20d212
HS
1497 return 0;
1498}
1499
1500/**
1501 * delete_long_name() - delete long name directory entries
1502 *
1503 * @itr: directory iterator
1504 * Return: 0 for success
1505 */
1506static int delete_long_name(fat_itr *itr)
1507{
041f0af3 1508 int seqn = itr->dent->nameext.name[0] & ~LAST_LONG_ENTRY_MASK;
3d20d212
HS
1509
1510 while (seqn--) {
84ca3055 1511 struct dir_entry *dent;
3d20d212
HS
1512 int ret;
1513
1514 ret = delete_single_dentry(itr);
1515 if (ret)
1516 return ret;
1517 dent = next_dent(itr);
1518 if (!dent)
1519 return -EIO;
1520 }
1521 return 0;
1522}
1523
1524/**
1525 * delete_dentry_long() - remove directory entry
1526 *
1527 * @itr: directory iterator
1528 * Return: 0 for success
1529 */
1530static int delete_dentry_long(fat_itr *itr)
f8240ce9
AT
1531{
1532 fsdata *mydata = itr->fsdata;
3d20d212 1533 dir_entry *dent = itr->dent;
f8240ce9
AT
1534
1535 /* free cluster blocks */
3d20d212 1536 clear_fatent(mydata, START(dent));
f8240ce9
AT
1537 if (flush_dirty_fat_buffer(mydata) < 0) {
1538 printf("Error: flush fat buffer\n");
1539 return -EIO;
1540 }
3d20d212
HS
1541 /* Position to first directory entry for long name */
1542 if (itr->clust != itr->dent_clust) {
1543 int ret;
f8240ce9 1544
3d20d212
HS
1545 ret = fat_move_to_cluster(itr, itr->dent_clust);
1546 if (ret)
1547 return ret;
1548 }
1549 itr->dent = itr->dent_start;
1550 itr->remaining = itr->dent_rem;
1551 dent = itr->dent_start;
1552 /* Delete long name */
1553 if ((dent->attr & ATTR_VFAT) == ATTR_VFAT &&
041f0af3 1554 (dent->nameext.name[0] & LAST_LONG_ENTRY_MASK)) {
3d20d212
HS
1555 int ret;
1556
1557 ret = delete_long_name(itr);
1558 if (ret)
1559 return ret;
1560 }
1561 /* Delete short name */
1562 delete_single_dentry(itr);
e97eb638 1563 return flush_dir(itr);
f8240ce9
AT
1564}
1565
1566int fat_unlink(const char *filename)
1567{
1568 fsdata fsdata = { .fatbuf = NULL, };
1569 fat_itr *itr = NULL;
1570 int n_entries, ret;
1571 char *filename_copy, *dirname, *basename;
1572
1573 filename_copy = strdup(filename);
0d532e91
HS
1574 if (!filename_copy) {
1575 printf("Error: allocating memory\n");
1576 ret = -ENOMEM;
1577 goto exit;
1578 }
f8240ce9
AT
1579 split_filename(filename_copy, &dirname, &basename);
1580
1581 if (!strcmp(dirname, "/") && !strcmp(basename, "")) {
1582 printf("Error: cannot remove root\n");
1583 ret = -EINVAL;
1584 goto exit;
1585 }
1586
1587 itr = malloc_cache_aligned(sizeof(fat_itr));
1588 if (!itr) {
1589 printf("Error: allocating memory\n");
0d532e91
HS
1590 ret = -ENOMEM;
1591 goto exit;
f8240ce9
AT
1592 }
1593
1594 ret = fat_itr_root(itr, &fsdata);
1595 if (ret)
1596 goto exit;
1597
1598 total_sector = fsdata.total_sect;
1599
1600 ret = fat_itr_resolve(itr, dirname, TYPE_DIR);
1601 if (ret) {
1602 printf("%s: doesn't exist (%d)\n", dirname, ret);
1603 ret = -ENOENT;
1604 goto exit;
1605 }
1606
1607 if (!find_directory_entry(itr, basename)) {
1608 printf("%s: doesn't exist\n", basename);
1609 ret = -ENOENT;
1610 goto exit;
1611 }
1612
1613 if (fat_itr_isdir(itr)) {
1614 n_entries = fat_dir_entries(itr);
1615 if (n_entries < 0) {
1616 ret = n_entries;
1617 goto exit;
1618 }
1619 if (n_entries > 2) {
1620 printf("Error: directory is not empty: %d\n",
1621 n_entries);
1622 ret = -EINVAL;
1623 goto exit;
1624 }
1625 }
1626
3d20d212 1627 ret = delete_dentry_long(itr);
f8240ce9
AT
1628
1629exit:
1630 free(fsdata.fatbuf);
1631 free(itr);
1632 free(filename_copy);
1633
1634 return ret;
1635}
1636
4c4006b6 1637int fat_mkdir(const char *dirname)
31a18d57
AT
1638{
1639 dir_entry *retdent;
1640 fsdata datablock = { .fatbuf = NULL, };
1641 fsdata *mydata = &datablock;
1642 fat_itr *itr = NULL;
4c4006b6 1643 char *dirname_copy, *parent, *basename;
31a18d57
AT
1644 char l_dirname[VFAT_MAXLEN_BYTES];
1645 int ret = -1;
1646 loff_t actwrite;
1647 unsigned int bytesperclust;
1648 dir_entry *dotdent = NULL;
1649
4c4006b6 1650 dirname_copy = strdup(dirname);
31a18d57
AT
1651 if (!dirname_copy)
1652 goto exit;
1653
4c4006b6
HS
1654 split_filename(dirname_copy, &parent, &basename);
1655 if (!strlen(basename)) {
31a18d57
AT
1656 ret = -EINVAL;
1657 goto exit;
1658 }
1659
4c4006b6
HS
1660 if (normalize_longname(l_dirname, basename)) {
1661 printf("FAT: illegal filename (%s)\n", basename);
31a18d57
AT
1662 ret = -EINVAL;
1663 goto exit;
1664 }
1665
1666 itr = malloc_cache_aligned(sizeof(fat_itr));
1667 if (!itr) {
1668 ret = -ENOMEM;
1669 goto exit;
1670 }
1671
1672 ret = fat_itr_root(itr, &datablock);
1673 if (ret)
1674 goto exit;
1675
1676 total_sector = datablock.total_sect;
1677
1678 ret = fat_itr_resolve(itr, parent, TYPE_DIR);
1679 if (ret) {
1680 printf("%s: doesn't exist (%d)\n", parent, ret);
1681 goto exit;
1682 }
1683
1684 retdent = find_directory_entry(itr, l_dirname);
1685
1686 if (retdent) {
1687 printf("%s: already exists\n", l_dirname);
1688 ret = -EEXIST;
1689 goto exit;
1690 } else {
57b745e2 1691 char shortname[SHORT_NAME_SIZE];
3049a510 1692 int ndent;
57b745e2 1693
31a18d57
AT
1694 if (itr->is_root) {
1695 /* root dir cannot have "." or ".." */
1696 if (!strcmp(l_dirname, ".") ||
1697 !strcmp(l_dirname, "..")) {
1698 ret = -EINVAL;
1699 goto exit;
1700 }
1701 }
1702
28cef9ca 1703 /* Check if long name is needed */
4c4006b6 1704 ndent = set_name(itr, basename, shortname);
3049a510
HS
1705 if (ndent < 0) {
1706 ret = ndent;
1707 goto exit;
1708 }
1709 ret = fat_find_empty_dentries(itr, ndent);
1710 if (ret)
28cef9ca 1711 goto exit;
3049a510 1712 if (ndent > 1) {
28cef9ca 1713 /* Set long name entries */
4c4006b6 1714 ret = fill_dir_slot(itr, basename, shortname);
28cef9ca
HS
1715 if (ret)
1716 goto exit;
1717 }
31a18d57
AT
1718
1719 /* Set attribute as archive for regular file */
57b745e2 1720 fill_dentry(itr->fsdata, itr->dent, shortname, 0, 0,
31a18d57
AT
1721 ATTR_DIR | ATTR_ARCH);
1722
1723 retdent = itr->dent;
1724 }
1725
1726 /* Default entries */
1727 bytesperclust = mydata->clust_size * mydata->sect_size;
1728 dotdent = malloc_cache_aligned(bytesperclust);
1729 if (!dotdent) {
1730 ret = -ENOMEM;
1731 goto exit;
1732 }
1733 memset(dotdent, 0, bytesperclust);
1734
041f0af3 1735 memcpy(&dotdent[0].nameext, ". ", 11);
31a18d57
AT
1736 dotdent[0].attr = ATTR_DIR | ATTR_ARCH;
1737
041f0af3 1738 memcpy(&dotdent[1].nameext, ".. ", 11);
31a18d57 1739 dotdent[1].attr = ATTR_DIR | ATTR_ARCH;
c5924118
HS
1740
1741 if (itr->is_root)
1742 set_start_cluster(mydata, &dotdent[1], 0);
1743 else
1744 set_start_cluster(mydata, &dotdent[1], itr->start_clust);
31a18d57
AT
1745
1746 ret = set_contents(mydata, retdent, 0, (__u8 *)dotdent,
1747 bytesperclust, &actwrite);
1748 if (ret < 0) {
1749 printf("Error: writing contents\n");
1750 goto exit;
1751 }
1752 /* Write twice for "." */
1753 set_start_cluster(mydata, &dotdent[0], START(retdent));
1754 ret = set_contents(mydata, retdent, 0, (__u8 *)dotdent,
1755 bytesperclust, &actwrite);
1756 if (ret < 0) {
1757 printf("Error: writing contents\n");
1758 goto exit;
1759 }
1760
1761 /* Flush fat buffer */
1762 ret = flush_dirty_fat_buffer(mydata);
1763 if (ret) {
1764 printf("Error: flush fat buffer\n");
e97eb638 1765 ret = -EIO;
31a18d57
AT
1766 goto exit;
1767 }
1768
1769 /* Write directory table to device */
a9f6706c 1770 ret = flush_dir(itr);
31a18d57
AT
1771
1772exit:
1773 free(dirname_copy);
1774 free(mydata->fatbuf);
1775 free(itr);
1776 free(dotdent);
1777 return ret;
1778}