xref: /openbmc/u-boot/fs/fat/fat.c (revision bf48fcb6)
1 /*
2  * fat.c
3  *
4  * R/O (V)FAT 12/16/32 filesystem implementation by Marcus Sundberg
5  *
6  * 2002-07-28 - rjones@nexus-tech.net - ported to ppcboot v1.1.6
7  * 2003-03-10 - kharris@nexus-tech.net - ported to uboot
8  *
9  * See file CREDITS for list of people who contributed to this
10  * project.
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License as
14  * published by the Free Software Foundation; either version 2 of
15  * the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
25  * MA 02111-1307 USA
26  */
27 
28 #include <common.h>
29 #include <config.h>
30 #include <exports.h>
31 #include <fat.h>
32 #include <asm/byteorder.h>
33 #include <part.h>
34 #include <malloc.h>
35 #include <linux/compiler.h>
36 
37 /*
38  * Convert a string to lowercase.
39  */
40 static void downcase(char *str)
41 {
42 	while (*str != '\0') {
43 		TOLOWER(*str);
44 		str++;
45 	}
46 }
47 
48 static block_dev_desc_t *cur_dev;
49 static disk_partition_t cur_part_info;
50 
51 #define DOS_BOOT_MAGIC_OFFSET	0x1fe
52 #define DOS_FS_TYPE_OFFSET	0x36
53 #define DOS_FS32_TYPE_OFFSET	0x52
54 
55 static int disk_read(__u32 block, __u32 nr_blocks, void *buf)
56 {
57 	if (!cur_dev || !cur_dev->block_read)
58 		return -1;
59 
60 	return cur_dev->block_read(cur_dev->dev,
61 			cur_part_info.start + block, nr_blocks, buf);
62 }
63 
64 int fat_set_blk_dev(block_dev_desc_t *dev_desc, disk_partition_t *info)
65 {
66 	ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, dev_desc->blksz);
67 
68 	cur_dev = dev_desc;
69 	cur_part_info = *info;
70 
71 	/* Make sure it has a valid FAT header */
72 	if (disk_read(0, 1, buffer) != 1) {
73 		cur_dev = NULL;
74 		return -1;
75 	}
76 
77 	/* Check if it's actually a DOS volume */
78 	if (memcmp(buffer + DOS_BOOT_MAGIC_OFFSET, "\x55\xAA", 2)) {
79 		cur_dev = NULL;
80 		return -1;
81 	}
82 
83 	/* Check for FAT12/FAT16/FAT32 filesystem */
84 	if (!memcmp(buffer + DOS_FS_TYPE_OFFSET, "FAT", 3))
85 		return 0;
86 	if (!memcmp(buffer + DOS_FS32_TYPE_OFFSET, "FAT32", 5))
87 		return 0;
88 
89 	cur_dev = NULL;
90 	return -1;
91 }
92 
93 int fat_register_device(block_dev_desc_t *dev_desc, int part_no)
94 {
95 	disk_partition_t info;
96 
97 	/* First close any currently found FAT filesystem */
98 	cur_dev = NULL;
99 
100 	/* Read the partition table, if present */
101 	if (get_partition_info(dev_desc, part_no, &info)) {
102 		if (part_no != 0) {
103 			printf("** Partition %d not valid on device %d **\n",
104 					part_no, dev_desc->dev);
105 			return -1;
106 		}
107 
108 		info.start = 0;
109 		info.size = dev_desc->lba;
110 		info.blksz = dev_desc->blksz;
111 		info.name[0] = 0;
112 		info.type[0] = 0;
113 		info.bootable = 0;
114 #ifdef CONFIG_PARTITION_UUIDS
115 		info.uuid[0] = 0;
116 #endif
117 	}
118 
119 	return fat_set_blk_dev(dev_desc, &info);
120 }
121 
122 /*
123  * Get the first occurence of a directory delimiter ('/' or '\') in a string.
124  * Return index into string if found, -1 otherwise.
125  */
126 static int dirdelim(char *str)
127 {
128 	char *start = str;
129 
130 	while (*str != '\0') {
131 		if (ISDIRDELIM(*str))
132 			return str - start;
133 		str++;
134 	}
135 	return -1;
136 }
137 
138 /*
139  * Extract zero terminated short name from a directory entry.
140  */
141 static void get_name(dir_entry *dirent, char *s_name)
142 {
143 	char *ptr;
144 
145 	memcpy(s_name, dirent->name, 8);
146 	s_name[8] = '\0';
147 	ptr = s_name;
148 	while (*ptr && *ptr != ' ')
149 		ptr++;
150 	if (dirent->ext[0] && dirent->ext[0] != ' ') {
151 		*ptr = '.';
152 		ptr++;
153 		memcpy(ptr, dirent->ext, 3);
154 		ptr[3] = '\0';
155 		while (*ptr && *ptr != ' ')
156 			ptr++;
157 	}
158 	*ptr = '\0';
159 	if (*s_name == DELETED_FLAG)
160 		*s_name = '\0';
161 	else if (*s_name == aRING)
162 		*s_name = DELETED_FLAG;
163 	downcase(s_name);
164 }
165 
166 /*
167  * Get the entry at index 'entry' in a FAT (12/16/32) table.
168  * On failure 0x00 is returned.
169  */
170 static __u32 get_fatent(fsdata *mydata, __u32 entry)
171 {
172 	__u32 bufnum;
173 	__u32 off16, offset;
174 	__u32 ret = 0x00;
175 	__u16 val1, val2;
176 
177 	switch (mydata->fatsize) {
178 	case 32:
179 		bufnum = entry / FAT32BUFSIZE;
180 		offset = entry - bufnum * FAT32BUFSIZE;
181 		break;
182 	case 16:
183 		bufnum = entry / FAT16BUFSIZE;
184 		offset = entry - bufnum * FAT16BUFSIZE;
185 		break;
186 	case 12:
187 		bufnum = entry / FAT12BUFSIZE;
188 		offset = entry - bufnum * FAT12BUFSIZE;
189 		break;
190 
191 	default:
192 		/* Unsupported FAT size */
193 		return ret;
194 	}
195 
196 	debug("FAT%d: entry: 0x%04x = %d, offset: 0x%04x = %d\n",
197 	       mydata->fatsize, entry, entry, offset, offset);
198 
199 	/* Read a new block of FAT entries into the cache. */
200 	if (bufnum != mydata->fatbufnum) {
201 		__u32 getsize = FATBUFBLOCKS;
202 		__u8 *bufptr = mydata->fatbuf;
203 		__u32 fatlength = mydata->fatlength;
204 		__u32 startblock = bufnum * FATBUFBLOCKS;
205 
206 		if (startblock + getsize > fatlength)
207 			getsize = fatlength - startblock;
208 
209 		startblock += mydata->fat_sect;	/* Offset from start of disk */
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 		off16 = (offset * 3) / 4;
228 
229 		switch (offset & 0x3) {
230 		case 0:
231 			ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[off16]);
232 			ret &= 0xfff;
233 			break;
234 		case 1:
235 			val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
236 			val1 &= 0xf000;
237 			val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]);
238 			val2 &= 0x00ff;
239 			ret = (val2 << 4) | (val1 >> 12);
240 			break;
241 		case 2:
242 			val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
243 			val1 &= 0xff00;
244 			val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]);
245 			val2 &= 0x000f;
246 			ret = (val2 << 8) | (val1 >> 8);
247 			break;
248 		case 3:
249 			ret = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
250 			ret = (ret & 0xfff0) >> 4;
251 			break;
252 		default:
253 			break;
254 		}
255 		break;
256 	}
257 	debug("FAT%d: ret: %08x, offset: %04x\n",
258 	       mydata->fatsize, ret, offset);
259 
260 	return ret;
261 }
262 
263 /*
264  * Read at most 'size' bytes from the specified cluster into 'buffer'.
265  * Return 0 on success, -1 otherwise.
266  */
267 static int
268 get_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer, unsigned long size)
269 {
270 	__u32 idx = 0;
271 	__u32 startsect;
272 	int ret;
273 
274 	if (clustnum > 0) {
275 		startsect = mydata->data_begin +
276 				clustnum * mydata->clust_size;
277 	} else {
278 		startsect = mydata->rootdir_sect;
279 	}
280 
281 	debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect);
282 
283 	if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
284 		ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
285 
286 		printf("FAT: Misaligned buffer address (%p)\n", buffer);
287 
288 		while (size >= mydata->sect_size) {
289 			ret = disk_read(startsect++, 1, tmpbuf);
290 			if (ret != 1) {
291 				debug("Error reading data (got %d)\n", ret);
292 				return -1;
293 			}
294 
295 			memcpy(buffer, tmpbuf, mydata->sect_size);
296 			buffer += mydata->sect_size;
297 			size -= mydata->sect_size;
298 		}
299 	} else {
300 		idx = size / mydata->sect_size;
301 		ret = disk_read(startsect, idx, buffer);
302 		if (ret != idx) {
303 			debug("Error reading data (got %d)\n", ret);
304 			return -1;
305 		}
306 		startsect += idx;
307 		idx *= mydata->sect_size;
308 		buffer += idx;
309 		size -= idx;
310 	}
311 	if (size) {
312 		ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
313 
314 		ret = disk_read(startsect, 1, tmpbuf);
315 		if (ret != 1) {
316 			debug("Error reading data (got %d)\n", ret);
317 			return -1;
318 		}
319 
320 		memcpy(buffer, tmpbuf, size);
321 	}
322 
323 	return 0;
324 }
325 
326 /*
327  * Read at most 'maxsize' bytes from 'pos' in the file associated with 'dentptr'
328  * into 'buffer'.
329  * Return the number of bytes read or -1 on fatal errors.
330  */
331 __u8 get_contents_vfatname_block[MAX_CLUSTSIZE]
332 	__aligned(ARCH_DMA_MINALIGN);
333 
334 static long
335 get_contents(fsdata *mydata, dir_entry *dentptr, unsigned long pos,
336 	     __u8 *buffer, unsigned long maxsize)
337 {
338 	unsigned long filesize = FAT2CPU32(dentptr->size), gotsize = 0;
339 	unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
340 	__u32 curclust = START(dentptr);
341 	__u32 endclust, newclust;
342 	unsigned long actsize;
343 
344 	debug("Filesize: %ld bytes\n", filesize);
345 
346 	if (pos >= filesize) {
347 		debug("Read position past EOF: %lu\n", pos);
348 		return gotsize;
349 	}
350 
351 	if (maxsize > 0 && filesize > pos + maxsize)
352 		filesize = pos + maxsize;
353 
354 	debug("%ld bytes\n", filesize);
355 
356 	actsize = bytesperclust;
357 
358 	/* go to cluster at pos */
359 	while (actsize <= pos) {
360 		curclust = get_fatent(mydata, curclust);
361 		if (CHECK_CLUST(curclust, mydata->fatsize)) {
362 			debug("curclust: 0x%x\n", curclust);
363 			debug("Invalid FAT entry\n");
364 			return gotsize;
365 		}
366 		actsize += bytesperclust;
367 	}
368 
369 	/* actsize > pos */
370 	actsize -= bytesperclust;
371 	filesize -= actsize;
372 	pos -= actsize;
373 
374 	/* align to beginning of next cluster if any */
375 	if (pos) {
376 		actsize = min(filesize, bytesperclust);
377 		if (get_cluster(mydata, curclust, get_contents_vfatname_block,
378 				(int)actsize) != 0) {
379 			printf("Error reading cluster\n");
380 			return -1;
381 		}
382 		filesize -= actsize;
383 		actsize -= pos;
384 		memcpy(buffer, get_contents_vfatname_block + pos, actsize);
385 		gotsize += actsize;
386 		if (!filesize)
387 			return gotsize;
388 		buffer += actsize;
389 
390 		curclust = get_fatent(mydata, curclust);
391 		if (CHECK_CLUST(curclust, mydata->fatsize)) {
392 			debug("curclust: 0x%x\n", curclust);
393 			debug("Invalid FAT entry\n");
394 			return gotsize;
395 		}
396 	}
397 
398 	actsize = bytesperclust;
399 	endclust = curclust;
400 
401 	do {
402 		/* search for consecutive clusters */
403 		while (actsize < filesize) {
404 			newclust = get_fatent(mydata, endclust);
405 			if ((newclust - 1) != endclust)
406 				goto getit;
407 			if (CHECK_CLUST(newclust, mydata->fatsize)) {
408 				debug("curclust: 0x%x\n", newclust);
409 				debug("Invalid FAT entry\n");
410 				return gotsize;
411 			}
412 			endclust = newclust;
413 			actsize += bytesperclust;
414 		}
415 
416 		/* get remaining bytes */
417 		actsize = filesize;
418 		if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
419 			printf("Error reading cluster\n");
420 			return -1;
421 		}
422 		gotsize += actsize;
423 		return gotsize;
424 getit:
425 		if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
426 			printf("Error reading cluster\n");
427 			return -1;
428 		}
429 		gotsize += (int)actsize;
430 		filesize -= actsize;
431 		buffer += actsize;
432 
433 		curclust = get_fatent(mydata, endclust);
434 		if (CHECK_CLUST(curclust, mydata->fatsize)) {
435 			debug("curclust: 0x%x\n", curclust);
436 			printf("Invalid FAT entry\n");
437 			return gotsize;
438 		}
439 		actsize = bytesperclust;
440 		endclust = curclust;
441 	} while (1);
442 }
443 
444 #ifdef CONFIG_SUPPORT_VFAT
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 /*
477  * Extract the full long filename starting at 'retdent' (which is really
478  * a slot) into 'l_name'. If successful also copy the real directory entry
479  * into 'retdent'
480  * Return 0 on success, -1 otherwise.
481  */
482 static int
483 get_vfatname(fsdata *mydata, int curclust, __u8 *cluster,
484 	     dir_entry *retdent, char *l_name)
485 {
486 	dir_entry *realdent;
487 	dir_slot *slotptr = (dir_slot *)retdent;
488 	__u8 *buflimit = cluster + mydata->sect_size * ((curclust == 0) ?
489 							PREFETCH_BLOCKS :
490 							mydata->clust_size);
491 	__u8 counter = (slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff;
492 	int idx = 0;
493 
494 	if (counter > VFAT_MAXSEQ) {
495 		debug("Error: VFAT name is too long\n");
496 		return -1;
497 	}
498 
499 	while ((__u8 *)slotptr < buflimit) {
500 		if (counter == 0)
501 			break;
502 		if (((slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff) != counter)
503 			return -1;
504 		slotptr++;
505 		counter--;
506 	}
507 
508 	if ((__u8 *)slotptr >= buflimit) {
509 		dir_slot *slotptr2;
510 
511 		if (curclust == 0)
512 			return -1;
513 		curclust = get_fatent(mydata, curclust);
514 		if (CHECK_CLUST(curclust, mydata->fatsize)) {
515 			debug("curclust: 0x%x\n", curclust);
516 			printf("Invalid FAT entry\n");
517 			return -1;
518 		}
519 
520 		if (get_cluster(mydata, curclust, get_contents_vfatname_block,
521 				mydata->clust_size * mydata->sect_size) != 0) {
522 			debug("Error: reading directory block\n");
523 			return -1;
524 		}
525 
526 		slotptr2 = (dir_slot *)get_contents_vfatname_block;
527 		while (counter > 0) {
528 			if (((slotptr2->id & ~LAST_LONG_ENTRY_MASK)
529 			    & 0xff) != counter)
530 				return -1;
531 			slotptr2++;
532 			counter--;
533 		}
534 
535 		/* Save the real directory entry */
536 		realdent = (dir_entry *)slotptr2;
537 		while ((__u8 *)slotptr2 > get_contents_vfatname_block) {
538 			slotptr2--;
539 			slot2str(slotptr2, l_name, &idx);
540 		}
541 	} else {
542 		/* Save the real directory entry */
543 		realdent = (dir_entry *)slotptr;
544 	}
545 
546 	do {
547 		slotptr--;
548 		if (slot2str(slotptr, l_name, &idx))
549 			break;
550 	} while (!(slotptr->id & LAST_LONG_ENTRY_MASK));
551 
552 	l_name[idx] = '\0';
553 	if (*l_name == DELETED_FLAG)
554 		*l_name = '\0';
555 	else if (*l_name == aRING)
556 		*l_name = DELETED_FLAG;
557 	downcase(l_name);
558 
559 	/* Return the real directory entry */
560 	memcpy(retdent, realdent, sizeof(dir_entry));
561 
562 	return 0;
563 }
564 
565 /* Calculate short name checksum */
566 static __u8 mkcksum(const char name[8], const char ext[3])
567 {
568 	int i;
569 
570 	__u8 ret = 0;
571 
572 	for (i = 0; i < sizeof(name); i++)
573 		ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + name[i];
574 	for (i = 0; i < sizeof(ext); i++)
575 		ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + ext[i];
576 
577 	return ret;
578 }
579 #endif	/* CONFIG_SUPPORT_VFAT */
580 
581 /*
582  * Get the directory entry associated with 'filename' from the directory
583  * starting at 'startsect'
584  */
585 __u8 get_dentfromdir_block[MAX_CLUSTSIZE]
586 	__aligned(ARCH_DMA_MINALIGN);
587 
588 static dir_entry *get_dentfromdir(fsdata *mydata, int startsect,
589 				  char *filename, dir_entry *retdent,
590 				  int dols)
591 {
592 	__u16 prevcksum = 0xffff;
593 	__u32 curclust = START(retdent);
594 	int files = 0, dirs = 0;
595 
596 	debug("get_dentfromdir: %s\n", filename);
597 
598 	while (1) {
599 		dir_entry *dentptr;
600 
601 		int i;
602 
603 		if (get_cluster(mydata, curclust, get_dentfromdir_block,
604 				mydata->clust_size * mydata->sect_size) != 0) {
605 			debug("Error: reading directory block\n");
606 			return NULL;
607 		}
608 
609 		dentptr = (dir_entry *)get_dentfromdir_block;
610 
611 		for (i = 0; i < DIRENTSPERCLUST; i++) {
612 			char s_name[14], l_name[VFAT_MAXLEN_BYTES];
613 
614 			l_name[0] = '\0';
615 			if (dentptr->name[0] == DELETED_FLAG) {
616 				dentptr++;
617 				continue;
618 			}
619 			if ((dentptr->attr & ATTR_VOLUME)) {
620 #ifdef CONFIG_SUPPORT_VFAT
621 				if ((dentptr->attr & ATTR_VFAT) == ATTR_VFAT &&
622 				    (dentptr->name[0] & LAST_LONG_ENTRY_MASK)) {
623 					prevcksum = ((dir_slot *)dentptr)->alias_checksum;
624 					get_vfatname(mydata, curclust,
625 						     get_dentfromdir_block,
626 						     dentptr, l_name);
627 					if (dols) {
628 						int isdir;
629 						char dirc;
630 						int doit = 0;
631 
632 						isdir = (dentptr->attr & ATTR_DIR);
633 
634 						if (isdir) {
635 							dirs++;
636 							dirc = '/';
637 							doit = 1;
638 						} else {
639 							dirc = ' ';
640 							if (l_name[0] != 0) {
641 								files++;
642 								doit = 1;
643 							}
644 						}
645 						if (doit) {
646 							if (dirc == ' ') {
647 								printf(" %8ld   %s%c\n",
648 									(long)FAT2CPU32(dentptr->size),
649 									l_name,
650 									dirc);
651 							} else {
652 								printf("            %s%c\n",
653 									l_name,
654 									dirc);
655 							}
656 						}
657 						dentptr++;
658 						continue;
659 					}
660 					debug("vfatname: |%s|\n", l_name);
661 				} else
662 #endif
663 				{
664 					/* Volume label or VFAT entry */
665 					dentptr++;
666 					continue;
667 				}
668 			}
669 			if (dentptr->name[0] == 0) {
670 				if (dols) {
671 					printf("\n%d file(s), %d dir(s)\n\n",
672 						files, dirs);
673 				}
674 				debug("Dentname == NULL - %d\n", i);
675 				return NULL;
676 			}
677 #ifdef CONFIG_SUPPORT_VFAT
678 			__u8 csum = mkcksum(dentptr->name, dentptr->ext);
679 			if (dols && csum == prevcksum) {
680 				prevcksum = 0xffff;
681 				dentptr++;
682 				continue;
683 			}
684 #endif
685 			get_name(dentptr, s_name);
686 			if (dols) {
687 				int isdir = (dentptr->attr & ATTR_DIR);
688 				char dirc;
689 				int doit = 0;
690 
691 				if (isdir) {
692 					dirs++;
693 					dirc = '/';
694 					doit = 1;
695 				} else {
696 					dirc = ' ';
697 					if (s_name[0] != 0) {
698 						files++;
699 						doit = 1;
700 					}
701 				}
702 
703 				if (doit) {
704 					if (dirc == ' ') {
705 						printf(" %8ld   %s%c\n",
706 							(long)FAT2CPU32(dentptr->size),
707 							s_name, dirc);
708 					} else {
709 						printf("            %s%c\n",
710 							s_name, dirc);
711 					}
712 				}
713 
714 				dentptr++;
715 				continue;
716 			}
717 
718 			if (strcmp(filename, s_name)
719 			    && strcmp(filename, l_name)) {
720 				debug("Mismatch: |%s|%s|\n", s_name, l_name);
721 				dentptr++;
722 				continue;
723 			}
724 
725 			memcpy(retdent, dentptr, sizeof(dir_entry));
726 
727 			debug("DentName: %s", s_name);
728 			debug(", start: 0x%x", START(dentptr));
729 			debug(", size:  0x%x %s\n",
730 			      FAT2CPU32(dentptr->size),
731 			      (dentptr->attr & ATTR_DIR) ? "(DIR)" : "");
732 
733 			return retdent;
734 		}
735 
736 		curclust = get_fatent(mydata, curclust);
737 		if (CHECK_CLUST(curclust, mydata->fatsize)) {
738 			debug("curclust: 0x%x\n", curclust);
739 			printf("Invalid FAT entry\n");
740 			return NULL;
741 		}
742 	}
743 
744 	return NULL;
745 }
746 
747 /*
748  * Read boot sector and volume info from a FAT filesystem
749  */
750 static int
751 read_bootsectandvi(boot_sector *bs, volume_info *volinfo, int *fatsize)
752 {
753 	__u8 *block;
754 	volume_info *vistart;
755 	int ret = 0;
756 
757 	if (cur_dev == NULL) {
758 		debug("Error: no device selected\n");
759 		return -1;
760 	}
761 
762 	block = memalign(ARCH_DMA_MINALIGN, cur_dev->blksz);
763 	if (block == NULL) {
764 		debug("Error: allocating block\n");
765 		return -1;
766 	}
767 
768 	if (disk_read(0, 1, block) < 0) {
769 		debug("Error: reading block\n");
770 		goto fail;
771 	}
772 
773 	memcpy(bs, block, sizeof(boot_sector));
774 	bs->reserved = FAT2CPU16(bs->reserved);
775 	bs->fat_length = FAT2CPU16(bs->fat_length);
776 	bs->secs_track = FAT2CPU16(bs->secs_track);
777 	bs->heads = FAT2CPU16(bs->heads);
778 	bs->total_sect = FAT2CPU32(bs->total_sect);
779 
780 	/* FAT32 entries */
781 	if (bs->fat_length == 0) {
782 		/* Assume FAT32 */
783 		bs->fat32_length = FAT2CPU32(bs->fat32_length);
784 		bs->flags = FAT2CPU16(bs->flags);
785 		bs->root_cluster = FAT2CPU32(bs->root_cluster);
786 		bs->info_sector = FAT2CPU16(bs->info_sector);
787 		bs->backup_boot = FAT2CPU16(bs->backup_boot);
788 		vistart = (volume_info *)(block + sizeof(boot_sector));
789 		*fatsize = 32;
790 	} else {
791 		vistart = (volume_info *)&(bs->fat32_length);
792 		*fatsize = 0;
793 	}
794 	memcpy(volinfo, vistart, sizeof(volume_info));
795 
796 	if (*fatsize == 32) {
797 		if (strncmp(FAT32_SIGN, vistart->fs_type, SIGNLEN) == 0)
798 			goto exit;
799 	} else {
800 		if (strncmp(FAT12_SIGN, vistart->fs_type, SIGNLEN) == 0) {
801 			*fatsize = 12;
802 			goto exit;
803 		}
804 		if (strncmp(FAT16_SIGN, vistart->fs_type, SIGNLEN) == 0) {
805 			*fatsize = 16;
806 			goto exit;
807 		}
808 	}
809 
810 	debug("Error: broken fs_type sign\n");
811 fail:
812 	ret = -1;
813 exit:
814 	free(block);
815 	return ret;
816 }
817 
818 __u8 do_fat_read_at_block[MAX_CLUSTSIZE]
819 	__aligned(ARCH_DMA_MINALIGN);
820 
821 long
822 do_fat_read_at(const char *filename, unsigned long pos, void *buffer,
823 	       unsigned long maxsize, int dols)
824 {
825 	char fnamecopy[2048];
826 	boot_sector bs;
827 	volume_info volinfo;
828 	fsdata datablock;
829 	fsdata *mydata = &datablock;
830 	dir_entry *dentptr = NULL;
831 	__u16 prevcksum = 0xffff;
832 	char *subname = "";
833 	__u32 cursect;
834 	int idx, isdir = 0;
835 	int files = 0, dirs = 0;
836 	long ret = -1;
837 	int firsttime;
838 	__u32 root_cluster = 0;
839 	int rootdir_size = 0;
840 	int j;
841 
842 	if (read_bootsectandvi(&bs, &volinfo, &mydata->fatsize)) {
843 		debug("Error: reading boot sector\n");
844 		return -1;
845 	}
846 
847 	if (mydata->fatsize == 32) {
848 		root_cluster = bs.root_cluster;
849 		mydata->fatlength = bs.fat32_length;
850 	} else {
851 		mydata->fatlength = bs.fat_length;
852 	}
853 
854 	mydata->fat_sect = bs.reserved;
855 
856 	cursect = mydata->rootdir_sect
857 		= mydata->fat_sect + mydata->fatlength * bs.fats;
858 
859 	mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0];
860 	mydata->clust_size = bs.cluster_size;
861 	if (mydata->sect_size != cur_part_info.blksz) {
862 		printf("Error: FAT sector size mismatch (fs=%hu, dev=%lu)\n",
863 				mydata->sect_size, cur_part_info.blksz);
864 		return -1;
865 	}
866 
867 	if (mydata->fatsize == 32) {
868 		mydata->data_begin = mydata->rootdir_sect -
869 					(mydata->clust_size * 2);
870 	} else {
871 		rootdir_size = ((bs.dir_entries[1]  * (int)256 +
872 				 bs.dir_entries[0]) *
873 				 sizeof(dir_entry)) /
874 				 mydata->sect_size;
875 		mydata->data_begin = mydata->rootdir_sect +
876 					rootdir_size -
877 					(mydata->clust_size * 2);
878 	}
879 
880 	mydata->fatbufnum = -1;
881 	mydata->fatbuf = memalign(ARCH_DMA_MINALIGN, FATBUFSIZE);
882 	if (mydata->fatbuf == NULL) {
883 		debug("Error: allocating memory\n");
884 		return -1;
885 	}
886 
887 #ifdef CONFIG_SUPPORT_VFAT
888 	debug("VFAT Support enabled\n");
889 #endif
890 	debug("FAT%d, fat_sect: %d, fatlength: %d\n",
891 	       mydata->fatsize, mydata->fat_sect, mydata->fatlength);
892 	debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n"
893 	       "Data begins at: %d\n",
894 	       root_cluster,
895 	       mydata->rootdir_sect,
896 	       mydata->rootdir_sect * mydata->sect_size, mydata->data_begin);
897 	debug("Sector size: %d, cluster size: %d\n", mydata->sect_size,
898 	      mydata->clust_size);
899 
900 	/* "cwd" is always the root... */
901 	while (ISDIRDELIM(*filename))
902 		filename++;
903 
904 	/* Make a copy of the filename and convert it to lowercase */
905 	strcpy(fnamecopy, filename);
906 	downcase(fnamecopy);
907 
908 	if (*fnamecopy == '\0') {
909 		if (!dols)
910 			goto exit;
911 
912 		dols = LS_ROOT;
913 	} else if ((idx = dirdelim(fnamecopy)) >= 0) {
914 		isdir = 1;
915 		fnamecopy[idx] = '\0';
916 		subname = fnamecopy + idx + 1;
917 
918 		/* Handle multiple delimiters */
919 		while (ISDIRDELIM(*subname))
920 			subname++;
921 	} else if (dols) {
922 		isdir = 1;
923 	}
924 
925 	j = 0;
926 	while (1) {
927 		int i;
928 
929 		if (j == 0) {
930 			debug("FAT read sect=%d, clust_size=%d, DIRENTSPERBLOCK=%zd\n",
931 				cursect, mydata->clust_size, DIRENTSPERBLOCK);
932 
933 			if (disk_read(cursect,
934 					(mydata->fatsize == 32) ?
935 					(mydata->clust_size) :
936 					PREFETCH_BLOCKS,
937 					do_fat_read_at_block) < 0) {
938 				debug("Error: reading rootdir block\n");
939 				goto exit;
940 			}
941 
942 			dentptr = (dir_entry *) do_fat_read_at_block;
943 		}
944 
945 		for (i = 0; i < DIRENTSPERBLOCK; i++) {
946 			char s_name[14], l_name[VFAT_MAXLEN_BYTES];
947 			__u8 csum;
948 
949 			l_name[0] = '\0';
950 			if (dentptr->name[0] == DELETED_FLAG) {
951 				dentptr++;
952 				continue;
953 			}
954 
955 			csum = mkcksum(dentptr->name, dentptr->ext);
956 			if (dentptr->attr & ATTR_VOLUME) {
957 #ifdef CONFIG_SUPPORT_VFAT
958 				if ((dentptr->attr & ATTR_VFAT) == ATTR_VFAT &&
959 				    (dentptr->name[0] & LAST_LONG_ENTRY_MASK)) {
960 					prevcksum =
961 						((dir_slot *)dentptr)->alias_checksum;
962 
963 					get_vfatname(mydata,
964 						     root_cluster,
965 						     do_fat_read_at_block,
966 						     dentptr, l_name);
967 
968 					if (dols == LS_ROOT) {
969 						char dirc;
970 						int doit = 0;
971 						int isdir =
972 							(dentptr->attr & ATTR_DIR);
973 
974 						if (isdir) {
975 							dirs++;
976 							dirc = '/';
977 							doit = 1;
978 						} else {
979 							dirc = ' ';
980 							if (l_name[0] != 0) {
981 								files++;
982 								doit = 1;
983 							}
984 						}
985 						if (doit) {
986 							if (dirc == ' ') {
987 								printf(" %8ld   %s%c\n",
988 									(long)FAT2CPU32(dentptr->size),
989 									l_name,
990 									dirc);
991 							} else {
992 								printf("            %s%c\n",
993 									l_name,
994 									dirc);
995 							}
996 						}
997 						dentptr++;
998 						continue;
999 					}
1000 					debug("Rootvfatname: |%s|\n",
1001 					       l_name);
1002 				} else
1003 #endif
1004 				{
1005 					/* Volume label or VFAT entry */
1006 					dentptr++;
1007 					continue;
1008 				}
1009 			} else if (dentptr->name[0] == 0) {
1010 				debug("RootDentname == NULL - %d\n", i);
1011 				if (dols == LS_ROOT) {
1012 					printf("\n%d file(s), %d dir(s)\n\n",
1013 						files, dirs);
1014 					ret = 0;
1015 				}
1016 				goto exit;
1017 			}
1018 #ifdef CONFIG_SUPPORT_VFAT
1019 			else if (dols == LS_ROOT && csum == prevcksum) {
1020 				prevcksum = 0xffff;
1021 				dentptr++;
1022 				continue;
1023 			}
1024 #endif
1025 			get_name(dentptr, s_name);
1026 
1027 			if (dols == LS_ROOT) {
1028 				int isdir = (dentptr->attr & ATTR_DIR);
1029 				char dirc;
1030 				int doit = 0;
1031 
1032 				if (isdir) {
1033 					dirc = '/';
1034 					if (s_name[0] != 0) {
1035 						dirs++;
1036 						doit = 1;
1037 					}
1038 				} else {
1039 					dirc = ' ';
1040 					if (s_name[0] != 0) {
1041 						files++;
1042 						doit = 1;
1043 					}
1044 				}
1045 				if (doit) {
1046 					if (dirc == ' ') {
1047 						printf(" %8ld   %s%c\n",
1048 							(long)FAT2CPU32(dentptr->size),
1049 							s_name, dirc);
1050 					} else {
1051 						printf("            %s%c\n",
1052 							s_name, dirc);
1053 					}
1054 				}
1055 				dentptr++;
1056 				continue;
1057 			}
1058 
1059 			if (strcmp(fnamecopy, s_name)
1060 			    && strcmp(fnamecopy, l_name)) {
1061 				debug("RootMismatch: |%s|%s|\n", s_name,
1062 				       l_name);
1063 				dentptr++;
1064 				continue;
1065 			}
1066 
1067 			if (isdir && !(dentptr->attr & ATTR_DIR))
1068 				goto exit;
1069 
1070 			debug("RootName: %s", s_name);
1071 			debug(", start: 0x%x", START(dentptr));
1072 			debug(", size:  0x%x %s\n",
1073 			       FAT2CPU32(dentptr->size),
1074 			       isdir ? "(DIR)" : "");
1075 
1076 			goto rootdir_done;	/* We got a match */
1077 		}
1078 		debug("END LOOP: j=%d   clust_size=%d\n", j,
1079 		       mydata->clust_size);
1080 
1081 		/*
1082 		 * On FAT32 we must fetch the FAT entries for the next
1083 		 * root directory clusters when a cluster has been
1084 		 * completely processed.
1085 		 */
1086 		++j;
1087 		int rootdir_end = 0;
1088 		if (mydata->fatsize == 32) {
1089 			if (j == mydata->clust_size) {
1090 				int nxtsect = 0;
1091 				int nxt_clust = 0;
1092 
1093 				nxt_clust = get_fatent(mydata, root_cluster);
1094 				rootdir_end = CHECK_CLUST(nxt_clust, 32);
1095 
1096 				nxtsect = mydata->data_begin +
1097 					(nxt_clust * mydata->clust_size);
1098 
1099 				root_cluster = nxt_clust;
1100 
1101 				cursect = nxtsect;
1102 				j = 0;
1103 			}
1104 		} else {
1105 			if (j == PREFETCH_BLOCKS)
1106 				j = 0;
1107 
1108 			rootdir_end = (++cursect - mydata->rootdir_sect >=
1109 				       rootdir_size);
1110 		}
1111 
1112 		/* If end of rootdir reached */
1113 		if (rootdir_end) {
1114 			if (dols == LS_ROOT) {
1115 				printf("\n%d file(s), %d dir(s)\n\n",
1116 				       files, dirs);
1117 				ret = 0;
1118 			}
1119 			goto exit;
1120 		}
1121 	}
1122 rootdir_done:
1123 
1124 	firsttime = 1;
1125 
1126 	while (isdir) {
1127 		int startsect = mydata->data_begin
1128 			+ START(dentptr) * mydata->clust_size;
1129 		dir_entry dent;
1130 		char *nextname = NULL;
1131 
1132 		dent = *dentptr;
1133 		dentptr = &dent;
1134 
1135 		idx = dirdelim(subname);
1136 
1137 		if (idx >= 0) {
1138 			subname[idx] = '\0';
1139 			nextname = subname + idx + 1;
1140 			/* Handle multiple delimiters */
1141 			while (ISDIRDELIM(*nextname))
1142 				nextname++;
1143 			if (dols && *nextname == '\0')
1144 				firsttime = 0;
1145 		} else {
1146 			if (dols && firsttime) {
1147 				firsttime = 0;
1148 			} else {
1149 				isdir = 0;
1150 			}
1151 		}
1152 
1153 		if (get_dentfromdir(mydata, startsect, subname, dentptr,
1154 				     isdir ? 0 : dols) == NULL) {
1155 			if (dols && !isdir)
1156 				ret = 0;
1157 			goto exit;
1158 		}
1159 
1160 		if (isdir && !(dentptr->attr & ATTR_DIR))
1161 			goto exit;
1162 
1163 		if (idx >= 0)
1164 			subname = nextname;
1165 	}
1166 
1167 	ret = get_contents(mydata, dentptr, pos, buffer, maxsize);
1168 	debug("Size: %d, got: %ld\n", FAT2CPU32(dentptr->size), ret);
1169 
1170 exit:
1171 	free(mydata->fatbuf);
1172 	return ret;
1173 }
1174 
1175 long
1176 do_fat_read(const char *filename, void *buffer, unsigned long maxsize, int dols)
1177 {
1178 	return do_fat_read_at(filename, 0, buffer, maxsize, dols);
1179 }
1180 
1181 int file_fat_detectfs(void)
1182 {
1183 	boot_sector bs;
1184 	volume_info volinfo;
1185 	int fatsize;
1186 	char vol_label[12];
1187 
1188 	if (cur_dev == NULL) {
1189 		printf("No current device\n");
1190 		return 1;
1191 	}
1192 
1193 #if defined(CONFIG_CMD_IDE) || \
1194     defined(CONFIG_CMD_SATA) || \
1195     defined(CONFIG_CMD_SCSI) || \
1196     defined(CONFIG_CMD_USB) || \
1197     defined(CONFIG_MMC)
1198 	printf("Interface:  ");
1199 	switch (cur_dev->if_type) {
1200 	case IF_TYPE_IDE:
1201 		printf("IDE");
1202 		break;
1203 	case IF_TYPE_SATA:
1204 		printf("SATA");
1205 		break;
1206 	case IF_TYPE_SCSI:
1207 		printf("SCSI");
1208 		break;
1209 	case IF_TYPE_ATAPI:
1210 		printf("ATAPI");
1211 		break;
1212 	case IF_TYPE_USB:
1213 		printf("USB");
1214 		break;
1215 	case IF_TYPE_DOC:
1216 		printf("DOC");
1217 		break;
1218 	case IF_TYPE_MMC:
1219 		printf("MMC");
1220 		break;
1221 	default:
1222 		printf("Unknown");
1223 	}
1224 
1225 	printf("\n  Device %d: ", cur_dev->dev);
1226 	dev_print(cur_dev);
1227 #endif
1228 
1229 	if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
1230 		printf("\nNo valid FAT fs found\n");
1231 		return 1;
1232 	}
1233 
1234 	memcpy(vol_label, volinfo.volume_label, 11);
1235 	vol_label[11] = '\0';
1236 	volinfo.fs_type[5] = '\0';
1237 
1238 	printf("Filesystem: %s \"%s\"\n", volinfo.fs_type, vol_label);
1239 
1240 	return 0;
1241 }
1242 
1243 int file_fat_ls(const char *dir)
1244 {
1245 	return do_fat_read(dir, NULL, 0, LS_YES);
1246 }
1247 
1248 long file_fat_read_at(const char *filename, unsigned long pos, void *buffer,
1249 		      unsigned long maxsize)
1250 {
1251 	printf("reading %s\n", filename);
1252 	return do_fat_read_at(filename, pos, buffer, maxsize, LS_NO);
1253 }
1254 
1255 long file_fat_read(const char *filename, void *buffer, unsigned long maxsize)
1256 {
1257 	return file_fat_read_at(filename, 0, buffer, maxsize);
1258 }
1259