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