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