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