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