fs: fat: support write with sub-directory path
[platform/kernel/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 #include <common.h>
12 #include <blk.h>
13 #include <config.h>
14 #include <exports.h>
15 #include <fat.h>
16 #include <fs.h>
17 #include <asm/byteorder.h>
18 #include <part.h>
19 #include <malloc.h>
20 #include <memalign.h>
21 #include <linux/compiler.h>
22 #include <linux/ctype.h>
23
24 /*
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.
28  */
29 static void downcase(char *str, size_t len)
30 {
31         while (*str != '\0' && len--) {
32                 *str = tolower(*str);
33                 str++;
34         }
35 }
36
37 static struct blk_desc *cur_dev;
38 static disk_partition_t cur_part_info;
39
40 #define DOS_BOOT_MAGIC_OFFSET   0x1fe
41 #define DOS_FS_TYPE_OFFSET      0x36
42 #define DOS_FS32_TYPE_OFFSET    0x52
43
44 static int disk_read(__u32 block, __u32 nr_blocks, void *buf)
45 {
46         ulong ret;
47
48         if (!cur_dev)
49                 return -1;
50
51         ret = blk_dread(cur_dev, cur_part_info.start + block, nr_blocks, buf);
52
53         if (ret != nr_blocks)
54                 return -1;
55
56         return ret;
57 }
58
59 int fat_set_blk_dev(struct blk_desc *dev_desc, disk_partition_t *info)
60 {
61         ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, dev_desc->blksz);
62
63         cur_dev = dev_desc;
64         cur_part_info = *info;
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;
70         }
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;
86 }
87
88 int fat_register_device(struct blk_desc *dev_desc, int part_no)
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 */
96         if (part_get_info(dev_desc, part_no, &info)) {
97                 if (part_no != 0) {
98                         printf("** Partition %d not valid on device %d **\n",
99                                         part_no, dev_desc->devnum);
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;
109 #if CONFIG_IS_ENABLED(PARTITION_UUIDS)
110                 info.uuid[0] = 0;
111 #endif
112         }
113
114         return fat_set_blk_dev(dev_desc, &info);
115 }
116
117 /*
118  * Extract zero terminated short name from a directory entry.
119  */
120 static void get_name(dir_entry *dirent, char *s_name)
121 {
122         char *ptr;
123
124         memcpy(s_name, dirent->name, 8);
125         s_name[8] = '\0';
126         ptr = s_name;
127         while (*ptr && *ptr != ' ')
128                 ptr++;
129         if (dirent->lcase & CASE_LOWER_BASE)
130                 downcase(s_name, (unsigned)(ptr - s_name));
131         if (dirent->ext[0] && dirent->ext[0] != ' ') {
132                 *ptr++ = '.';
133                 memcpy(ptr, dirent->ext, 3);
134                 if (dirent->lcase & CASE_LOWER_EXT)
135                         downcase(ptr, 3);
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)
144                 *s_name = DELETED_FLAG;
145 }
146
147 static int flush_dirty_fat_buffer(fsdata *mydata);
148 #if !defined(CONFIG_FAT_WRITE)
149 /* Stub for read only operation */
150 int flush_dirty_fat_buffer(fsdata *mydata)
151 {
152         (void)(mydata);
153         return 0;
154 }
155 #endif
156
157 /*
158  * Get the entry at index 'entry' in a FAT (12/16/32) table.
159  * On failure 0x00 is returned.
160  */
161 static __u32 get_fatent(fsdata *mydata, __u32 entry)
162 {
163         __u32 bufnum;
164         __u32 offset, off8;
165         __u32 ret = 0x00;
166
167         if (CHECK_CLUST(entry, mydata->fatsize)) {
168                 printf("Error: Invalid FAT entry: 0x%08x\n", entry);
169                 return ret;
170         }
171
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
191         debug("FAT%d: entry: 0x%08x = %d, offset: 0x%04x = %d\n",
192                mydata->fatsize, entry, entry, offset, offset);
193
194         /* Read a new block of FAT entries into the cache. */
195         if (bufnum != mydata->fatbufnum) {
196                 __u32 getsize = FATBUFBLOCKS;
197                 __u8 *bufptr = mydata->fatbuf;
198                 __u32 fatlength = mydata->fatlength;
199                 __u32 startblock = bufnum * FATBUFBLOCKS;
200
201                 /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
202                 if (startblock + getsize > fatlength)
203                         getsize = fatlength - startblock;
204
205                 startblock += mydata->fat_sect; /* Offset from start of disk */
206
207                 /* Write back the fatbuf to the disk */
208                 if (flush_dirty_fat_buffer(mydata) < 0)
209                         return -1;
210
211                 if (disk_read(startblock, getsize, bufptr) < 0) {
212                         debug("Error reading FAT blocks\n");
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:
221                 ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]);
222                 break;
223         case 16:
224                 ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]);
225                 break;
226         case 12:
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);
230
231                 if (offset & 0x1)
232                         ret >>= 4;
233                 ret &= 0xfff;
234         }
235         debug("FAT%d: ret: 0x%08x, entry: 0x%08x, offset: 0x%04x\n",
236                mydata->fatsize, ret, entry, offset);
237
238         return ret;
239 }
240
241 /*
242  * Read at most 'size' bytes from the specified cluster into 'buffer'.
243  * Return 0 on success, -1 otherwise.
244  */
245 static int
246 get_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer, unsigned long size)
247 {
248         __u32 idx = 0;
249         __u32 startsect;
250         int ret;
251
252         if (clustnum > 0) {
253                 startsect = clust_to_sect(mydata, clustnum);
254         } else {
255                 startsect = mydata->rootdir_sect;
256         }
257
258         debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect);
259
260         if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
261                 ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
262
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 {
277                 idx = size / mydata->sect_size;
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);
292                 if (ret != 1) {
293                         debug("Error reading data (got %d)\n", ret);
294                         return -1;
295                 }
296
297                 memcpy(buffer, tmpbuf, size);
298         }
299
300         return 0;
301 }
302
303 /*
304  * Read at most 'maxsize' bytes from 'pos' in the file associated with 'dentptr'
305  * into 'buffer'.
306  * Update the number of bytes read in *gotsize or return -1 on fatal errors.
307  */
308 __u8 get_contents_vfatname_block[MAX_CLUSTSIZE]
309         __aligned(ARCH_DMA_MINALIGN);
310
311 static int get_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos,
312                         __u8 *buffer, loff_t maxsize, loff_t *gotsize)
313 {
314         loff_t filesize = FAT2CPU32(dentptr->size);
315         unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
316         __u32 curclust = START(dentptr);
317         __u32 endclust, newclust;
318         loff_t actsize;
319
320         *gotsize = 0;
321         debug("Filesize: %llu bytes\n", filesize);
322
323         if (pos >= filesize) {
324                 debug("Read position past EOF: %llu\n", pos);
325                 return 0;
326         }
327
328         if (maxsize > 0 && filesize > pos + maxsize)
329                 filesize = pos + maxsize;
330
331         debug("%llu bytes\n", filesize);
332
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");
341                         return 0;
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) {
353                 actsize = min(filesize, (loff_t)bytesperclust);
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);
362                 *gotsize += actsize;
363                 if (!filesize)
364                         return 0;
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");
371                         return 0;
372                 }
373         }
374
375         actsize = bytesperclust;
376         endclust = curclust;
377
378         do {
379                 /* search for consecutive clusters */
380                 while (actsize < filesize) {
381                         newclust = get_fatent(mydata, endclust);
382                         if ((newclust - 1) != endclust)
383                                 goto getit;
384                         if (CHECK_CLUST(newclust, mydata->fatsize)) {
385                                 debug("curclust: 0x%x\n", newclust);
386                                 debug("Invalid FAT entry\n");
387                                 return 0;
388                         }
389                         endclust = newclust;
390                         actsize += bytesperclust;
391                 }
392
393                 /* get remaining bytes */
394                 actsize = filesize;
395                 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
396                         printf("Error reading cluster\n");
397                         return -1;
398                 }
399                 *gotsize += actsize;
400                 return 0;
401 getit:
402                 if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
403                         printf("Error reading cluster\n");
404                         return -1;
405                 }
406                 *gotsize += (int)actsize;
407                 filesize -= actsize;
408                 buffer += actsize;
409
410                 curclust = get_fatent(mydata, endclust);
411                 if (CHECK_CLUST(curclust, mydata->fatsize)) {
412                         debug("curclust: 0x%x\n", curclust);
413                         printf("Invalid FAT entry\n");
414                         return 0;
415                 }
416                 actsize = bytesperclust;
417                 endclust = curclust;
418         } while (1);
419 }
420
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  */
426 static int slot2str(dir_slot *slotptr, char *l_name, int *idx)
427 {
428         int j;
429
430         for (j = 0; j <= 8; j += 2) {
431                 l_name[*idx] = slotptr->name0_4[j];
432                 if (l_name[*idx] == 0x00)
433                         return 1;
434                 (*idx)++;
435         }
436         for (j = 0; j <= 10; j += 2) {
437                 l_name[*idx] = slotptr->name5_10[j];
438                 if (l_name[*idx] == 0x00)
439                         return 1;
440                 (*idx)++;
441         }
442         for (j = 0; j <= 2; j += 2) {
443                 l_name[*idx] = slotptr->name11_12[j];
444                 if (l_name[*idx] == 0x00)
445                         return 1;
446                 (*idx)++;
447         }
448
449         return 0;
450 }
451
452 /* Calculate short name checksum */
453 static __u8 mkcksum(const char name[8], const char ext[3])
454 {
455         int i;
456
457         __u8 ret = 0;
458
459         for (i = 0; i < 8; i++)
460                 ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + name[i];
461         for (i = 0; i < 3; i++)
462                 ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + ext[i];
463
464         return ret;
465 }
466
467 /*
468  * Read boot sector and volume info from a FAT filesystem
469  */
470 static int
471 read_bootsectandvi(boot_sector *bs, volume_info *volinfo, int *fatsize)
472 {
473         __u8 *block;
474         volume_info *vistart;
475         int ret = 0;
476
477         if (cur_dev == NULL) {
478                 debug("Error: no device selected\n");
479                 return -1;
480         }
481
482         block = malloc_cache_aligned(cur_dev->blksz);
483         if (block == NULL) {
484                 debug("Error: allocating block\n");
485                 return -1;
486         }
487
488         if (disk_read(0, 1, block) < 0) {
489                 debug("Error: reading block\n");
490                 goto fail;
491         }
492
493         memcpy(bs, block, sizeof(boot_sector));
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);
499
500         /* FAT32 entries */
501         if (bs->fat_length == 0) {
502                 /* Assume FAT32 */
503                 bs->fat32_length = FAT2CPU32(bs->fat32_length);
504                 bs->flags = FAT2CPU16(bs->flags);
505                 bs->root_cluster = FAT2CPU32(bs->root_cluster);
506                 bs->info_sector = FAT2CPU16(bs->info_sector);
507                 bs->backup_boot = FAT2CPU16(bs->backup_boot);
508                 vistart = (volume_info *)(block + sizeof(boot_sector));
509                 *fatsize = 32;
510         } else {
511                 vistart = (volume_info *)&(bs->fat32_length);
512                 *fatsize = 0;
513         }
514         memcpy(volinfo, vistart, sizeof(volume_info));
515
516         if (*fatsize == 32) {
517                 if (strncmp(FAT32_SIGN, vistart->fs_type, SIGNLEN) == 0)
518                         goto exit;
519         } else {
520                 if (strncmp(FAT12_SIGN, vistart->fs_type, SIGNLEN) == 0) {
521                         *fatsize = 12;
522                         goto exit;
523                 }
524                 if (strncmp(FAT16_SIGN, vistart->fs_type, SIGNLEN) == 0) {
525                         *fatsize = 16;
526                         goto exit;
527                 }
528         }
529
530         debug("Error: broken fs_type sign\n");
531 fail:
532         ret = -1;
533 exit:
534         free(block);
535         return ret;
536 }
537
538 static int get_fs_info(fsdata *mydata)
539 {
540         boot_sector bs;
541         volume_info volinfo;
542         int ret;
543
544         ret = read_bootsectandvi(&bs, &volinfo, &mydata->fatsize);
545         if (ret) {
546                 debug("Error: reading boot sector\n");
547                 return ret;
548         }
549
550         if (mydata->fatsize == 32) {
551                 mydata->fatlength = bs.fat32_length;
552                 mydata->total_sect = bs.total_sect;
553         } else {
554                 mydata->fatlength = bs.fat_length;
555                 mydata->total_sect = (bs.sectors[1] << 8) + bs.sectors[0];
556                 if (!mydata->total_sect)
557                         mydata->total_sect = bs.total_sect;
558         }
559         if (!mydata->total_sect) /* unlikely */
560                 mydata->total_sect = (u32)cur_part_info.size;
561
562         mydata->fats = bs.fats;
563         mydata->fat_sect = bs.reserved;
564
565         mydata->rootdir_sect = mydata->fat_sect + mydata->fatlength * bs.fats;
566
567         mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0];
568         mydata->clust_size = bs.cluster_size;
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         }
574
575         if (mydata->fatsize == 32) {
576                 mydata->data_begin = mydata->rootdir_sect -
577                                         (mydata->clust_size * 2);
578                 mydata->root_cluster = bs.root_cluster;
579         } else {
580                 mydata->rootdir_size = ((bs.dir_entries[1]  * (int)256 +
581                                          bs.dir_entries[0]) *
582                                          sizeof(dir_entry)) /
583                                          mydata->sect_size;
584                 mydata->data_begin = mydata->rootdir_sect +
585                                         mydata->rootdir_size -
586                                         (mydata->clust_size * 2);
587                 mydata->root_cluster =
588                         sect_to_clust(mydata, mydata->rootdir_sect);
589         }
590
591         mydata->fatbufnum = -1;
592         mydata->fat_dirty = 0;
593         mydata->fatbuf = malloc_cache_aligned(FATBUFSIZE);
594         if (mydata->fatbuf == NULL) {
595                 debug("Error: allocating memory\n");
596                 return -1;
597         }
598
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",
603                mydata->root_cluster,
604                mydata->rootdir_sect,
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);
608
609         return 0;
610 }
611
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
632 typedef struct {
633         fsdata    *fsdata;        /* filesystem parameters */
634         unsigned   clust;         /* current cluster */
635         unsigned   next_clust;    /* next cluster if remaining == 0 */
636         int        last_cluster;  /* set once we've read last cluster */
637         int        is_root;       /* is iterator at root directory */
638         int        remaining;     /* remaining dent's in current cluster */
639
640         /* current iterator position values: */
641         dir_entry *dent;          /* current directory entry */
642         char       l_name[VFAT_MAXLEN_BYTES];    /* long (vfat) name */
643         char       s_name[14];    /* short 8.3 name */
644         char      *name;          /* l_name if there is one, else s_name */
645
646         /* storage for current cluster in memory: */
647         u8         block[MAX_CLUSTSIZE] __aligned(ARCH_DMA_MINALIGN);
648 } fat_itr;
649
650 static int fat_itr_isdir(fat_itr *itr);
651
652 /**
653  * fat_itr_root() - initialize an iterator to start at the root
654  * directory
655  *
656  * @itr: iterator to initialize
657  * @fsdata: filesystem data for the partition
658  * @return 0 on success, else -errno
659  */
660 static int fat_itr_root(fat_itr *itr, fsdata *fsdata)
661 {
662         if (get_fs_info(fsdata))
663                 return -ENXIO;
664
665         itr->fsdata = fsdata;
666         itr->clust = fsdata->root_cluster;
667         itr->next_clust = fsdata->root_cluster;
668         itr->dent = NULL;
669         itr->remaining = 0;
670         itr->last_cluster = 0;
671         itr->is_root = 1;
672
673         return 0;
674 }
675
676 /**
677  * fat_itr_child() - initialize an iterator to descend into a sub-
678  * directory
679  *
680  * Initializes 'itr' to iterate the contents of the directory at
681  * the current cursor position of 'parent'.  It is an error to
682  * call this if the current cursor of 'parent' is pointing at a
683  * regular file.
684  *
685  * Note that 'itr' and 'parent' can be the same pointer if you do
686  * not need to preserve 'parent' after this call, which is useful
687  * for traversing directory structure to resolve a file/directory.
688  *
689  * @itr: iterator to initialize
690  * @parent: the iterator pointing at a directory entry in the
691  *    parent directory of the directory to iterate
692  */
693 static void fat_itr_child(fat_itr *itr, fat_itr *parent)
694 {
695         fsdata *mydata = parent->fsdata;  /* for silly macros */
696         unsigned clustnum = START(parent->dent);
697
698         assert(fat_itr_isdir(parent));
699
700         itr->fsdata = parent->fsdata;
701         if (clustnum > 0) {
702                 itr->clust = clustnum;
703                 itr->next_clust = clustnum;
704                 itr->is_root = 0;
705         } else {
706                 itr->clust = parent->fsdata->root_cluster;
707                 itr->next_clust = parent->fsdata->root_cluster;
708                 itr->is_root = 1;
709         }
710         itr->dent = NULL;
711         itr->remaining = 0;
712         itr->last_cluster = 0;
713 }
714
715 static void *next_cluster(fat_itr *itr)
716 {
717         fsdata *mydata = itr->fsdata;  /* for silly macros */
718         int ret;
719         u32 sect;
720
721         /* have we reached the end? */
722         if (itr->last_cluster)
723                 return NULL;
724
725         sect = clust_to_sect(itr->fsdata, itr->next_clust);
726
727         debug("FAT read(sect=%d), clust_size=%d, DIRENTSPERBLOCK=%zd\n",
728               sect, itr->fsdata->clust_size, DIRENTSPERBLOCK);
729
730         /*
731          * NOTE: do_fat_read_at() had complicated logic to deal w/
732          * vfat names that span multiple clusters in the fat16 case,
733          * which get_dentfromdir() probably also needed (and was
734          * missing).  And not entirely sure what fat32 didn't have
735          * the same issue..  We solve that by only caring about one
736          * dent at a time and iteratively constructing the vfat long
737          * name.
738          */
739         ret = disk_read(sect, itr->fsdata->clust_size,
740                         itr->block);
741         if (ret < 0) {
742                 debug("Error: reading block\n");
743                 return NULL;
744         }
745
746         itr->clust = itr->next_clust;
747         if (itr->is_root && itr->fsdata->fatsize != 32) {
748                 itr->next_clust++;
749                 sect = clust_to_sect(itr->fsdata, itr->next_clust);
750                 if (sect - itr->fsdata->rootdir_sect >=
751                     itr->fsdata->rootdir_size) {
752                         debug("nextclust: 0x%x\n", itr->next_clust);
753                         itr->last_cluster = 1;
754                 }
755         } else {
756                 itr->next_clust = get_fatent(itr->fsdata, itr->next_clust);
757                 if (CHECK_CLUST(itr->next_clust, itr->fsdata->fatsize)) {
758                         debug("nextclust: 0x%x\n", itr->next_clust);
759                         itr->last_cluster = 1;
760                 }
761         }
762
763         return itr->block;
764 }
765
766 static dir_entry *next_dent(fat_itr *itr)
767 {
768         if (itr->remaining == 0) {
769                 struct dir_entry *dent = next_cluster(itr);
770                 unsigned nbytes = itr->fsdata->sect_size *
771                         itr->fsdata->clust_size;
772
773                 /* have we reached the last cluster? */
774                 if (!dent) {
775                         /* a sign for no more entries left */
776                         itr->dent = NULL;
777                         return NULL;
778                 }
779
780                 itr->remaining = nbytes / sizeof(dir_entry) - 1;
781                 itr->dent = dent;
782         } else {
783                 itr->remaining--;
784                 itr->dent++;
785         }
786
787         /* have we reached the last valid entry? */
788         if (itr->dent->name[0] == 0)
789                 return NULL;
790
791         return itr->dent;
792 }
793
794 static dir_entry *extract_vfat_name(fat_itr *itr)
795 {
796         struct dir_entry *dent = itr->dent;
797         int seqn = itr->dent->name[0] & ~LAST_LONG_ENTRY_MASK;
798         u8 chksum, alias_checksum = ((dir_slot *)dent)->alias_checksum;
799         int n = 0;
800
801         while (seqn--) {
802                 char buf[13];
803                 int idx = 0;
804
805                 slot2str((dir_slot *)dent, buf, &idx);
806
807                 /* shift accumulated long-name up and copy new part in: */
808                 memmove(itr->l_name + idx, itr->l_name, n);
809                 memcpy(itr->l_name, buf, idx);
810                 n += idx;
811
812                 dent = next_dent(itr);
813                 if (!dent)
814                         return NULL;
815         }
816
817         itr->l_name[n] = '\0';
818
819         chksum = mkcksum(dent->name, dent->ext);
820
821         /* checksum mismatch could mean deleted file, etc.. skip it: */
822         if (chksum != alias_checksum) {
823                 debug("** chksum=%x, alias_checksum=%x, l_name=%s, s_name=%8s.%3s\n",
824                       chksum, alias_checksum, itr->l_name, dent->name, dent->ext);
825                 return NULL;
826         }
827
828         return dent;
829 }
830
831 /**
832  * fat_itr_next() - step to the next entry in a directory
833  *
834  * Must be called once on a new iterator before the cursor is valid.
835  *
836  * @itr: the iterator to iterate
837  * @return boolean, 1 if success or 0 if no more entries in the
838  *    current directory
839  */
840 static int fat_itr_next(fat_itr *itr)
841 {
842         dir_entry *dent;
843
844         itr->name = NULL;
845
846         while (1) {
847                 dent = next_dent(itr);
848                 if (!dent)
849                         return 0;
850
851                 if (dent->name[0] == DELETED_FLAG ||
852                     dent->name[0] == aRING)
853                         continue;
854
855                 if (dent->attr & ATTR_VOLUME) {
856                         if ((dent->attr & ATTR_VFAT) == ATTR_VFAT &&
857                             (dent->name[0] & LAST_LONG_ENTRY_MASK)) {
858                                 dent = extract_vfat_name(itr);
859                                 if (!dent)
860                                         continue;
861                                 itr->name = itr->l_name;
862                                 break;
863                         } else {
864                                 /* Volume label or VFAT entry, skip */
865                                 continue;
866                         }
867                 }
868
869                 break;
870         }
871
872         get_name(dent, itr->s_name);
873         if (!itr->name)
874                 itr->name = itr->s_name;
875
876         return 1;
877 }
878
879 /**
880  * fat_itr_isdir() - is current cursor position pointing to a directory
881  *
882  * @itr: the iterator
883  * @return true if cursor is at a directory
884  */
885 static int fat_itr_isdir(fat_itr *itr)
886 {
887         return !!(itr->dent->attr & ATTR_DIR);
888 }
889
890 /*
891  * Helpers:
892  */
893
894 #define TYPE_FILE 0x1
895 #define TYPE_DIR  0x2
896 #define TYPE_ANY  (TYPE_FILE | TYPE_DIR)
897
898 /**
899  * fat_itr_resolve() - traverse directory structure to resolve the
900  * requested path.
901  *
902  * Traverse directory structure to the requested path.  If the specified
903  * path is to a directory, this will descend into the directory and
904  * leave it iterator at the start of the directory.  If the path is to a
905  * file, it will leave the iterator in the parent directory with current
906  * cursor at file's entry in the directory.
907  *
908  * @itr: iterator initialized to root
909  * @path: the requested path
910  * @type: bitmask of allowable file types
911  * @return 0 on success or -errno
912  */
913 static int fat_itr_resolve(fat_itr *itr, const char *path, unsigned type)
914 {
915         const char *next;
916
917         /* chomp any extra leading slashes: */
918         while (path[0] && ISDIRDELIM(path[0]))
919                 path++;
920
921         /* are we at the end? */
922         if (strlen(path) == 0) {
923                 if (!(type & TYPE_DIR))
924                         return -ENOENT;
925                 return 0;
926         }
927
928         /* find length of next path entry: */
929         next = path;
930         while (next[0] && !ISDIRDELIM(next[0]))
931                 next++;
932
933         if (itr->is_root) {
934                 /* root dir doesn't have "." nor ".." */
935                 if ((((next - path) == 1) && !strncmp(path, ".", 1)) ||
936                     (((next - path) == 2) && !strncmp(path, "..", 2))) {
937                         /* point back to itself */
938                         itr->clust = itr->fsdata->root_cluster;
939                         itr->next_clust = itr->fsdata->root_cluster;
940                         itr->dent = NULL;
941                         itr->remaining = 0;
942                         itr->last_cluster = 0;
943
944                         if (next[0] == 0) {
945                                 if (type & TYPE_DIR)
946                                         return 0;
947                                 else
948                                         return -ENOENT;
949                         }
950
951                         return fat_itr_resolve(itr, next, type);
952                 }
953         }
954
955         while (fat_itr_next(itr)) {
956                 int match = 0;
957                 unsigned n = max(strlen(itr->name), (size_t)(next - path));
958
959                 /* check both long and short name: */
960                 if (!strncasecmp(path, itr->name, n))
961                         match = 1;
962                 else if (itr->name != itr->s_name &&
963                          !strncasecmp(path, itr->s_name, n))
964                         match = 1;
965
966                 if (!match)
967                         continue;
968
969                 if (fat_itr_isdir(itr)) {
970                         /* recurse into directory: */
971                         fat_itr_child(itr, itr);
972                         return fat_itr_resolve(itr, next, type);
973                 } else if (next[0]) {
974                         /*
975                          * If next is not empty then we have a case
976                          * like: /path/to/realfile/nonsense
977                          */
978                         debug("bad trailing path: %s\n", next);
979                         return -ENOENT;
980                 } else if (!(type & TYPE_FILE)) {
981                         return -ENOTDIR;
982                 } else {
983                         return 0;
984                 }
985         }
986
987         return -ENOENT;
988 }
989
990 int file_fat_detectfs(void)
991 {
992         boot_sector bs;
993         volume_info volinfo;
994         int fatsize;
995         char vol_label[12];
996
997         if (cur_dev == NULL) {
998                 printf("No current device\n");
999                 return 1;
1000         }
1001
1002 #if defined(CONFIG_IDE) || \
1003     defined(CONFIG_SATA) || \
1004     defined(CONFIG_SCSI) || \
1005     defined(CONFIG_CMD_USB) || \
1006     defined(CONFIG_MMC)
1007         printf("Interface:  ");
1008         switch (cur_dev->if_type) {
1009         case IF_TYPE_IDE:
1010                 printf("IDE");
1011                 break;
1012         case IF_TYPE_SATA:
1013                 printf("SATA");
1014                 break;
1015         case IF_TYPE_SCSI:
1016                 printf("SCSI");
1017                 break;
1018         case IF_TYPE_ATAPI:
1019                 printf("ATAPI");
1020                 break;
1021         case IF_TYPE_USB:
1022                 printf("USB");
1023                 break;
1024         case IF_TYPE_DOC:
1025                 printf("DOC");
1026                 break;
1027         case IF_TYPE_MMC:
1028                 printf("MMC");
1029                 break;
1030         default:
1031                 printf("Unknown");
1032         }
1033
1034         printf("\n  Device %d: ", cur_dev->devnum);
1035         dev_print(cur_dev);
1036 #endif
1037
1038         if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
1039                 printf("\nNo valid FAT fs found\n");
1040                 return 1;
1041         }
1042
1043         memcpy(vol_label, volinfo.volume_label, 11);
1044         vol_label[11] = '\0';
1045         volinfo.fs_type[5] = '\0';
1046
1047         printf("Filesystem: %s \"%s\"\n", volinfo.fs_type, vol_label);
1048
1049         return 0;
1050 }
1051
1052 int fat_exists(const char *filename)
1053 {
1054         fsdata fsdata;
1055         fat_itr *itr;
1056         int ret;
1057
1058         itr = malloc_cache_aligned(sizeof(fat_itr));
1059         if (!itr)
1060                 return 0;
1061         ret = fat_itr_root(itr, &fsdata);
1062         if (ret)
1063                 goto out;
1064
1065         ret = fat_itr_resolve(itr, filename, TYPE_ANY);
1066         free(fsdata.fatbuf);
1067 out:
1068         free(itr);
1069         return ret == 0;
1070 }
1071
1072 int fat_size(const char *filename, loff_t *size)
1073 {
1074         fsdata fsdata;
1075         fat_itr *itr;
1076         int ret;
1077
1078         itr = malloc_cache_aligned(sizeof(fat_itr));
1079         if (!itr)
1080                 return -ENOMEM;
1081         ret = fat_itr_root(itr, &fsdata);
1082         if (ret)
1083                 goto out_free_itr;
1084
1085         ret = fat_itr_resolve(itr, filename, TYPE_FILE);
1086         if (ret) {
1087                 /*
1088                  * Directories don't have size, but fs_size() is not
1089                  * expected to fail if passed a directory path:
1090                  */
1091                 free(fsdata.fatbuf);
1092                 fat_itr_root(itr, &fsdata);
1093                 if (!fat_itr_resolve(itr, filename, TYPE_DIR)) {
1094                         *size = 0;
1095                         ret = 0;
1096                 }
1097                 goto out_free_both;
1098         }
1099
1100         *size = FAT2CPU32(itr->dent->size);
1101 out_free_both:
1102         free(fsdata.fatbuf);
1103 out_free_itr:
1104         free(itr);
1105         return ret;
1106 }
1107
1108 int file_fat_read_at(const char *filename, loff_t pos, void *buffer,
1109                      loff_t maxsize, loff_t *actread)
1110 {
1111         fsdata fsdata;
1112         fat_itr *itr;
1113         int ret;
1114
1115         itr = malloc_cache_aligned(sizeof(fat_itr));
1116         if (!itr)
1117                 return -ENOMEM;
1118         ret = fat_itr_root(itr, &fsdata);
1119         if (ret)
1120                 goto out_free_itr;
1121
1122         ret = fat_itr_resolve(itr, filename, TYPE_FILE);
1123         if (ret)
1124                 goto out_free_both;
1125
1126         debug("reading %s at pos %llu\n", filename, pos);
1127         ret = get_contents(&fsdata, itr->dent, pos, buffer, maxsize, actread);
1128
1129 out_free_both:
1130         free(fsdata.fatbuf);
1131 out_free_itr:
1132         free(itr);
1133         return ret;
1134 }
1135
1136 int file_fat_read(const char *filename, void *buffer, int maxsize)
1137 {
1138         loff_t actread;
1139         int ret;
1140
1141         ret =  file_fat_read_at(filename, 0, buffer, maxsize, &actread);
1142         if (ret)
1143                 return ret;
1144         else
1145                 return actread;
1146 }
1147
1148 int fat_read_file(const char *filename, void *buf, loff_t offset, loff_t len,
1149                   loff_t *actread)
1150 {
1151         int ret;
1152
1153         ret = file_fat_read_at(filename, offset, buf, len, actread);
1154         if (ret)
1155                 printf("** Unable to read file %s **\n", filename);
1156
1157         return ret;
1158 }
1159
1160 typedef struct {
1161         struct fs_dir_stream parent;
1162         struct fs_dirent dirent;
1163         fsdata fsdata;
1164         fat_itr itr;
1165 } fat_dir;
1166
1167 int fat_opendir(const char *filename, struct fs_dir_stream **dirsp)
1168 {
1169         fat_dir *dir;
1170         int ret;
1171
1172         dir = malloc_cache_aligned(sizeof(*dir));
1173         if (!dir)
1174                 return -ENOMEM;
1175         memset(dir, 0, sizeof(*dir));
1176
1177         ret = fat_itr_root(&dir->itr, &dir->fsdata);
1178         if (ret)
1179                 goto fail_free_dir;
1180
1181         ret = fat_itr_resolve(&dir->itr, filename, TYPE_DIR);
1182         if (ret)
1183                 goto fail_free_both;
1184
1185         *dirsp = (struct fs_dir_stream *)dir;
1186         return 0;
1187
1188 fail_free_both:
1189         free(dir->fsdata.fatbuf);
1190 fail_free_dir:
1191         free(dir);
1192         return ret;
1193 }
1194
1195 int fat_readdir(struct fs_dir_stream *dirs, struct fs_dirent **dentp)
1196 {
1197         fat_dir *dir = (fat_dir *)dirs;
1198         struct fs_dirent *dent = &dir->dirent;
1199
1200         if (!fat_itr_next(&dir->itr))
1201                 return -ENOENT;
1202
1203         memset(dent, 0, sizeof(*dent));
1204         strcpy(dent->name, dir->itr.name);
1205
1206         if (fat_itr_isdir(&dir->itr)) {
1207                 dent->type = FS_DT_DIR;
1208         } else {
1209                 dent->type = FS_DT_REG;
1210                 dent->size = FAT2CPU32(dir->itr.dent->size);
1211         }
1212
1213         *dentp = dent;
1214
1215         return 0;
1216 }
1217
1218 void fat_closedir(struct fs_dir_stream *dirs)
1219 {
1220         fat_dir *dir = (fat_dir *)dirs;
1221         free(dir->fsdata.fatbuf);
1222         free(dir);
1223 }
1224
1225 void fat_close(void)
1226 {
1227 }