3 * Stäubli Faverges - <www.staubli.com>
4 * Pierre AUBERT p.aubert@staubli.com
6 * SPDX-License-Identifier: GPL-2.0+
17 /*-----------------------------------------------------------------------------
19 *-----------------------------------------------------------------------------
21 unsigned int fat_decode (Fs_t *fs, unsigned int num)
23 unsigned int start = num * 3 / 2;
24 unsigned char *address = fs -> fat_buf + start;
26 if (num < 2 || start + 1 > (fs -> fat_len * SZ_STD_SECTOR))
30 return ((address [1] & 0xff) << 4) | ((address [0] & 0xf0 ) >> 4);
32 return ((address [1] & 0xf) << 8) | (address [0] & 0xff );
34 /*-----------------------------------------------------------------------------
36 *-----------------------------------------------------------------------------
38 static int check_fat (Fs_t *fs)
42 /* Cluster verification */
43 for (i = 3 ; i < fs -> num_clus; i++){
44 f = fat_decode (fs, i);
45 if (f < FAT12_LAST && f > fs -> num_clus){
46 /* Wrong cluster number detected */
52 /*-----------------------------------------------------------------------------
54 *-----------------------------------------------------------------------------
56 static int read_one_fat (BootSector_t *boot, Fs_t *fs, int nfat)
58 if (dev_read (fs -> fat_buf,
59 (fs -> fat_start + nfat * fs -> fat_len),
64 if (fs -> fat_buf [0] || fs -> fat_buf [1] || fs -> fat_buf [2]) {
65 if ((fs -> fat_buf [0] != boot -> descr &&
66 (fs -> fat_buf [0] != 0xf9 || boot -> descr != MEDIA_STD)) ||
67 fs -> fat_buf [0] < MEDIA_STD){
71 if (fs -> fat_buf [1] != 0xff || fs -> fat_buf [2] != 0xff){
72 /* FAT doesn't start with good values */
77 if (fs -> num_clus >= FAT12_MAX_NB) {
78 /* Too much clusters */
82 return check_fat (fs);
84 /*-----------------------------------------------------------------------------
86 *-----------------------------------------------------------------------------
88 int read_fat (BootSector_t *boot, Fs_t *fs)
93 /* Allocate Fat Buffer */
94 buflen = fs -> fat_len * SZ_STD_SECTOR;
99 if ((fs -> fat_buf = malloc (buflen)) == NULL) {
103 /* Try to read each Fat */
104 for (i = 0; i< fs -> nb_fat; i++){
105 if (read_one_fat (boot, fs, i) == 0) {
112 if (i == fs -> nb_fat){
116 if (fs -> fat_len > (((fs -> num_clus + 2) *
117 (FAT_BITS / 4) -1 ) / 2 /
118 SZ_STD_SECTOR + 1)) {