]> git.ipfire.org Git - thirdparty/u-boot.git/blame - fs/fat/fat.c
fs: fat: dynamically allocate memory for temporary buffer
[thirdparty/u-boot.git] / fs / fat / fat.c
CommitLineData
83d290c5 1// SPDX-License-Identifier: GPL-2.0+
71f95118
WD
2/*
3 * fat.c
4 *
5 * R/O (V)FAT 12/16/32 filesystem implementation by Marcus Sundberg
6 *
7 * 2002-07-28 - rjones@nexus-tech.net - ported to ppcboot v1.1.6
8 * 2003-03-10 - kharris@nexus-tech.net - ported to uboot
71f95118
WD
9 */
10
11#include <common.h>
2a981dc2 12#include <blk.h>
71f95118 13#include <config.h>
ac497771 14#include <exports.h>
71f95118 15#include <fat.h>
1f40366b 16#include <fs.h>
71f95118 17#include <asm/byteorder.h>
7205e407 18#include <part.h>
9a800ac7 19#include <malloc.h>
cf92e05c 20#include <memalign.h>
9a800ac7 21#include <linux/compiler.h>
fb7e16cc 22#include <linux/ctype.h>
71f95118 23
71f95118 24/*
21a24c3b
RC
25 * Convert a string to lowercase. Converts at most 'len' characters,
26 * 'len' may be larger than the length of 'str' if 'str' is NULL
27 * terminated.
71f95118 28 */
21a24c3b 29static void downcase(char *str, size_t len)
71f95118 30{
21a24c3b 31 while (*str != '\0' && len--) {
fb7e16cc 32 *str = tolower(*str);
71f95118
WD
33 str++;
34 }
35}
36
4101f687 37static struct blk_desc *cur_dev;
9813b750 38static disk_partition_t cur_part_info;
7385c28e 39
9813b750 40#define DOS_BOOT_MAGIC_OFFSET 0x1fe
7205e407 41#define DOS_FS_TYPE_OFFSET 0x36
66c2d73c 42#define DOS_FS32_TYPE_OFFSET 0x52
71f95118 43
9813b750 44static int disk_read(__u32 block, __u32 nr_blocks, void *buf)
71f95118 45{
0a04ed86
ŁM
46 ulong ret;
47
2a981dc2 48 if (!cur_dev)
7205e407 49 return -1;
7385c28e 50
2a981dc2 51 ret = blk_dread(cur_dev, cur_part_info.start + block, nr_blocks, buf);
0a04ed86 52
42a9f147 53 if (ret != nr_blocks)
0a04ed86
ŁM
54 return -1;
55
56 return ret;
71f95118
WD
57}
58
4101f687 59int fat_set_blk_dev(struct blk_desc *dev_desc, disk_partition_t *info)
71f95118 60{
9a800ac7 61 ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, dev_desc->blksz);
7205e407 62
5e8f9831
SW
63 cur_dev = dev_desc;
64 cur_part_info = *info;
9813b750
KM
65
66 /* Make sure it has a valid FAT header */
67 if (disk_read(0, 1, buffer) != 1) {
68 cur_dev = NULL;
69 return -1;
bf1060ea 70 }
9813b750
KM
71
72 /* Check if it's actually a DOS volume */
73 if (memcmp(buffer + DOS_BOOT_MAGIC_OFFSET, "\x55\xAA", 2)) {
74 cur_dev = NULL;
75 return -1;
76 }
77
78 /* Check for FAT12/FAT16/FAT32 filesystem */
79 if (!memcmp(buffer + DOS_FS_TYPE_OFFSET, "FAT", 3))
80 return 0;
81 if (!memcmp(buffer + DOS_FS32_TYPE_OFFSET, "FAT32", 5))
82 return 0;
83
84 cur_dev = NULL;
85 return -1;
71f95118
WD
86}
87
4101f687 88int fat_register_device(struct blk_desc *dev_desc, int part_no)
5e8f9831
SW
89{
90 disk_partition_t info;
91
92 /* First close any currently found FAT filesystem */
93 cur_dev = NULL;
94
95 /* Read the partition table, if present */
3e8bd469 96 if (part_get_info(dev_desc, part_no, &info)) {
5e8f9831
SW
97 if (part_no != 0) {
98 printf("** Partition %d not valid on device %d **\n",
bcce53d0 99 part_no, dev_desc->devnum);
5e8f9831
SW
100 return -1;
101 }
102
103 info.start = 0;
104 info.size = dev_desc->lba;
105 info.blksz = dev_desc->blksz;
106 info.name[0] = 0;
107 info.type[0] = 0;
108 info.bootable = 0;
b331cd62 109#if CONFIG_IS_ENABLED(PARTITION_UUIDS)
5e8f9831
SW
110 info.uuid[0] = 0;
111#endif
112 }
113
114 return fat_set_blk_dev(dev_desc, &info);
115}
9813b750 116
71f95118
WD
117/*
118 * Extract zero terminated short name from a directory entry.
119 */
9795e07b 120static void get_name(dir_entry *dirent, char *s_name)
71f95118
WD
121{
122 char *ptr;
123
7385c28e 124 memcpy(s_name, dirent->name, 8);
71f95118
WD
125 s_name[8] = '\0';
126 ptr = s_name;
127 while (*ptr && *ptr != ' ')
128 ptr++;
21a24c3b
RC
129 if (dirent->lcase & CASE_LOWER_BASE)
130 downcase(s_name, (unsigned)(ptr - s_name));
71f95118 131 if (dirent->ext[0] && dirent->ext[0] != ' ') {
21a24c3b 132 *ptr++ = '.';
7385c28e 133 memcpy(ptr, dirent->ext, 3);
21a24c3b
RC
134 if (dirent->lcase & CASE_LOWER_EXT)
135 downcase(ptr, 3);
71f95118
WD
136 ptr[3] = '\0';
137 while (*ptr && *ptr != ' ')
138 ptr++;
139 }
140 *ptr = '\0';
141 if (*s_name == DELETED_FLAG)
142 *s_name = '\0';
143 else if (*s_name == aRING)
3c2c2f42 144 *s_name = DELETED_FLAG;
71f95118
WD
145}
146
b8948d2a 147static int flush_dirty_fat_buffer(fsdata *mydata);
d8c3ea99
TFC
148
149#if !CONFIG_IS_ENABLED(FAT_WRITE)
b8948d2a
SB
150/* Stub for read only operation */
151int flush_dirty_fat_buffer(fsdata *mydata)
152{
153 (void)(mydata);
154 return 0;
155}
156#endif
157
71f95118
WD
158/*
159 * Get the entry at index 'entry' in a FAT (12/16/32) table.
160 * On failure 0x00 is returned.
161 */
9795e07b 162static __u32 get_fatent(fsdata *mydata, __u32 entry)
71f95118
WD
163{
164 __u32 bufnum;
b352caea 165 __u32 offset, off8;
71f95118
WD
166 __u32 ret = 0x00;
167
b8948d2a
SB
168 if (CHECK_CLUST(entry, mydata->fatsize)) {
169 printf("Error: Invalid FAT entry: 0x%08x\n", entry);
170 return ret;
171 }
172
71f95118
WD
173 switch (mydata->fatsize) {
174 case 32:
175 bufnum = entry / FAT32BUFSIZE;
176 offset = entry - bufnum * FAT32BUFSIZE;
177 break;
178 case 16:
179 bufnum = entry / FAT16BUFSIZE;
180 offset = entry - bufnum * FAT16BUFSIZE;
181 break;
182 case 12:
183 bufnum = entry / FAT12BUFSIZE;
184 offset = entry - bufnum * FAT12BUFSIZE;
185 break;
186
187 default:
188 /* Unsupported FAT size */
189 return ret;
190 }
191
b8948d2a 192 debug("FAT%d: entry: 0x%08x = %d, offset: 0x%04x = %d\n",
7385c28e 193 mydata->fatsize, entry, entry, offset, offset);
2aa98c66 194
71f95118
WD
195 /* Read a new block of FAT entries into the cache. */
196 if (bufnum != mydata->fatbufnum) {
60b36f0f 197 __u32 getsize = FATBUFBLOCKS;
71f95118
WD
198 __u8 *bufptr = mydata->fatbuf;
199 __u32 fatlength = mydata->fatlength;
200 __u32 startblock = bufnum * FATBUFBLOCKS;
201
6c1a8080 202 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
8006dd2e
BT
203 if (startblock + getsize > fatlength)
204 getsize = fatlength - startblock;
60b36f0f 205
71f95118
WD
206 startblock += mydata->fat_sect; /* Offset from start of disk */
207
b8948d2a
SB
208 /* Write back the fatbuf to the disk */
209 if (flush_dirty_fat_buffer(mydata) < 0)
210 return -1;
211
71f95118 212 if (disk_read(startblock, getsize, bufptr) < 0) {
7385c28e 213 debug("Error reading FAT blocks\n");
71f95118
WD
214 return ret;
215 }
216 mydata->fatbufnum = bufnum;
217 }
218
219 /* Get the actual entry from the table */
220 switch (mydata->fatsize) {
221 case 32:
7385c28e 222 ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]);
71f95118
WD
223 break;
224 case 16:
7385c28e 225 ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]);
71f95118 226 break;
7385c28e 227 case 12:
b352caea
SB
228 off8 = (offset * 3) / 2;
229 /* fatbut + off8 may be unaligned, read in byte granularity */
230 ret = mydata->fatbuf[off8] + (mydata->fatbuf[off8 + 1] << 8);
8d48c92b
SB
231
232 if (offset & 0x1)
233 ret >>= 4;
234 ret &= 0xfff;
71f95118 235 }
b8948d2a
SB
236 debug("FAT%d: ret: 0x%08x, entry: 0x%08x, offset: 0x%04x\n",
237 mydata->fatsize, ret, entry, offset);
71f95118
WD
238
239 return ret;
240}
241
71f95118
WD
242/*
243 * Read at most 'size' bytes from the specified cluster into 'buffer'.
244 * Return 0 on success, -1 otherwise.
245 */
246static int
9795e07b 247get_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer, unsigned long size)
71f95118 248{
3f270f42 249 __u32 idx = 0;
71f95118 250 __u32 startsect;
46236b14 251 int ret;
71f95118
WD
252
253 if (clustnum > 0) {
265edc03 254 startsect = clust_to_sect(mydata, clustnum);
71f95118
WD
255 } else {
256 startsect = mydata->rootdir_sect;
257 }
258
7385c28e
WD
259 debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect);
260
cc63b25e 261 if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
9a800ac7 262 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
7385c28e 263
1c381ceb 264 debug("FAT: Misaligned buffer address (%p)\n", buffer);
cc63b25e
BT
265
266 while (size >= mydata->sect_size) {
267 ret = disk_read(startsect++, 1, tmpbuf);
268 if (ret != 1) {
269 debug("Error reading data (got %d)\n", ret);
270 return -1;
271 }
272
273 memcpy(buffer, tmpbuf, mydata->sect_size);
274 buffer += mydata->sect_size;
275 size -= mydata->sect_size;
276 }
277 } else {
ac497771 278 idx = size / mydata->sect_size;
cc63b25e
BT
279 ret = disk_read(startsect, idx, buffer);
280 if (ret != idx) {
281 debug("Error reading data (got %d)\n", ret);
282 return -1;
283 }
284 startsect += idx;
285 idx *= mydata->sect_size;
286 buffer += idx;
287 size -= idx;
288 }
289 if (size) {
290 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
291
292 ret = disk_read(startsect, 1, tmpbuf);
46236b14
KM
293 if (ret != 1) {
294 debug("Error reading data (got %d)\n", ret);
7205e407 295 return -1;
71f95118 296 }
7205e407 297
cc63b25e 298 memcpy(buffer, tmpbuf, size);
71f95118
WD
299 }
300
301 return 0;
302}
303
71f95118 304/*
1170e634 305 * Read at most 'maxsize' bytes from 'pos' in the file associated with 'dentptr'
71f95118 306 * into 'buffer'.
1ad0b98a 307 * Update the number of bytes read in *gotsize or return -1 on fatal errors.
71f95118 308 */
1ad0b98a
SR
309static int get_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos,
310 __u8 *buffer, loff_t maxsize, loff_t *gotsize)
71f95118 311{
1ad0b98a 312 loff_t filesize = FAT2CPU32(dentptr->size);
ac497771 313 unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
71f95118 314 __u32 curclust = START(dentptr);
7205e407 315 __u32 endclust, newclust;
1ad0b98a 316 loff_t actsize;
71f95118 317
1ad0b98a
SR
318 *gotsize = 0;
319 debug("Filesize: %llu bytes\n", filesize);
71f95118 320
1170e634 321 if (pos >= filesize) {
1ad0b98a
SR
322 debug("Read position past EOF: %llu\n", pos);
323 return 0;
1170e634
BT
324 }
325
326 if (maxsize > 0 && filesize > pos + maxsize)
327 filesize = pos + maxsize;
71f95118 328
1ad0b98a 329 debug("%llu bytes\n", filesize);
7385c28e 330
1170e634
BT
331 actsize = bytesperclust;
332
333 /* go to cluster at pos */
334 while (actsize <= pos) {
335 curclust = get_fatent(mydata, curclust);
336 if (CHECK_CLUST(curclust, mydata->fatsize)) {
337 debug("curclust: 0x%x\n", curclust);
338 debug("Invalid FAT entry\n");
1ad0b98a 339 return 0;
1170e634
BT
340 }
341 actsize += bytesperclust;
342 }
343
344 /* actsize > pos */
345 actsize -= bytesperclust;
346 filesize -= actsize;
347 pos -= actsize;
348
349 /* align to beginning of next cluster if any */
350 if (pos) {
8537874a
TFC
351 __u8 *tmp_buffer;
352
1ad0b98a 353 actsize = min(filesize, (loff_t)bytesperclust);
8537874a
TFC
354 tmp_buffer = malloc_cache_aligned(actsize);
355 if (!tmp_buffer) {
356 debug("Error: allocating buffer\n");
357 return -ENOMEM;
358 }
359
360 if (get_cluster(mydata, curclust, tmp_buffer, actsize) != 0) {
1170e634 361 printf("Error reading cluster\n");
8537874a 362 free(tmp_buffer);
1170e634
BT
363 return -1;
364 }
365 filesize -= actsize;
366 actsize -= pos;
8537874a
TFC
367 memcpy(buffer, tmp_buffer + pos, actsize);
368 free(tmp_buffer);
1ad0b98a 369 *gotsize += actsize;
1170e634 370 if (!filesize)
1ad0b98a 371 return 0;
1170e634
BT
372 buffer += actsize;
373
374 curclust = get_fatent(mydata, curclust);
375 if (CHECK_CLUST(curclust, mydata->fatsize)) {
376 debug("curclust: 0x%x\n", curclust);
377 debug("Invalid FAT entry\n");
1ad0b98a 378 return 0;
1170e634
BT
379 }
380 }
381
7385c28e
WD
382 actsize = bytesperclust;
383 endclust = curclust;
71f95118
WD
384
385 do {
7205e407 386 /* search for consecutive clusters */
7385c28e 387 while (actsize < filesize) {
7205e407 388 newclust = get_fatent(mydata, endclust);
7385c28e 389 if ((newclust - 1) != endclust)
7205e407 390 goto getit;
8ce4e5c2 391 if (CHECK_CLUST(newclust, mydata->fatsize)) {
7385c28e
WD
392 debug("curclust: 0x%x\n", newclust);
393 debug("Invalid FAT entry\n");
1ad0b98a 394 return 0;
7205e407 395 }
7385c28e
WD
396 endclust = newclust;
397 actsize += bytesperclust;
7205e407 398 }
7385c28e 399
7205e407 400 /* get remaining bytes */
7385c28e 401 actsize = filesize;
0880e5bb 402 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
7385c28e 403 printf("Error reading cluster\n");
7205e407
WD
404 return -1;
405 }
1ad0b98a
SR
406 *gotsize += actsize;
407 return 0;
7205e407
WD
408getit:
409 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
7385c28e 410 printf("Error reading cluster\n");
7205e407
WD
411 return -1;
412 }
1ad0b98a 413 *gotsize += (int)actsize;
7205e407
WD
414 filesize -= actsize;
415 buffer += actsize;
7385c28e 416
7205e407 417 curclust = get_fatent(mydata, endclust);
8ce4e5c2 418 if (CHECK_CLUST(curclust, mydata->fatsize)) {
7385c28e
WD
419 debug("curclust: 0x%x\n", curclust);
420 printf("Invalid FAT entry\n");
1ad0b98a 421 return 0;
71f95118 422 }
7385c28e
WD
423 actsize = bytesperclust;
424 endclust = curclust;
71f95118
WD
425 } while (1);
426}
427
71f95118
WD
428/*
429 * Extract the file name information from 'slotptr' into 'l_name',
430 * starting at l_name[*idx].
431 * Return 1 if terminator (zero byte) is found, 0 otherwise.
432 */
9795e07b 433static int slot2str(dir_slot *slotptr, char *l_name, int *idx)
71f95118
WD
434{
435 int j;
436
437 for (j = 0; j <= 8; j += 2) {
438 l_name[*idx] = slotptr->name0_4[j];
7385c28e
WD
439 if (l_name[*idx] == 0x00)
440 return 1;
71f95118
WD
441 (*idx)++;
442 }
443 for (j = 0; j <= 10; j += 2) {
444 l_name[*idx] = slotptr->name5_10[j];
7385c28e
WD
445 if (l_name[*idx] == 0x00)
446 return 1;
71f95118
WD
447 (*idx)++;
448 }
449 for (j = 0; j <= 2; j += 2) {
450 l_name[*idx] = slotptr->name11_12[j];
7385c28e
WD
451 if (l_name[*idx] == 0x00)
452 return 1;
71f95118
WD
453 (*idx)++;
454 }
455
456 return 0;
457}
458
71f95118 459/* Calculate short name checksum */
ff04f6d1 460static __u8 mkcksum(const char name[8], const char ext[3])
71f95118
WD
461{
462 int i;
7385c28e 463
71f95118
WD
464 __u8 ret = 0;
465
6ad77d88 466 for (i = 0; i < 8; i++)
ff04f6d1 467 ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + name[i];
6ad77d88 468 for (i = 0; i < 3; i++)
ff04f6d1 469 ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + ext[i];
71f95118
WD
470
471 return ret;
472}
71f95118 473
71f95118
WD
474/*
475 * Read boot sector and volume info from a FAT filesystem
476 */
477static int
9795e07b 478read_bootsectandvi(boot_sector *bs, volume_info *volinfo, int *fatsize)
71f95118 479{
ac497771 480 __u8 *block;
71f95118 481 volume_info *vistart;
ac497771
SS
482 int ret = 0;
483
484 if (cur_dev == NULL) {
485 debug("Error: no device selected\n");
486 return -1;
487 }
488
09fa964b 489 block = malloc_cache_aligned(cur_dev->blksz);
ac497771
SS
490 if (block == NULL) {
491 debug("Error: allocating block\n");
492 return -1;
493 }
71f95118 494
9795e07b 495 if (disk_read(0, 1, block) < 0) {
7385c28e 496 debug("Error: reading block\n");
ac497771 497 goto fail;
71f95118
WD
498 }
499
500 memcpy(bs, block, sizeof(boot_sector));
7385c28e
WD
501 bs->reserved = FAT2CPU16(bs->reserved);
502 bs->fat_length = FAT2CPU16(bs->fat_length);
503 bs->secs_track = FAT2CPU16(bs->secs_track);
504 bs->heads = FAT2CPU16(bs->heads);
505 bs->total_sect = FAT2CPU32(bs->total_sect);
71f95118
WD
506
507 /* FAT32 entries */
508 if (bs->fat_length == 0) {
509 /* Assume FAT32 */
510 bs->fat32_length = FAT2CPU32(bs->fat32_length);
7385c28e 511 bs->flags = FAT2CPU16(bs->flags);
71f95118 512 bs->root_cluster = FAT2CPU32(bs->root_cluster);
7385c28e
WD
513 bs->info_sector = FAT2CPU16(bs->info_sector);
514 bs->backup_boot = FAT2CPU16(bs->backup_boot);
515 vistart = (volume_info *)(block + sizeof(boot_sector));
71f95118
WD
516 *fatsize = 32;
517 } else {
7385c28e 518 vistart = (volume_info *)&(bs->fat32_length);
71f95118
WD
519 *fatsize = 0;
520 }
521 memcpy(volinfo, vistart, sizeof(volume_info));
522
71f95118 523 if (*fatsize == 32) {
7385c28e 524 if (strncmp(FAT32_SIGN, vistart->fs_type, SIGNLEN) == 0)
ac497771 525 goto exit;
71f95118 526 } else {
651351fe 527 if (strncmp(FAT12_SIGN, vistart->fs_type, SIGNLEN) == 0) {
71f95118 528 *fatsize = 12;
ac497771 529 goto exit;
71f95118 530 }
651351fe 531 if (strncmp(FAT16_SIGN, vistart->fs_type, SIGNLEN) == 0) {
71f95118 532 *fatsize = 16;
ac497771 533 goto exit;
71f95118
WD
534 }
535 }
536
7385c28e 537 debug("Error: broken fs_type sign\n");
ac497771
SS
538fail:
539 ret = -1;
540exit:
541 free(block);
542 return ret;
71f95118
WD
543}
544
45449980 545static int get_fs_info(fsdata *mydata)
71f95118 546{
7385c28e
WD
547 boot_sector bs;
548 volume_info volinfo;
45449980 549 int ret;
7385c28e 550
45449980
RC
551 ret = read_bootsectandvi(&bs, &volinfo, &mydata->fatsize);
552 if (ret) {
7385c28e 553 debug("Error: reading boot sector\n");
45449980 554 return ret;
7385c28e
WD
555 }
556
40e21916 557 if (mydata->fatsize == 32) {
7385c28e 558 mydata->fatlength = bs.fat32_length;
f23101f9 559 mydata->total_sect = bs.total_sect;
40e21916 560 } else {
7385c28e 561 mydata->fatlength = bs.fat_length;
f23101f9
AT
562 mydata->total_sect = (bs.sectors[1] << 8) + bs.sectors[0];
563 if (!mydata->total_sect)
564 mydata->total_sect = bs.total_sect;
40e21916 565 }
f23101f9
AT
566 if (!mydata->total_sect) /* unlikely */
567 mydata->total_sect = (u32)cur_part_info.size;
7385c28e 568
f23101f9 569 mydata->fats = bs.fats;
7385c28e
WD
570 mydata->fat_sect = bs.reserved;
571
45449980 572 mydata->rootdir_sect = mydata->fat_sect + mydata->fatlength * bs.fats;
7385c28e 573
ac497771 574 mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0];
7385c28e 575 mydata->clust_size = bs.cluster_size;
46236b14
KM
576 if (mydata->sect_size != cur_part_info.blksz) {
577 printf("Error: FAT sector size mismatch (fs=%hu, dev=%lu)\n",
578 mydata->sect_size, cur_part_info.blksz);
579 return -1;
580 }
cd80a4fe
PW
581 if (mydata->clust_size == 0) {
582 printf("Error: FAT cluster size not set\n");
583 return -1;
584 }
585 if ((unsigned int)mydata->clust_size * mydata->sect_size >
586 MAX_CLUSTSIZE) {
587 printf("Error: FAT cluster size too big (cs=%u, max=%u)\n",
588 (unsigned int)mydata->clust_size * mydata->sect_size,
589 MAX_CLUSTSIZE);
590 return -1;
591 }
7385c28e
WD
592
593 if (mydata->fatsize == 32) {
594 mydata->data_begin = mydata->rootdir_sect -
595 (mydata->clust_size * 2);
c6e3baa5 596 mydata->root_cluster = bs.root_cluster;
7385c28e 597 } else {
45449980
RC
598 mydata->rootdir_size = ((bs.dir_entries[1] * (int)256 +
599 bs.dir_entries[0]) *
600 sizeof(dir_entry)) /
601 mydata->sect_size;
7385c28e 602 mydata->data_begin = mydata->rootdir_sect +
45449980 603 mydata->rootdir_size -
7385c28e 604 (mydata->clust_size * 2);
265edc03
RC
605 mydata->root_cluster =
606 sect_to_clust(mydata, mydata->rootdir_sect);
7385c28e
WD
607 }
608
609 mydata->fatbufnum = -1;
3c0ed9c3 610 mydata->fat_dirty = 0;
09fa964b 611 mydata->fatbuf = malloc_cache_aligned(FATBUFSIZE);
ac497771
SS
612 if (mydata->fatbuf == NULL) {
613 debug("Error: allocating memory\n");
614 return -1;
615 }
71f95118 616
7385c28e
WD
617 debug("FAT%d, fat_sect: %d, fatlength: %d\n",
618 mydata->fatsize, mydata->fat_sect, mydata->fatlength);
619 debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n"
620 "Data begins at: %d\n",
c6e3baa5 621 mydata->root_cluster,
7385c28e 622 mydata->rootdir_sect,
ac497771
SS
623 mydata->rootdir_sect * mydata->sect_size, mydata->data_begin);
624 debug("Sector size: %d, cluster size: %d\n", mydata->sect_size,
625 mydata->clust_size);
7385c28e 626
45449980
RC
627 return 0;
628}
629
c6e3baa5
RC
630
631/*
632 * Directory iterator, to simplify filesystem traversal
633 *
634 * Implements an iterator pattern to traverse directory tables,
635 * transparently handling directory tables split across multiple
636 * clusters, and the difference between FAT12/FAT16 root directory
637 * (contiguous) and subdirectories + FAT32 root (chained).
638 *
639 * Rough usage:
640 *
641 * for (fat_itr_root(&itr, fsdata); fat_itr_next(&itr); ) {
642 * // to traverse down to a subdirectory pointed to by
643 * // current iterator position:
644 * fat_itr_child(&itr, &itr);
645 * }
646 *
647 * For more complete example, see fat_itr_resolve()
648 */
649
650typedef struct {
651 fsdata *fsdata; /* filesystem parameters */
3a10e072 652 unsigned start_clust; /* first cluster */
c6e3baa5 653 unsigned clust; /* current cluster */
f528c140 654 unsigned next_clust; /* next cluster if remaining == 0 */
c6e3baa5
RC
655 int last_cluster; /* set once we've read last cluster */
656 int is_root; /* is iterator at root directory */
657 int remaining; /* remaining dent's in current cluster */
658
659 /* current iterator position values: */
660 dir_entry *dent; /* current directory entry */
661 char l_name[VFAT_MAXLEN_BYTES]; /* long (vfat) name */
662 char s_name[14]; /* short 8.3 name */
663 char *name; /* l_name if there is one, else s_name */
664
665 /* storage for current cluster in memory: */
666 u8 block[MAX_CLUSTSIZE] __aligned(ARCH_DMA_MINALIGN);
667} fat_itr;
668
669static int fat_itr_isdir(fat_itr *itr);
670
671/**
672 * fat_itr_root() - initialize an iterator to start at the root
673 * directory
674 *
675 * @itr: iterator to initialize
676 * @fsdata: filesystem data for the partition
677 * @return 0 on success, else -errno
678 */
679static int fat_itr_root(fat_itr *itr, fsdata *fsdata)
680{
681 if (get_fs_info(fsdata))
682 return -ENXIO;
683
684 itr->fsdata = fsdata;
3a10e072 685 itr->start_clust = 0;
c6e3baa5 686 itr->clust = fsdata->root_cluster;
f528c140 687 itr->next_clust = fsdata->root_cluster;
c6e3baa5
RC
688 itr->dent = NULL;
689 itr->remaining = 0;
690 itr->last_cluster = 0;
691 itr->is_root = 1;
692
693 return 0;
694}
695
696/**
697 * fat_itr_child() - initialize an iterator to descend into a sub-
698 * directory
699 *
700 * Initializes 'itr' to iterate the contents of the directory at
701 * the current cursor position of 'parent'. It is an error to
702 * call this if the current cursor of 'parent' is pointing at a
703 * regular file.
704 *
705 * Note that 'itr' and 'parent' can be the same pointer if you do
706 * not need to preserve 'parent' after this call, which is useful
707 * for traversing directory structure to resolve a file/directory.
708 *
709 * @itr: iterator to initialize
710 * @parent: the iterator pointing at a directory entry in the
711 * parent directory of the directory to iterate
712 */
713static void fat_itr_child(fat_itr *itr, fat_itr *parent)
714{
715 fsdata *mydata = parent->fsdata; /* for silly macros */
716 unsigned clustnum = START(parent->dent);
717
718 assert(fat_itr_isdir(parent));
719
720 itr->fsdata = parent->fsdata;
3a10e072 721 itr->start_clust = clustnum;
c6e3baa5
RC
722 if (clustnum > 0) {
723 itr->clust = clustnum;
f528c140 724 itr->next_clust = clustnum;
8df87314 725 itr->is_root = 0;
c6e3baa5
RC
726 } else {
727 itr->clust = parent->fsdata->root_cluster;
f528c140 728 itr->next_clust = parent->fsdata->root_cluster;
8df87314 729 itr->is_root = 1;
c6e3baa5
RC
730 }
731 itr->dent = NULL;
732 itr->remaining = 0;
733 itr->last_cluster = 0;
c6e3baa5
RC
734}
735
736static void *next_cluster(fat_itr *itr)
737{
738 fsdata *mydata = itr->fsdata; /* for silly macros */
739 int ret;
740 u32 sect;
741
742 /* have we reached the end? */
743 if (itr->last_cluster)
744 return NULL;
745
d3035b85 746 sect = clust_to_sect(itr->fsdata, itr->next_clust);
c6e3baa5
RC
747
748 debug("FAT read(sect=%d), clust_size=%d, DIRENTSPERBLOCK=%zd\n",
749 sect, itr->fsdata->clust_size, DIRENTSPERBLOCK);
750
751 /*
752 * NOTE: do_fat_read_at() had complicated logic to deal w/
753 * vfat names that span multiple clusters in the fat16 case,
754 * which get_dentfromdir() probably also needed (and was
755 * missing). And not entirely sure what fat32 didn't have
756 * the same issue.. We solve that by only caring about one
757 * dent at a time and iteratively constructing the vfat long
758 * name.
759 */
760 ret = disk_read(sect, itr->fsdata->clust_size,
761 itr->block);
762 if (ret < 0) {
763 debug("Error: reading block\n");
764 return NULL;
765 }
766
f528c140 767 itr->clust = itr->next_clust;
c6e3baa5 768 if (itr->is_root && itr->fsdata->fatsize != 32) {
f528c140
AT
769 itr->next_clust++;
770 sect = clust_to_sect(itr->fsdata, itr->next_clust);
c6e3baa5
RC
771 if (sect - itr->fsdata->rootdir_sect >=
772 itr->fsdata->rootdir_size) {
f528c140 773 debug("nextclust: 0x%x\n", itr->next_clust);
c6e3baa5
RC
774 itr->last_cluster = 1;
775 }
776 } else {
f528c140
AT
777 itr->next_clust = get_fatent(itr->fsdata, itr->next_clust);
778 if (CHECK_CLUST(itr->next_clust, itr->fsdata->fatsize)) {
779 debug("nextclust: 0x%x\n", itr->next_clust);
c6e3baa5
RC
780 itr->last_cluster = 1;
781 }
782 }
783
784 return itr->block;
785}
786
787static dir_entry *next_dent(fat_itr *itr)
788{
789 if (itr->remaining == 0) {
790 struct dir_entry *dent = next_cluster(itr);
791 unsigned nbytes = itr->fsdata->sect_size *
792 itr->fsdata->clust_size;
793
794 /* have we reached the last cluster? */
f528c140
AT
795 if (!dent) {
796 /* a sign for no more entries left */
797 itr->dent = NULL;
c6e3baa5 798 return NULL;
f528c140 799 }
c6e3baa5
RC
800
801 itr->remaining = nbytes / sizeof(dir_entry) - 1;
802 itr->dent = dent;
803 } else {
804 itr->remaining--;
805 itr->dent++;
806 }
807
808 /* have we reached the last valid entry? */
809 if (itr->dent->name[0] == 0)
810 return NULL;
811
812 return itr->dent;
813}
814
815static dir_entry *extract_vfat_name(fat_itr *itr)
816{
817 struct dir_entry *dent = itr->dent;
818 int seqn = itr->dent->name[0] & ~LAST_LONG_ENTRY_MASK;
819 u8 chksum, alias_checksum = ((dir_slot *)dent)->alias_checksum;
820 int n = 0;
821
822 while (seqn--) {
823 char buf[13];
824 int idx = 0;
825
826 slot2str((dir_slot *)dent, buf, &idx);
827
8b021bb9
PW
828 if (n + idx >= sizeof(itr->l_name))
829 return NULL;
830
c6e3baa5
RC
831 /* shift accumulated long-name up and copy new part in: */
832 memmove(itr->l_name + idx, itr->l_name, n);
833 memcpy(itr->l_name, buf, idx);
834 n += idx;
835
836 dent = next_dent(itr);
837 if (!dent)
838 return NULL;
839 }
840
841 itr->l_name[n] = '\0';
842
843 chksum = mkcksum(dent->name, dent->ext);
844
845 /* checksum mismatch could mean deleted file, etc.. skip it: */
846 if (chksum != alias_checksum) {
847 debug("** chksum=%x, alias_checksum=%x, l_name=%s, s_name=%8s.%3s\n",
848 chksum, alias_checksum, itr->l_name, dent->name, dent->ext);
849 return NULL;
850 }
851
852 return dent;
853}
854
855/**
856 * fat_itr_next() - step to the next entry in a directory
857 *
858 * Must be called once on a new iterator before the cursor is valid.
859 *
860 * @itr: the iterator to iterate
861 * @return boolean, 1 if success or 0 if no more entries in the
862 * current directory
863 */
864static int fat_itr_next(fat_itr *itr)
865{
866 dir_entry *dent;
867
868 itr->name = NULL;
869
870 while (1) {
871 dent = next_dent(itr);
872 if (!dent)
873 return 0;
874
875 if (dent->name[0] == DELETED_FLAG ||
876 dent->name[0] == aRING)
877 continue;
878
879 if (dent->attr & ATTR_VOLUME) {
8bad6cb1 880 if ((dent->attr & ATTR_VFAT) == ATTR_VFAT &&
c6e3baa5
RC
881 (dent->name[0] & LAST_LONG_ENTRY_MASK)) {
882 dent = extract_vfat_name(itr);
883 if (!dent)
884 continue;
885 itr->name = itr->l_name;
886 break;
887 } else {
888 /* Volume label or VFAT entry, skip */
889 continue;
890 }
891 }
892
893 break;
894 }
895
896 get_name(dent, itr->s_name);
897 if (!itr->name)
898 itr->name = itr->s_name;
899
900 return 1;
901}
902
903/**
904 * fat_itr_isdir() - is current cursor position pointing to a directory
905 *
906 * @itr: the iterator
907 * @return true if cursor is at a directory
908 */
909static int fat_itr_isdir(fat_itr *itr)
910{
911 return !!(itr->dent->attr & ATTR_DIR);
912}
913
914/*
915 * Helpers:
916 */
917
918#define TYPE_FILE 0x1
919#define TYPE_DIR 0x2
920#define TYPE_ANY (TYPE_FILE | TYPE_DIR)
921
922/**
923 * fat_itr_resolve() - traverse directory structure to resolve the
924 * requested path.
925 *
926 * Traverse directory structure to the requested path. If the specified
927 * path is to a directory, this will descend into the directory and
928 * leave it iterator at the start of the directory. If the path is to a
929 * file, it will leave the iterator in the parent directory with current
930 * cursor at file's entry in the directory.
931 *
932 * @itr: iterator initialized to root
933 * @path: the requested path
934 * @type: bitmask of allowable file types
935 * @return 0 on success or -errno
936 */
937static int fat_itr_resolve(fat_itr *itr, const char *path, unsigned type)
938{
939 const char *next;
940
941 /* chomp any extra leading slashes: */
942 while (path[0] && ISDIRDELIM(path[0]))
943 path++;
944
945 /* are we at the end? */
946 if (strlen(path) == 0) {
947 if (!(type & TYPE_DIR))
948 return -ENOENT;
949 return 0;
950 }
951
952 /* find length of next path entry: */
953 next = path;
954 while (next[0] && !ISDIRDELIM(next[0]))
955 next++;
956
b94b6be5
AT
957 if (itr->is_root) {
958 /* root dir doesn't have "." nor ".." */
959 if ((((next - path) == 1) && !strncmp(path, ".", 1)) ||
960 (((next - path) == 2) && !strncmp(path, "..", 2))) {
961 /* point back to itself */
962 itr->clust = itr->fsdata->root_cluster;
f528c140 963 itr->next_clust = itr->fsdata->root_cluster;
b94b6be5
AT
964 itr->dent = NULL;
965 itr->remaining = 0;
966 itr->last_cluster = 0;
967
968 if (next[0] == 0) {
969 if (type & TYPE_DIR)
970 return 0;
971 else
972 return -ENOENT;
973 }
974
975 return fat_itr_resolve(itr, next, type);
976 }
977 }
978
c6e3baa5
RC
979 while (fat_itr_next(itr)) {
980 int match = 0;
981 unsigned n = max(strlen(itr->name), (size_t)(next - path));
982
983 /* check both long and short name: */
984 if (!strncasecmp(path, itr->name, n))
985 match = 1;
986 else if (itr->name != itr->s_name &&
987 !strncasecmp(path, itr->s_name, n))
988 match = 1;
989
990 if (!match)
991 continue;
992
993 if (fat_itr_isdir(itr)) {
994 /* recurse into directory: */
995 fat_itr_child(itr, itr);
996 return fat_itr_resolve(itr, next, type);
997 } else if (next[0]) {
998 /*
999 * If next is not empty then we have a case
1000 * like: /path/to/realfile/nonsense
1001 */
1002 debug("bad trailing path: %s\n", next);
1003 return -ENOENT;
1004 } else if (!(type & TYPE_FILE)) {
1005 return -ENOTDIR;
1006 } else {
1007 return 0;
1008 }
1009 }
1010
1011 return -ENOENT;
1012}
1013
9795e07b 1014int file_fat_detectfs(void)
71f95118 1015{
7385c28e
WD
1016 boot_sector bs;
1017 volume_info volinfo;
1018 int fatsize;
1019 char vol_label[12];
71f95118 1020
7385c28e 1021 if (cur_dev == NULL) {
7205e407
WD
1022 printf("No current device\n");
1023 return 1;
1024 }
7385c28e 1025
fc843a02 1026#if defined(CONFIG_IDE) || \
10e40d54 1027 defined(CONFIG_SATA) || \
c649e3c9 1028 defined(CONFIG_SCSI) || \
dd60d122 1029 defined(CONFIG_CMD_USB) || \
21f6f963 1030 defined(CONFIG_MMC)
7205e407 1031 printf("Interface: ");
7385c28e
WD
1032 switch (cur_dev->if_type) {
1033 case IF_TYPE_IDE:
1034 printf("IDE");
1035 break;
1036 case IF_TYPE_SATA:
1037 printf("SATA");
1038 break;
1039 case IF_TYPE_SCSI:
1040 printf("SCSI");
1041 break;
1042 case IF_TYPE_ATAPI:
1043 printf("ATAPI");
1044 break;
1045 case IF_TYPE_USB:
1046 printf("USB");
1047 break;
1048 case IF_TYPE_DOC:
1049 printf("DOC");
1050 break;
1051 case IF_TYPE_MMC:
1052 printf("MMC");
1053 break;
1054 default:
1055 printf("Unknown");
7205e407 1056 }
7385c28e 1057
bcce53d0 1058 printf("\n Device %d: ", cur_dev->devnum);
7205e407
WD
1059 dev_print(cur_dev);
1060#endif
7385c28e
WD
1061
1062 if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
7205e407
WD
1063 printf("\nNo valid FAT fs found\n");
1064 return 1;
1065 }
7385c28e
WD
1066
1067 memcpy(vol_label, volinfo.volume_label, 11);
7205e407 1068 vol_label[11] = '\0';
7385c28e
WD
1069 volinfo.fs_type[5] = '\0';
1070
461f86e6 1071 printf("Filesystem: %s \"%s\"\n", volinfo.fs_type, vol_label);
7385c28e 1072
7205e407 1073 return 0;
71f95118
WD
1074}
1075
b7b5f319
SW
1076int fat_exists(const char *filename)
1077{
8eafae20 1078 fsdata fsdata;
2460098c 1079 fat_itr *itr;
1ad0b98a 1080 int ret;
1ad0b98a 1081
09fa964b 1082 itr = malloc_cache_aligned(sizeof(fat_itr));
af609e37
TT
1083 if (!itr)
1084 return 0;
8eafae20
RC
1085 ret = fat_itr_root(itr, &fsdata);
1086 if (ret)
af609e37 1087 goto out;
8eafae20
RC
1088
1089 ret = fat_itr_resolve(itr, filename, TYPE_ANY);
725ffdb5 1090 free(fsdata.fatbuf);
af609e37 1091out:
2460098c 1092 free(itr);
1ad0b98a 1093 return ret == 0;
b7b5f319
SW
1094}
1095
d455d878 1096int fat_size(const char *filename, loff_t *size)
cf659819 1097{
8eafae20 1098 fsdata fsdata;
2460098c 1099 fat_itr *itr;
8eafae20
RC
1100 int ret;
1101
09fa964b 1102 itr = malloc_cache_aligned(sizeof(fat_itr));
af609e37
TT
1103 if (!itr)
1104 return -ENOMEM;
8eafae20
RC
1105 ret = fat_itr_root(itr, &fsdata);
1106 if (ret)
af609e37 1107 goto out_free_itr;
8eafae20
RC
1108
1109 ret = fat_itr_resolve(itr, filename, TYPE_FILE);
1110 if (ret) {
1111 /*
1112 * Directories don't have size, but fs_size() is not
1113 * expected to fail if passed a directory path:
1114 */
725ffdb5 1115 free(fsdata.fatbuf);
8eafae20
RC
1116 fat_itr_root(itr, &fsdata);
1117 if (!fat_itr_resolve(itr, filename, TYPE_DIR)) {
1118 *size = 0;
725ffdb5 1119 ret = 0;
8eafae20 1120 }
af609e37 1121 goto out_free_both;
8eafae20
RC
1122 }
1123
1124 *size = FAT2CPU32(itr->dent->size);
af609e37 1125out_free_both:
725ffdb5 1126 free(fsdata.fatbuf);
af609e37 1127out_free_itr:
2460098c 1128 free(itr);
725ffdb5 1129 return ret;
cf659819
SW
1130}
1131
1ad0b98a
SR
1132int file_fat_read_at(const char *filename, loff_t pos, void *buffer,
1133 loff_t maxsize, loff_t *actread)
71f95118 1134{
8eafae20 1135 fsdata fsdata;
2460098c 1136 fat_itr *itr;
8eafae20
RC
1137 int ret;
1138
09fa964b 1139 itr = malloc_cache_aligned(sizeof(fat_itr));
af609e37
TT
1140 if (!itr)
1141 return -ENOMEM;
8eafae20
RC
1142 ret = fat_itr_root(itr, &fsdata);
1143 if (ret)
af609e37 1144 goto out_free_itr;
8eafae20
RC
1145
1146 ret = fat_itr_resolve(itr, filename, TYPE_FILE);
1147 if (ret)
af609e37 1148 goto out_free_both;
8eafae20 1149
287c04e1 1150 debug("reading %s at pos %llu\n", filename, pos);
725ffdb5
RC
1151 ret = get_contents(&fsdata, itr->dent, pos, buffer, maxsize, actread);
1152
af609e37 1153out_free_both:
725ffdb5 1154 free(fsdata.fatbuf);
af609e37 1155out_free_itr:
2460098c 1156 free(itr);
725ffdb5 1157 return ret;
1170e634
BT
1158}
1159
1ad0b98a 1160int file_fat_read(const char *filename, void *buffer, int maxsize)
1170e634 1161{
1ad0b98a
SR
1162 loff_t actread;
1163 int ret;
1164
1165 ret = file_fat_read_at(filename, 0, buffer, maxsize, &actread);
1166 if (ret)
1167 return ret;
1168 else
1169 return actread;
71f95118 1170}
e6d52415 1171
d455d878
SR
1172int fat_read_file(const char *filename, void *buf, loff_t offset, loff_t len,
1173 loff_t *actread)
e6d52415 1174{
1ad0b98a 1175 int ret;
e6d52415 1176
d455d878
SR
1177 ret = file_fat_read_at(filename, offset, buf, len, actread);
1178 if (ret)
e6d52415 1179 printf("** Unable to read file %s **\n", filename);
e6d52415 1180
d455d878 1181 return ret;
e6d52415
SG
1182}
1183
1f40366b
RC
1184typedef struct {
1185 struct fs_dir_stream parent;
1186 struct fs_dirent dirent;
1187 fsdata fsdata;
1188 fat_itr itr;
1189} fat_dir;
1190
1191int fat_opendir(const char *filename, struct fs_dir_stream **dirsp)
1192{
34dd853c 1193 fat_dir *dir;
1f40366b
RC
1194 int ret;
1195
34dd853c 1196 dir = malloc_cache_aligned(sizeof(*dir));
1f40366b
RC
1197 if (!dir)
1198 return -ENOMEM;
34dd853c 1199 memset(dir, 0, sizeof(*dir));
1f40366b
RC
1200
1201 ret = fat_itr_root(&dir->itr, &dir->fsdata);
1202 if (ret)
af609e37 1203 goto fail_free_dir;
1f40366b
RC
1204
1205 ret = fat_itr_resolve(&dir->itr, filename, TYPE_DIR);
1206 if (ret)
af609e37 1207 goto fail_free_both;
1f40366b
RC
1208
1209 *dirsp = (struct fs_dir_stream *)dir;
1210 return 0;
1211
af609e37 1212fail_free_both:
725ffdb5 1213 free(dir->fsdata.fatbuf);
af609e37 1214fail_free_dir:
1f40366b
RC
1215 free(dir);
1216 return ret;
1217}
1218
1219int fat_readdir(struct fs_dir_stream *dirs, struct fs_dirent **dentp)
1220{
1221 fat_dir *dir = (fat_dir *)dirs;
1222 struct fs_dirent *dent = &dir->dirent;
1223
1224 if (!fat_itr_next(&dir->itr))
1225 return -ENOENT;
1226
1227 memset(dent, 0, sizeof(*dent));
1228 strcpy(dent->name, dir->itr.name);
1229
1230 if (fat_itr_isdir(&dir->itr)) {
1231 dent->type = FS_DT_DIR;
1232 } else {
1233 dent->type = FS_DT_REG;
1234 dent->size = FAT2CPU32(dir->itr.dent->size);
1235 }
1236
1237 *dentp = dent;
1238
1239 return 0;
1240}
1241
1242void fat_closedir(struct fs_dir_stream *dirs)
1243{
1244 fat_dir *dir = (fat_dir *)dirs;
725ffdb5 1245 free(dir->fsdata.fatbuf);
1f40366b
RC
1246 free(dir);
1247}
1248
e6d52415
SG
1249void fat_close(void)
1250{
1251}