summaryrefslogtreecommitdiff
path: root/nuttx/fs/fat/fs_fat32util.c
blob: a37f8fadbfbb8e34a673fd3488d6063a245f8cde (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
/****************************************************************************
 * fs/fat/fs_fat32util.c
 *
 *   Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <spudmonkey@racsa.co.cr>
 *
 * References:
 *   Microsoft FAT documentation
 *   Some good ideas were leveraged from the FAT implementation:
 *     'Copyright (C) 2007, ChaN, all right reserved.'
 *     which has an unrestricted license.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <semaphore.h>
#include <assert.h>
#include <errno.h>
#include <debug.h>

#include <nuttx/kmalloc.h>
#include <nuttx/fs.h>
#include <nuttx/fat.h>

#include "fs_internal.h"
#include "fs_fat32.h"

/****************************************************************************
 * Definitions
 ****************************************************************************/

/****************************************************************************
 * Private Types
 ****************************************************************************/

/****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/

/****************************************************************************
 * Private Variables
 ****************************************************************************/

/****************************************************************************
 * Public Variables
 ****************************************************************************/

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Name: fat_path2dirname
 *
 * Desciption:  Convert a user filename into a properly formatted FAT
 *   (short) filname as it would appear in a directory entry.  Here are the
 *    rules for the 11 byte name in the directory:
 *
 *   The first byte:
 *   - 0xe5 = The directory is free
 *   - 0x00 = This directory and all following directories are free
 *   - 0x05 = Really 0xe5
 *   - 0x20 = May NOT be ' '
 *
 *   Any bytes
 *     0x00-0x1f = (except for 0x00 and 0x05 in the first byte)
 *     0x22      = '"'
 *     0x2a-0x2c = '*', '+', ','
 *     0x2e-0x2f = '.', '/'
 *     0x3a-0x3f = ':', ';', '<', '=', '>', '?'
 *     0x5b-0x5d = '[', '\\', ;]'
 *     0x7c      = '|'
 *
 *   Upper case characters are not allowed in directory names (without some
 *   poorly documented operatgions on the NTRes directory byte).  Lower case
 *   codes may represent different characters in other character sets ("DOS
 *   code pages".  The logic below does not, at present, support any other
 *   character sets.
 *
 ****************************************************************************/

static inline int fat_path2dirname(const char **path, struct fat_dirinfo_s *dirinfo,
                                   char *terminator)
{
#ifdef CONFIG_FAT_LCNAMES
    unsigned int ntlcenable = FATNTRES_LCNAME | FATNTRES_LCEXT;
    unsigned int ntlcfound  = 0;
#endif
    const char *node = *path;
    int endndx;
    uint8_t ch;
    int ndx = 0;

    /* Initialized the name with all spaces */

    memset(dirinfo->fd_name, ' ', 8+3);
 
    /* Loop until the name is successfully parsed or an error occurs */

    endndx  = 8;
    for (;;)
      {
        /* Get the next byte from the path */

        ch = *node++;

        /* Check if this the last byte in this node of the name */

        if ((ch == '\0' || ch == '/') && ndx != 0 )
          {
            /* Return the accumulated NT flags and the terminating character */
#ifdef CONFIG_FAT_LCNAMES
            dirinfo->fd_ntflags = ntlcfound & ntlcenable;
#endif
            *terminator = ch;
            *path       = node;
            return OK;
          }

        /* Accept only the printable character set.  Note the first byte
         * of the name could be 0x05 meaning that is it 0xe5, but this is
         * not a printable character in this character in either case.
         */

        else if (!isgraph(ch))
          {
            goto errout;
          }

        /* Check for transition from name to extension */

        else if (ch == '.')
          {
            /* Starting the extension */

            ndx    = 8;
            endndx = 11;
            continue;
          }

        /* Reject printable characters forbidden by FAT */

        else if (ch == '"'  ||  (ch >= '*' && ch <= ',') ||
                 ch == '.'  ||   ch == '/'               ||
                (ch >= ':'  &&   ch <= '?')              ||
                (ch >= '['  &&   ch <= ']')              ||
                (ch == '|'))
          {
            goto errout;
          }

        /* Check for upper case charaters */

#ifdef CONFIG_FAT_LCNAMES
        else if (isupper(ch))
          {
            /* Some or all of the characters in the name or extension
             * are upper case. Force all of the characters to be interpreted
             * as upper case.
             */

              if ( endndx == 8)
                {
                  /* Clear lower case name bit in mask*/
                  ntlcenable &= FATNTRES_LCNAME;
                }
              else
                {
                  /* Clear lower case extension in mask */
                  ntlcenable &= FATNTRES_LCNAME;
                }
          }
#endif

        /* Check for lower case characters */

        else if (islower(ch))
          {
            /* Convert the character to upper case */

            ch = toupper(ch);

            /* Some or all of the characters in the name or extension
             * are lower case.  They can be interpreted as lower case if
             * only if all of the characters in the name or extension are
             * lower case.
             */

#ifdef CONFIG_FAT_LCNAMES
            if ( endndx == 8)
              {
                /* Set lower case name bit */
                ntlcfound |= FATNTRES_LCNAME;
              }
            else
              {
                /* Set lower case extension bit */
                ntlcfound |= FATNTRES_LCNAME;
              }
#endif
          }

        /* Check if the file name exceeds the size permitted (without
         * long file name support
         */

        if (ndx >= endndx)
          {
            goto errout;
          }

        /* Save next character in the accumulated name */

        dirinfo->fd_name[ndx++] = ch;
      }

 errout:
    return -EINVAL;
}

/****************************************************************************
 * Name: fat_checkfsinfo
 *
 * Desciption: Read the FAT32 FSINFO sector
 *
 ****************************************************************************/

static int fat_checkfsinfo(struct fat_mountpt_s *fs)
{
  /* Make sure that the fsinfo sector is in the cache */

  if (fat_fscacheread(fs, fs->fs_fsinfo) == OK)
    {
      /* Verify that this is, indeed, an FSINFO sector */

      if (FSI_GETLEADSIG(fs->fs_buffer) == 0x41615252  &&
          FSI_GETSTRUCTSIG(fs->fs_buffer) == 0x61417272 &&
          FSI_GETTRAILSIG(fs->fs_buffer) == BOOT_SIGNATURE32)
        {
          fs->fs_fsinextfree  = FSI_GETFREECOUNT(fs->fs_buffer);
          fs->fs_fsifreecount = FSI_GETNXTFREE(fs->fs_buffer);
          return OK;
        }
    }
  return -ENODEV;
}

/****************************************************************************
 * Name: fat_checkbootrecord
 *
 * Desciption: Read a sector and verify that it is a a FAT boot record.
 *
 ****************************************************************************/

static int fat_checkbootrecord(struct fat_mountpt_s *fs)
{
  uint32_t ndatasectors;
  uint32_t ntotalfatsects;
  uint16_t rootdirsectors = 0;
  bool     notfat32 = false;

  /* Verify the MBR signature at offset 510 in the sector (true even
   * if the sector size is greater than 512.  All FAT file systems have
   * this signature. On a FAT32 volume, the RootEntCount , FatSz16, and
   * FatSz32 values should always be zero.  The FAT sector size should
   * match the reported hardware sector size.
   */

  if (MBR_GETSIGNATURE(fs->fs_buffer) != BOOT_SIGNATURE16 ||
      MBR_GETBYTESPERSEC(fs->fs_buffer) != fs->fs_hwsectorsize)
    {
      return -ENODEV;
    }

  /* Verify the FAT32 file system type. The determination of the file
   * system type is based on the number of clusters on the volume:  FAT12
   * volume has <= FAT_MAXCLUST12 (4084) clusters, a FAT16 volume has <=
   * FAT_MINCLUST16 (microsfoft says < 65,525) clusters, and any larger
   * is FAT32.
   *
   * Get the number of 32-bit directory entries in root directory (zero
   * for FAT32).
   */

  fs->fs_rootentcnt = MBR_GETROOTENTCNT(fs->fs_buffer);
  if (fs->fs_rootentcnt != 0)
    {
      notfat32       = true; /* Must be zero for FAT32 */
      rootdirsectors = (32 * fs->fs_rootentcnt  + fs->fs_hwsectorsize - 1) / fs->fs_hwsectorsize;
    }

  /* Determine the number of sectors in a FAT. */

  fs->fs_nfatsects = MBR_GETFATSZ16(fs->fs_buffer); /* Should be zero */
  if (fs->fs_nfatsects)
    {
      notfat32 = true; /* Must be zero for FAT32 */
    }
  else
    {
      fs->fs_nfatsects = MBR_GETFATSZ32(fs->fs_buffer);
    }

  if (!fs->fs_nfatsects || fs->fs_nfatsects >= fs->fs_hwnsectors)
    {
      return -ENODEV;
    }

  /* Get the total number of sectors on the volume. */

  fs->fs_fattotsec = MBR_GETTOTSEC16(fs->fs_buffer); /* Should be zero */
  if (fs->fs_fattotsec)
    {
      notfat32 = true; /* Must be zero for FAT32 */
    }
  else
    {
      fs->fs_fattotsec = MBR_GETTOTSEC32(fs->fs_buffer);
    }

  if (!fs->fs_fattotsec || fs->fs_fattotsec > fs->fs_hwnsectors)
    {
      return -ENODEV;
    }

  /* Get the total number of reserved sectors */

  fs->fs_fatresvdseccount = MBR_GETRESVDSECCOUNT(fs->fs_buffer);
  if (fs->fs_fatresvdseccount > fs->fs_hwnsectors)
    {
      return -ENODEV;
    }

  /* Get the number of FATs. This is probably two but could have other values */

  fs->fs_fatnumfats = MBR_GETNUMFATS(fs->fs_buffer);
  ntotalfatsects = fs->fs_fatnumfats * fs->fs_nfatsects;

  /* Get the total number of data sectors */

  ndatasectors = fs->fs_fattotsec - fs->fs_fatresvdseccount - ntotalfatsects - rootdirsectors;
  if (ndatasectors > fs->fs_hwnsectors)
    {
      return -ENODEV;
    }

  /* Get the sectors per cluster */

  fs->fs_fatsecperclus = MBR_GETSECPERCLUS(fs->fs_buffer);

  /* Calculate the number of clusters */

  fs->fs_nclusters = ndatasectors / fs->fs_fatsecperclus;

  /* Finally, the test: */

  if (fs->fs_nclusters <= FAT_MAXCLUST12)
    {
      fs->fs_fsinfo = 0;
      fs->fs_type   = FSTYPE_FAT12;
    }
  else if (fs->fs_nclusters <= FAT_MAXCLUST16)
    {
      fs->fs_fsinfo = 0;
      fs->fs_type   = FSTYPE_FAT16;
    }
  else if (!notfat32)
    {
      fs->fs_fsinfo   = fs->fs_fatbase + MBR_GETFSINFO(fs->fs_buffer);
      fs->fs_type     = FSTYPE_FAT32;
    }
  else
    {
      return -ENODEV;
    }

  /* We have what appears to be a valid FAT filesystem! Save a few more things
   * from the boot record that we will need later.
   */

  fs->fs_fatbase     += fs->fs_fatresvdseccount;

  if (fs->fs_type == FSTYPE_FAT32)
    {
      fs->fs_rootbase = MBR_GETROOTCLUS(fs->fs_buffer);
    }
  else
    {
      fs->fs_rootbase = fs->fs_fatbase + ntotalfatsects; 
    }

  fs->fs_database     = fs->fs_fatbase + ntotalfatsects + fs->fs_rootentcnt / DIRSEC_NDIRS(fs);
  fs->fs_fsifreecount = 0xffffffff;

  return OK;
}

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: fat_getuint16
 ****************************************************************************/

uint16_t fat_getuint16(uint8_t *ptr)
{
#ifdef CONFIG_ENDIAN_BIG
  /* The bytes always have to be swapped if the target is big-endian */

  return ((uint16_t)ptr[0] << 8) | ptr[1];
#else
  /* Byte-by-byte transfer is still necessary if the address is un-aligned */

  return ((uint16_t)ptr[1] << 8) | ptr[0];
#endif
}

/****************************************************************************
 * Name: fat_getuint32
 ****************************************************************************/

uint32_t fat_getuint32(uint8_t *ptr)
{
#ifdef CONFIG_ENDIAN_BIG
  /* The bytes always have to be swapped if the target is big-endian */

  return ((uint32_t)fat_getuint16(&ptr[0]) << 16) | fat_getuint16(&ptr[2]);
#else
  /* Byte-by-byte transfer is still necessary if the address is un-aligned */

  return ((uint32_t)fat_getuint16(&ptr[2]) << 16) | fat_getuint16(&ptr[0]);
#endif
}

/****************************************************************************
 * Name: fat_putuint16
 ****************************************************************************/

void fat_putuint16(uint8_t *ptr, uint16_t value16)
{
  uint8_t *val = (uint8_t*)&value16;
#ifdef CONFIG_ENDIAN_BIG
  /* The bytes always have to be swapped if the target is big-endian */

  ptr[0] = val[1];
  ptr[1] = val[0];
#else
  /* Byte-by-byte transfer is still necessary if the address is un-aligned */

  ptr[0] = val[0];
  ptr[1] = val[1];
#endif
}

/****************************************************************************
 * Name: fat_putuint32
 ****************************************************************************/

void fat_putuint32(uint8_t *ptr, uint32_t value32)
{
  uint16_t *val = (uint16_t*)&value32;
#ifdef CONFIG_ENDIAN_BIG
  /* The bytes always have to be swapped if the target is big-endian */

  fat_putuint16(&ptr[0], val[2]);
  fat_putuint16(&ptr[2], val[0]);
#else
  /* Byte-by-byte transfer is still necessary if the address is un-aligned */

  fat_putuint16(&ptr[0], val[0]);
  fat_putuint16(&ptr[2], val[2]);
#endif
}

/****************************************************************************
 * Name: fat_semtake
 ****************************************************************************/

void fat_semtake(struct fat_mountpt_s *fs)
{
  /* Take the semaphore (perhaps waiting) */

  while (sem_wait(&fs->fs_sem) != 0)
    {
      /* The only case that an error should occur here is if
       * the wait was awakened by a signal.
       */

      ASSERT(*get_errno_ptr() == EINTR);
    }
}

/****************************************************************************
 * Name: fat_semgive
 ****************************************************************************/

void fat_semgive(struct fat_mountpt_s *fs)
{
   sem_post(&fs->fs_sem);
}

/****************************************************************************
 * Name: fat_systime2fattime
 *
 * Desciption: Get the system time convertto a time and and date suitble
 * for writing into the FAT FS.
 *
 *    TIME in LS 16-bits:
 *      Bits 0:4   = 2 second count (0-29 representing 0-58 seconds)
 *      Bits 5-10  = minutes (0-59)
 *      Bits 11-15 = hours (0-23)
 *    DATE in MS 16-bits
 *      Bits 0:4   = Day of month (0-31)
 *      Bits 5:8   = Month of year (1-12)
 *      Bits 9:15  = Year from 1980 (0-127 representing 1980-2107)
 *
 ****************************************************************************/

uint32_t fat_systime2fattime(void)
{
    return 0;
}

/****************************************************************************
 * Name: fat_fattime2systime
 *
 * Desciption: Convert FAT data and time to a system time_t
 *
 *    16-bit FAT time:
 *      Bits 0:4   = 2 second count (0-29 representing 0-58 seconds)
 *      Bits 5-10  = minutes (0-59)
 *      Bits 11-15 = hours (0-23)
 *    16-bit FAT date:
 *      Bits 0:4   = Day of month (0-31)
 *      Bits 5:8   = Month of year (1-12)
 *      Bits 9:15  = Year from 1980 (0-127 representing 1980-2107)
 *
 ****************************************************************************/

time_t fat_fattime2systime(uint16_t fattime, uint16_t fatdate)
{
    return 0;
}

/****************************************************************************
 * Name: fat_mount
 *
 * Desciption: This function is called only when the mountpoint is first
 *   established.  It initializes the mountpoint structure and verifies
 *   that a valid FAT32 filesystem is provided by the block driver.
 *
 *   The caller should hold the mountpoint semaphore
 *
 ****************************************************************************/

int fat_mount(struct fat_mountpt_s *fs, bool writeable)
{
  FAR struct inode *inode;
  struct geometry geo;
  int ret;

  /* Assume that the mount is successful */

  fs->fs_mounted = true;

  /* Check if there is media available */

  inode = fs->fs_blkdriver;
  if (!inode || !inode->u.i_bops || !inode->u.i_bops->geometry ||
      inode->u.i_bops->geometry(inode, &geo) != OK || !geo.geo_available)
    {
      ret = -ENODEV;
      goto errout;
    }

  /* Make sure that that the media is write-able (if write access is needed) */

  if (writeable && !geo.geo_writeenabled)
    {
      ret = -EACCES;
      goto errout;
    }

  /* Save the hardware geometry */

  fs->fs_hwsectorsize = geo.geo_sectorsize;
  fs->fs_hwnsectors   = geo.geo_nsectors;

  /* Allocate a buffer to hold one hardware sector */

  fs->fs_buffer = (uint8_t*)kmalloc(fs->fs_hwsectorsize);
  if (!fs->fs_buffer)
    {
      ret = -ENOMEM;
      goto errout;
    }

  /* Search FAT boot record on the drive.  First check at sector zero.  This
   * could be either the boot record or a partition that refers to the boot
   * record.
   *
   * First read sector zero.  This will be the first access to the drive and a
   * likely failure point.
   */

  fs->fs_fatbase = 0;
  ret = fat_hwread(fs, fs->fs_buffer, 0, 1);
  if (ret < 0)
    {
      goto errout_with_buffer;
    }

  ret = fat_checkbootrecord(fs);
  if (ret != OK)
    {
      /* The contents of sector 0 is not a boot record.  It could be a
       * partition, however.  Assume it is a partition and get the offset
       * into the partition table.  This table is at offset MBR_TABLE and is
       * indexed by 16x the partition number.  Here we support only
       * partition 0.
       *
       * Check if the partition exists and, if so, get the bootsector for that
       * partition and see if we can find the boot record there.
       */
 
      if (PART1_GETTYPE(fs->fs_buffer) == 0)
        {
          fdbg("No MBR or partition\n");
          goto errout_with_buffer;
        }

      /* There appears to be a partition, get the sector number of the
       * partition (LBA)
       */

      fs->fs_fatbase = PART1_GETSTARTSECTOR(fs->fs_buffer);

      /* Read the new candidate boot sector */

      ret = fat_hwread(fs, fs->fs_buffer, fs->fs_fatbase, 1);
      if (ret < 0)
        {
          goto errout_with_buffer;
        }

      /* Check if this is a boot record */

      ret = fat_checkbootrecord(fs);
      if (ret != OK)
        {
          fdbg("No valid MBR\n");
          goto errout_with_buffer;
        }
    }

  /* We have what appears to be a valid FAT filesystem! Now read the
   * FSINFO sector (FAT32 only)
   */

  if (fs->fs_type == FSTYPE_FAT32)
  {
      ret = fat_checkfsinfo(fs);
      if (ret != OK)
      {
        goto errout_with_buffer;
      }
  }

  /* We did it! */

  fdbg("FAT%d:\n", fs->fs_type == 0 ? 12 : fs->fs_type == 1  ? 16 : 32);
  fdbg("\tHW  sector size:     %d\n", fs->fs_hwsectorsize);
  fdbg("\t    sectors:         %d\n", fs->fs_hwnsectors);
  fdbg("\tFAT reserved:        %d\n", fs->fs_fatresvdseccount);
  fdbg("\t    sectors:         %d\n", fs->fs_fattotsec);
  fdbg("\t    start sector:    %d\n", fs->fs_fatbase);
  fdbg("\t    root sector:     %d\n", fs->fs_rootbase);
  fdbg("\t    root entries:    %d\n", fs->fs_rootentcnt);
  fdbg("\t    data sector:     %d\n", fs->fs_database);
  fdbg("\t    FSINFO sector:   %d\n", fs->fs_fsinfo);
  fdbg("\t    Num FATs:        %d\n", fs->fs_fatnumfats);
  fdbg("\t    FAT sectors:     %d\n", fs->fs_nfatsects);
  fdbg("\t    sectors/cluster: %d\n", fs->fs_fatsecperclus);
  fdbg("\t    max clusters:    %d\n", fs->fs_nclusters);
  fdbg("\tFSI free count       %d\n", fs->fs_fsifreecount);
  fdbg("\t    next free        %d\n", fs->fs_fsinextfree);

  return OK;

 errout_with_buffer:
  kfree(fs->fs_buffer);
  fs->fs_buffer = 0;
 errout:
  fs->fs_mounted = false;
  return ret;
}

/****************************************************************************
 * Name: fat_checkmount
 *
 * Desciption: Check if the mountpoint is still valid.
 *
 *   The caller should hold the mountpoint semaphore
 *
 ****************************************************************************/

int fat_checkmount(struct fat_mountpt_s *fs)
{
  /* If the fs_mounted flag is false, then we have already handled the loss
   * of the mount.
   */

  if (fs && fs->fs_mounted)
    {
      struct fat_file_s *file;

      /* We still think the mount is healthy.  Check an see if this is
       * still the case
       */

      if (fs->fs_blkdriver)
        {
          struct inode *inode = fs->fs_blkdriver;
          if (inode && inode->u.i_bops && inode->u.i_bops->geometry)
            {
              struct geometry geo;
              int errcode = inode->u.i_bops->geometry(inode, &geo);
              if (errcode == OK && geo.geo_available && !geo.geo_mediachanged)
                {
                  return OK;
                }
            }
        }

      /* If we get here, the mount is NOT healthy */

      fs->fs_mounted = false;

      /* Make sure that this is flagged in every opened file */

      for (file = fs->fs_head; file; file = file->ff_next)
        {
          file->ff_open = false;
        }
    }
  return -ENODEV;
}

/****************************************************************************
 * Name: fat_hwread
 *
 * Desciption: Read the specified sector into the sector buffer
 *
 ****************************************************************************/

int fat_hwread(struct fat_mountpt_s *fs, uint8_t *buffer,  size_t sector,
               unsigned int nsectors)
{
  int ret = -ENODEV;
  if (fs && fs->fs_blkdriver )
    {
      struct inode *inode = fs->fs_blkdriver;
      if (inode && inode->u.i_bops && inode->u.i_bops->read)
        {
          ssize_t nSectorsRead = inode->u.i_bops->read(inode, buffer,
                                                       sector, nsectors);
          if (nSectorsRead == nsectors)
            {
              ret = OK;
            }
          else if (nSectorsRead < 0)
            {
              ret = nSectorsRead;
            }
        }
    }
  return ret;
}

/****************************************************************************
 * Name: fat_hwwrite
 *
 * Desciption: Write the sector buffer to the specified sector
 *
 ****************************************************************************/

int fat_hwwrite(struct fat_mountpt_s *fs, uint8_t *buffer, size_t sector,
                unsigned int nsectors)
{
  int ret = -ENODEV;
  if (fs && fs->fs_blkdriver )
    {
      struct inode *inode = fs->fs_blkdriver;
      if (inode && inode->u.i_bops && inode->u.i_bops->write)
        {
          ssize_t nSectorsWritten =
              inode->u.i_bops->write(inode, buffer, sector, nsectors);

          if (nSectorsWritten == nsectors)
            {
              ret = OK;
            }
          else if (nSectorsWritten < 0)
            {
              ret = nSectorsWritten;
            }
        }
    }
  return ret;
}

/****************************************************************************
 * Name: fat_cluster2sector
 *
 * Desciption: Convert a cluster number to a start sector number
 *
 ****************************************************************************/

ssize_t fat_cluster2sector(struct fat_mountpt_s *fs,  uint32_t cluster )
{
  cluster -= 2;
  if (cluster >= fs->fs_nclusters - 2)
    {
       return -EINVAL;
    }
  return cluster * fs->fs_fatsecperclus + fs->fs_database;
}

/****************************************************************************
 * Name: fat_getcluster
 *
 * Desciption: Get the next cluster start from the FAT.
 *
 * Return:  <0: error, 0:cluster unassigned, >=0: start sector of cluster
 *
 ****************************************************************************/

ssize_t fat_getcluster(struct fat_mountpt_s *fs, uint32_t clusterno)
{
  /* Verify that the cluster number is within range */

  if (clusterno >= 2 && clusterno < fs->fs_nclusters)
    {
      /* Okay.. Read the next cluster from the FAT.  The way we will do
       * this depends on the type of FAT filesystm we are dealing with.
       */

      switch (fs->fs_type)
        {
          case FSTYPE_FAT12 :
            {
              size_t       fatsector;
              unsigned int fatoffset;
              unsigned int cluster;
              unsigned int fatindex;

              /* FAT12 is more complex because it has 12-bits (1.5 bytes)
               * per FAT entry. Get the offset to the first byte:
               */

              fatoffset = (clusterno * 3) / 2;
              fatsector = fs->fs_fatbase + SEC_NSECTORS(fs, fatoffset);

              /* Read the sector at this offset */

              if (fat_fscacheread(fs, fatsector) < 0)
                {
                  /* Read error */

                  break;
                }

              /* Get the first, LS byte of the cluster from the FAT */

              fatindex = fatoffset & SEC_NDXMASK(fs);
              cluster  = fs->fs_buffer[fatindex];

              /* With FAT12, the second byte of the cluster number may lie in
               * a different sector than the first byte.
               */

              fatindex++;
              if (fatindex >= fs->fs_hwsectorsize)
                {
                  fatsector++;
                  fatindex = 0;

                  if (fat_fscacheread(fs, fatsector) < 0)
                    {
                      /* Read error */

                      break;
                    }
                }

              /* Get the second, MS byte of the cluster for 16-bits.  The
               * does not depend on the endian-ness of the target, but only
               * on the fact that the byte stream is little-endian.
               */

              cluster |= (unsigned int)fs->fs_buffer[fatindex] << 8;

              /* Now, pick out the correct 12 bit cluster start sector value */

              if ((clusterno & 1) != 0)
                {
                  /* Odd.. take the MS 12-bits */

                  cluster >>= 4;
                }
              else
                {
                  /* Even.. take the LS 12-bits */

                  cluster &= 0x0fff;
                }
              return cluster;
            }

          case FSTYPE_FAT16 :
            {
              unsigned int fatoffset = 2 * clusterno;
              size_t       fatsector = fs->fs_fatbase + SEC_NSECTORS(fs, fatoffset);
              unsigned int fatindex  = fatoffset & SEC_NDXMASK(fs);

              if (fat_fscacheread(fs, fatsector) < 0)
                {
                  /* Read error */
                  break;
                }
              return FAT_GETFAT16(fs->fs_buffer, fatindex);
            }

          case FSTYPE_FAT32 :
            {
              unsigned int fatoffset = 4 * clusterno;
              size_t       fatsector = fs->fs_fatbase + SEC_NSECTORS(fs, fatoffset);
              unsigned int fatindex  = fatoffset & SEC_NDXMASK(fs);

              if (fat_fscacheread(fs, fatsector) < 0)
                {
                  /* Read error */
                  break;
                }
              return FAT_GETFAT32(fs->fs_buffer, fatindex) & 0x0fffffff;
            }
          default:
              break;
        }
    }

  /* There is no cluster information, or an error occured */

  return (ssize_t)-EINVAL;
}

/****************************************************************************
 * Name: fat_putcluster
 *
 * Desciption: Write a new cluster into the FAT
 *
 ****************************************************************************/

int fat_putcluster(struct fat_mountpt_s *fs, uint32_t clusterno, size_t nextcluster)
{
  /* Verify that the cluster number is within range.  Zero erases the cluster. */

  if (clusterno == 0 || (clusterno >= 2 && clusterno < fs->fs_nclusters))
    {
      /* Okay.. Write the next cluster into the FAT.  The way we will do
       * this depends on the type of FAT filesystm we are dealing with.
       */

      switch (fs->fs_type)
        {
          case FSTYPE_FAT12 :
            {
              size_t       fatsector;
              unsigned int fatoffset;
              unsigned int fatindex;
              uint8_t      value;

              /* FAT12 is more complex because it has 12-bits (1.5 bytes)
               * per FAT entry. Get the offset to the first byte:
               */

              fatoffset = (clusterno * 3) / 2;
              fatsector = fs->fs_fatbase + SEC_NSECTORS(fs, fatoffset);

              /* Make sure that the sector at this offset is in the cache */

              if (fat_fscacheread(fs, fatsector)< 0)
                {
                  /* Read error */

                  break;
                }

              /* Get the LS byte first handling the 12-bit alignment within
               * the 16-bits
               */

              fatindex = fatoffset & SEC_NDXMASK(fs);
              if ((clusterno & 1) != 0)
                {
                  /* Save the LS four bits of the next cluster */

                  value = (fs->fs_buffer[fatindex] & 0x0f) | nextcluster << 4;
                }
              else
                {
                  /* Save the LS eight bits of the next cluster */

                  value = (uint8_t)nextcluster;
                }
              fs->fs_buffer[fatindex] = value;

              /* With FAT12, the second byte of the cluster number may lie in
               * a different sector than the first byte.
               */

              fatindex++;
              if (fatindex >= fs->fs_hwsectorsize)
                {
                  /* Read the next sector */

                  fatsector++;
                  fatindex = 0;

                  /* Set the dirty flag to make sure the sector that we
                   * just modified is written out.
                   */

                  fs->fs_dirty = true;
                  if (fat_fscacheread(fs, fatsector) < 0)
                    {
                      /* Read error */
                      break;
                    }
                }

              /* Output the MS byte first handling the 12-bit alignment within
               * the 16-bits
               */

              if ((clusterno & 1) != 0)
                {
                  /* Save the MS eight bits of the next cluster */

                  value = (uint8_t)(nextcluster >> 4);
                }
              else
                {
                  /* Save the MS four bits of the next cluster */

                  value = (fs->fs_buffer[fatindex] & 0xf0) | ((nextcluster >> 8) & 0x0f);
                }
              fs->fs_buffer[fatindex] = value;
            }
          break;

          case FSTYPE_FAT16 :
            {
              unsigned int fatoffset = 2 * clusterno;
              size_t       fatsector = fs->fs_fatbase + SEC_NSECTORS(fs, fatoffset);
              unsigned int fatindex  = fatoffset & SEC_NDXMASK(fs);

              if (fat_fscacheread(fs, fatsector) < 0)
                {
                  /* Read error */
                  break;
                }
              FAT_PUTFAT16(fs->fs_buffer, fatindex, nextcluster & 0xffff);
            }
          break;

          case FSTYPE_FAT32 :
            {
              unsigned int fatoffset = 4 * clusterno;
              size_t       fatsector = fs->fs_fatbase + SEC_NSECTORS(fs, fatoffset);
              unsigned int fatindex  = fatoffset & SEC_NDXMASK(fs);

              if (fat_fscacheread(fs, fatsector) < 0)
                {
                  /* Read error */
                  break;
                }
              FAT_PUTFAT32(fs->fs_buffer, fatindex, nextcluster & 0x0fffffff);
            }
          break;

          default:
              return -EINVAL;
        }

      /* Mark the modified sector as "dirty" and return success */

      fs->fs_dirty = 1;
      return OK;
    }

  return -EINVAL;
}

/****************************************************************************
 * Name: fat_removechain
 *
 * Desciption: Remove an entire chain of clusters, starting with 'cluster'
 *
 ****************************************************************************/

int fat_removechain(struct fat_mountpt_s *fs, uint32_t cluster)
{
  int32_t nextcluster;
  int    ret;

  /* Loop while there are clusters in the chain */

  while (cluster >= 2 && cluster < fs->fs_nclusters)
    {
      /* Get the next cluster after the current one */

      nextcluster = fat_getcluster(fs, cluster);
      if (nextcluster < 0)
        {
          /* Error! */
          return nextcluster;
        }

      /* Then nullify current cluster -- removing it from the chain */

      ret = fat_putcluster(fs, cluster, 0);
      if (ret < 0)
        {
          return ret;
        }

      /* Update FSINFINFO data */

      if (fs->fs_fsifreecount != 0xffffffff)
        {
          fs->fs_fsifreecount++;
          fs->fs_fsidirty = 1;
        }

      /* Then set up to remove the next cluster */

      cluster = nextcluster;
  }

  return OK;
}

/****************************************************************************
 * Name: fat_extendchain
 *
 * Desciption: Add a new cluster to the chain following cluster (if cluster
 *   is non-NULL).  if cluster is zero, then a new chain is created.
 *
 * Return: <0:error, 0: no free cluster, >=2: new cluster number
 *
 ****************************************************************************/

int32_t fat_extendchain(struct fat_mountpt_s *fs, uint32_t cluster)
{
  ssize_t  startsector;
  uint32_t newcluster;
  uint32_t startcluster;
  int      ret;

  /* The special value 0 is used when the new chain should start */

  if (cluster == 0)
    {
      /* The FSINFO NextFree entry should be a good starting point
       * in the search for a new cluster
       */

      startcluster = fs->fs_fsinextfree;
      if (startcluster == 0 || startcluster >= fs->fs_nclusters)
        {
          /* But it is bad.. we have to start at the beginning */
          startcluster = 1;
        }
    }
  else
    {
      /* We are extending an existing chain. Verify that this
       * is a valid cluster by examining its start sector.
       */

      startsector = fat_getcluster(fs, cluster);
      if (startsector < 0)
        {
          /* An error occurred, return the error value */

          return startsector;
        }
      else if (startsector < 2)
        {

          /* Oops.. this cluster does not exist. */
          return 0;
        }
      else if (startsector < fs->fs_nclusters)
        {
          /* It is already followed by next cluster */

          return startsector;
        }

      /* Okay.. it checks out */

      startcluster = cluster;
    }

  /* Loop until (1) we discover that there are not free clusters
   * (return 0), an errors occurs (return -errno), or (3) we find
   * the next cluster (return the new cluster number).
   */

  newcluster = startcluster;
  for (;;)
    {
      /* Examine the next cluster in the FAT */

      newcluster++;
      if (newcluster >= fs->fs_nclusters)
        {
          /* If we hit the end of the available clusters, then
           * wrap back to the beginning because we might have
           * started at a non-optimal place.  But don't continue
           * past the start cluster.
           */

          newcluster = 2;
          if (newcluster > startcluster)
            {
              /* We are back past the starting cluster, then there
               * is no free cluster.
               */

              return 0;
            }
        }

      /* We have a candidate cluster.  Check if the cluster number is
       * mapped to a group of sectors.
       */

      startsector = fat_getcluster(fs, newcluster);
      if (startsector == 0)
        {
          /* Found have found a free cluster break out*/
          break;
        }
      else if (startsector < 0)
        {
          /* Some error occurred, return the error number */
          return startsector;
        }

      /* We wrap all the back to the starting cluster?  If so, then
       * there are no free clusters.
       */

      if (newcluster == startcluster)
        {
          return 0;
        }
    }

  /* We get here only if we break out with an available cluster
   * number in 'newcluster'  Now mark that cluster as in-use.
   */

  ret = fat_putcluster(fs, newcluster, 0x0fffffff);
  if (ret < 0)
    {
      /* An error occurred */ 
      return ret;
    }

  /* And link if to the start cluster (if any)*/

  if (cluster)
    {
      /* There is a start cluster -- link it */

      ret = fat_putcluster(fs, cluster, newcluster);
      if (ret < 0)
        {
          return ret;
        }
    }

  /* And update the FINSINFO for the next time we have to search */

  fs->fs_fsinextfree = newcluster;
  if (fs->fs_fsifreecount != 0xffffffff)
    {
      fs->fs_fsifreecount--;
      fs->fs_fsidirty = 1;
    }

  /* Return then number of the new cluster that was added to the chain */

  return newcluster;
}

/****************************************************************************
 * Name: fat_nextdirentry
 *
 * Desciption: Read the next directory entry from the sector in cache,
 *   reading the next sector(s) in the cluster as necessary.
 *
 ****************************************************************************/

int fat_nextdirentry(struct fat_mountpt_s *fs, struct fs_fatdir_s *dir)
{
  unsigned int cluster;
  unsigned int ndx;

  /* Increment the index to the next 32-byte directory entry */

  ndx = dir->fd_index + 1;

  /* Check if all of the directory entries in this sectory have
   * been examined.
   */

  if ((ndx & (DIRSEC_NDIRS(fs)-1)) == 0)
    {
      /* Yes, then we will have to read the next sector */

      dir->fd_currsector++;

      /* For FAT12/16, the root directory is a group of sectors relative
       * to the first sector of the fat volume.
       */

      if (!dir->fd_currcluster)
        {
          /* For FAT12/16, the boot record tells us number of 32-bit directories
           * that are contained in the root directory.  This should correspond to
           * an even number of sectors.
           */

          if (ndx >= fs->fs_rootentcnt)
            {
              /* When we index past this count, we have examined all of the entries in
               * the root directory.
               */

              return ERROR;
            }
        }
      else
        {
          /* Not a FAT12/16 root directory, check if we have examined the entire
           * cluster comprising the directory.
           *
           * The current sector within the cluster is the entry number divided
           * byte the number of entries per sector
           */

          int sector = ndx / DIRSEC_NDIRS(fs);

          /* We are finished with the cluster when the last sector of the cluster
           * has been examined.
           */

          if ((sector & (fs->fs_fatsecperclus-1)) == 0)
            {
              /* Get next cluster */

              cluster = fat_getcluster(fs, dir->fd_currcluster);

              /* Check if a valid cluster was obtained. */

              if (cluster < 2 || cluster >= fs->fs_nclusters)
                {
                  /* No, we have probably reached the end of the cluster list */
                  return ERROR;
                }

              /* Initialize for new cluster */

              dir->fd_currcluster = cluster;
              dir->fd_currsector  = fat_cluster2sector(fs, cluster);
            }
        }
    }

  /* Save the new index into dir->fd_currsector */

  dir->fd_index = ndx;
  return OK;
}

/****************************************************************************
 * Name: fat_finddirentry
 *
 * Desciption: Given a path to something that may or may not be in the file
 *   system, return the directory entry of the item.
 *
 ****************************************************************************/

int fat_finddirentry(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo,
                     const char *path)
{
  size_t cluster;
  uint8_t *direntry = NULL;
  char terminator;
  int ret;

  /* Initialize to traverse the chain.  Set it to the cluster of
   * the root directory
   */

  cluster = fs->fs_rootbase;
  if (fs->fs_type == FSTYPE_FAT32)
    {
      /* For FAT32, the root directory is variable sized and is a
       * cluster chain like any other directory.  fs_rootbase holds
       * the first cluster of the root directory.
       */

      dirinfo->dir.fd_startcluster = cluster;
      dirinfo->dir.fd_currcluster  = cluster;
      dirinfo->dir.fd_currsector   = fat_cluster2sector(fs, cluster);
    }
  else
    {
      /* For FAT12/16, the first sector of the root directory is a sector
       * relative to the first sector of the fat volume.
       */

      dirinfo->dir.fd_startcluster = 0;
      dirinfo->dir.fd_currcluster  = 0;
      dirinfo->dir.fd_currsector   = cluster;
    }

  /* fd_index is the index into the current directory table */

  dirinfo->dir.fd_index = 0;

  /* If no path was provided, then the root directory must be exactly
   * what the caller is looking for.
   */

  if (*path == '\0')
    {
      dirinfo->fd_entry = NULL;
      return OK;
    }

  /* Otherwise, loop until the path is found */

  for (;;)
    {
      /* Convert the next the path segment name into the kind of
       * name that we would see in the directory entry.
       */

      ret = fat_path2dirname(&path, dirinfo, &terminator);
      if (ret < 0)
        {
          /* ERROR:  The filename contains invalid characters or is
           * too long.
           */

          return ret;
        }

      /* Now search the current directory entry for an entry with this
       * matching name.
       */

      for (;;)
        {
          /* Read the next sector into memory */

          ret = fat_fscacheread(fs, dirinfo->dir.fd_currsector);
          if (ret < 0)
            {
              return ret;
            }

          /* Get a pointer to the directory entry */

          direntry = &fs->fs_buffer[DIRSEC_BYTENDX(fs, dirinfo->dir.fd_index)];

          /* Check if we are at the end of the directory */

          if (direntry[DIR_NAME] == DIR0_ALLEMPTY)
            {
              return -ENOENT;
            }

          /* Check if we have found the directory entry that we are looking for */

          if (direntry[DIR_NAME] != DIR0_EMPTY &&
              !(DIR_GETATTRIBUTES(direntry) & FATATTR_VOLUMEID) &&
              !memcmp(&direntry[DIR_NAME], dirinfo->fd_name, 8+3) )
            {
              /* Yes.. break out of the loop */
              break;
            }

          /* No... get the next directory index and try again */

          if (fat_nextdirentry(fs, &dirinfo->dir) != OK)
            {
              return -ENOENT;
            }
        }

      /* We get here only if we have found a directory entry that matches
       * the path element that we are looking for.
       *
       * If the terminator character in the path was the end of the string
       * then we have successfully found the directory entry that describes
       * the path.
       */

      if (!terminator)
        {
          /* Return the pointer to the matching directory entry */
          dirinfo->fd_entry = direntry;
          return OK;
        }

      /* No.. then we have found one of the intermediate directories on
       * the way to the final path target.  In this case, make sure
       * the thing that we found is, indeed, a directory.
       */

      if (!(DIR_GETATTRIBUTES(direntry) & FATATTR_DIRECTORY))
        {
          /* Ooops.. we found something else */
          return -ENOTDIR;
        }

      /* Get the cluster number of this directory */

      cluster =
          ((uint32_t)DIR_GETFSTCLUSTHI(direntry) << 16) |
          DIR_GETFSTCLUSTLO(direntry);

      /* The restart scanning at the new directory */

      dirinfo->dir.fd_currcluster = dirinfo->dir.fd_startcluster = cluster;
      dirinfo->dir.fd_currsector  = fat_cluster2sector(fs, cluster);
      dirinfo->dir.fd_index       = 2;
    }
}

/****************************************************************************
 * Name: fat_allocatedirentry
 *
 * Desciption: Find a free directory entry
 *
 ****************************************************************************/

int fat_allocatedirentry(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo)
{
  int32_t cluster;
  size_t  sector;
  uint8_t *direntry;
  uint8_t ch;
  int     ret;
  int     i;

  /* Re-initialize directory object */

  cluster = dirinfo->dir.fd_startcluster;
  if (cluster)
    {
     /* Cluster chain can be extended */

      dirinfo->dir.fd_currcluster = cluster;
      dirinfo->dir.fd_currsector  = fat_cluster2sector(fs, cluster);
    }
  else
    {
      /* Fixed size FAT12/16 root directory is at fixxed offset/size */

      dirinfo->dir.fd_currsector = fs->fs_rootbase;
    }
  dirinfo->dir.fd_index = 0;

  for (;;)
    {
      unsigned int dirindex;

      /* Read the directory sector into fs_buffer */

      ret = fat_fscacheread(fs, dirinfo->dir.fd_currsector);
      if (ret < 0)
        {
          return ret;
        }

      /* Get a pointer to the entry at fd_index */

      dirindex = (dirinfo->dir.fd_index & DIRSEC_NDXMASK(fs)) * 32;
      direntry = &fs->fs_buffer[dirindex];

      /* Check if this directory entry is empty */

      ch = direntry[DIR_NAME];
      if (ch == DIR0_ALLEMPTY || ch == DIR0_EMPTY)
        {
          /* It is empty -- we have found a directory entry */

          dirinfo->fd_entry = direntry;
          return OK;
        }

      ret = fat_nextdirentry(fs, &dirinfo->dir);
      if (ret < 0)
        {
          return ret;
        }
    }

  /* If we get here, then we have reached the end of the directory table
   * in this sector without finding a free directory enty.
   *
   * It this is a fixed size dirctory entry, then this is an error.
   * Otherwise, we can try to extend the directory cluster chain to
   * make space for the new directory entry.
   */

  if (!cluster)
    {
      /* The size is fixed */
      return -ENOSPC;
    }

  /* Try to extend the cluster chain for this directory */

  cluster = fat_extendchain(fs, dirinfo->dir.fd_currcluster);
  if (cluster < 0)
    {
      return cluster;
    }

 /* Flush out any cached date in fs_buffer.. we are going to use
  * it to initialize the new directory cluster.
  */

  ret = fat_fscacheflush(fs);
  if (ret < 0)
    {
      return ret;
    }

  /* Clear all sectors comprising the new directory cluster */

  fs->fs_currentsector = fat_cluster2sector(fs, cluster);
  memset(fs->fs_buffer, 0, fs->fs_hwsectorsize);

  sector = sector;
  for (i = fs->fs_fatsecperclus; i; i--)
    {
      ret = fat_hwwrite(fs, fs->fs_buffer, sector, 1);
      if ( ret < 0)
        {
          return ret;
        }
      sector++;
    }

  dirinfo->fd_entry = fs->fs_buffer;
  return OK;
}

/****************************************************************************
 * Name: fat_dirname2path
 *
 * Desciption:  Convert a filename in a raw directory entry into a user
 *    filename.  This is essentially the inverse operation of that performed
 *    by fat_path2dirname.  See that function for more details.
 *
 ****************************************************************************/

int fat_dirname2path(char *path, uint8_t *direntry)
{
#ifdef CONFIG_FAT_LCNAMES
    uint8_t ntflags;
#endif
    int  ch;
    int  ndx;

    /* Check if we will be doing upper to lower case conversions */

#ifdef CONFIG_FAT_LCNAMES
    ntflags = DIR_GETNTRES(direntry);
#endif

    /* Get the 8-byte filename */

    for (ndx = 0; ndx < 8; ndx++)
      {
        /* Get the next filename character from the directory entry */

        ch = direntry[ndx];

        /* Any space (or ndx==8) terminates the filename */

        if (ch == ' ')
          {
            break;
          }

        /* In this version, we never write 0xe5 in the directoryfilenames
         * (because we do not handle any character sets where 0xe5 is valid
         * in a filaname), but we could encounted this in a filesystem
         * written by some other system
         */

        if (ndx == 0 && ch == DIR0_E5)
          {
            ch = 0xe5;
          }

        /* Check if we should perform upper to lower case conversion
         * of the (whole) filename.
         */

#ifdef CONFIG_FAT_LCNAMES
        if (ntflags & FATNTRES_LCNAME && isupper(ch))
          {
            ch = tolower(ch);
          }
#endif
        /* Copy the next character into the filename */

        *path++ = ch;
      }

    /* Check if there is an extension */

    if (direntry[8] != ' ')
      {
        /* Yes, output the dot before the extension */

        *path++ = '.';

        /* Then output the (up to) 3 character extension */

        for (ndx = 8; ndx < 11; ndx++)
          {
            /* Get the next extensions character from the directory entry */

            ch = direntry[DIR_NAME + ndx];

            /* Any space (or ndx==11) terminates the extension */

            if (ch == ' ')
              {
                break;
              }

            /* Check if we should perform upper to lower case conversion
             * of the (whole) filename.
             */

#ifdef CONFIG_FAT_LCNAMES
            if (ntflags & FATNTRES_LCEXT && isupper(ch))
              {
                ch = tolower(ch);
              }
#endif
        /* Copy the next character into the filename */

            *path++ = ch;
          }
      }

    /* Put a null terminator at the end of the filename */

    *path = '\0';
    return OK;
}

/****************************************************************************
 * Name: fat_dirtruncate
 *
 * Desciption: Truncate an existing file to zero length
 *
 * Assumptions:  The caller holds mountpoint semaphore, fs_buffer holds
 *   the directory entry, dirinfo refers to the current fs_buffer content.
 *
 ****************************************************************************/

int  fat_dirtruncate(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo)
{
  unsigned int startcluster;
  uint32_t     writetime;
  size_t       savesector;
  int          ret;

  /* Get start cluster of the file to truncate */

  startcluster =
      ((uint32_t)DIR_GETFSTCLUSTHI(dirinfo->fd_entry) << 16) |
      DIR_GETFSTCLUSTLO(dirinfo->fd_entry);

  /* Clear the cluster start value in the directory and set the file size
   * to zero.  This makes the file look empty but also have to dispose of
   * all of the clusters in the chain.
   */

  DIR_PUTFSTCLUSTHI(dirinfo->fd_entry, 0);
  DIR_PUTFSTCLUSTLO(dirinfo->fd_entry, 0);
  DIR_PUTFILESIZE(dirinfo->fd_entry, 0);

  /* Set the ARCHIVE attribute and update the write time */

  DIR_PUTATTRIBUTES(dirinfo->fd_entry, FATATTR_ARCHIVE);
 
  writetime = fat_systime2fattime();
  DIR_PUTWRTTIME(dirinfo->fd_entry, writetime & 0xffff);
  DIR_PUTWRTDATE(dirinfo->fd_entry, writetime > 16);

  /* This sector needs to be written back to disk eventually */

  fs->fs_dirty = true;

  /* Now remove the entire cluster chain comprising the file */

  savesector = fs->fs_currentsector;
  ret = fat_removechain(fs, startcluster);
  if (ret < 0)
  {
    return ret;
  }

  /* Setup FSINFO to resuse this cluster next */

  fs->fs_fsinextfree = startcluster - 1;

  /* Make sure that the directory is still in the cache */

  return fat_fscacheread(fs, savesector);
}

/****************************************************************************
 * Name: fat_dircreate
 *
 * Desciption: Create a directory entry for a new file
 *
 ****************************************************************************/

int fat_dircreate(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo)
{
  uint8_t  *direntry;
  uint32_t  fattime;
  int       ret;

  /* Set up the directory entry */

  ret = fat_allocatedirentry(fs, dirinfo);
  if (ret != OK)
    {
      /* Failed to set up directory entry */
      return ret;
    }

  /* Initialize the 32-byte directory entry */

  direntry = dirinfo->fd_entry;
  memset(direntry, 0, 32);

  /* Directory name info */

  memcpy(&direntry[DIR_NAME], dirinfo->fd_name, 8+3);
#ifdef CONFIG_FLAT_LCNAMES
  DIR_PUTNTRES(dirinfo->fd_entry, dirinfo->fd_ntflags);
#else
  DIR_PUTNTRES(dirinfo->fd_entry, 0);
#endif

  /* ARCHIVE attribute, write time, creation time */
  DIR_PUTATTRIBUTES(dirinfo->fd_entry, FATATTR_ARCHIVE);
 
  fattime = fat_systime2fattime();
  DIR_PUTWRTTIME(dirinfo->fd_entry, fattime & 0xffff);
  DIR_PUTCRTIME(dirinfo->fd_entry, fattime & 0xffff);
  DIR_PUTWRTDATE(dirinfo->fd_entry, fattime >> 16);
  DIR_PUTCRDATE(dirinfo->fd_entry, fattime >> 16);

  fs->fs_dirty = true;
  return OK;
}

/****************************************************************************
 * Name: fat_remove
 *
 * Desciption: Remove a directory or file from the file system.  This
 *   implements both rmdir() and unlink().
 *
 ****************************************************************************/

int fat_remove(struct fat_mountpt_s *fs, const char *relpath, bool directory)
{
  struct fat_dirinfo_s dirinfo;
  uint32_t  dircluster;
  size_t  dirsector;
  int     ret;

  /* Find the directory entry referring to the entry to be deleted */

  ret = fat_finddirentry(fs, &dirinfo, relpath);
  if (ret != OK)
    {
      /* No such path */

      return -ENOENT;
    }

  /* Check if this is a FAT12/16 root directory */

  if (dirinfo.fd_entry == NULL)
    {
      /* The root directory cannot be removed */

      return -EPERM;
    }

  /* The object has to have write access to be deleted */

  if ((DIR_GETATTRIBUTES(dirinfo.fd_entry) & FATATTR_READONLY) != 0)
    {
      /* It is a read-only entry */

      return -EACCES;
    }

  /* Get the directory sector and cluster containing the
   * entry to be deleted
   */

  dirsector  = fs->fs_currentsector;
  dircluster =
      ((uint32_t)DIR_GETFSTCLUSTHI(dirinfo.fd_entry) << 16) |
      DIR_GETFSTCLUSTLO(dirinfo.fd_entry);

  /* Is this entry a directory? */

  if (DIR_GETATTRIBUTES(dirinfo.fd_entry) & FATATTR_DIRECTORY)
    {
      /* It is a sub-directory. Check if we are be asked to remove
       * a directory or a file.
       */

      if (!directory)
        {
          /* We are asked to delete a file */

          return -EISDIR;
        }

      /* We are asked to delete a directory. Check if this
       * sub-directory is empty
       */

      dirinfo.dir.fd_currcluster = dircluster;
      dirinfo.dir.fd_currsector  = fat_cluster2sector(fs, dircluster);
      dirinfo.dir.fd_index       = 2;

      /* Loop until either (1) an entry is found in the directory
       * (error), (2) the directory is found to be empty, or (3) some
       * error occurs.
       */

      for (;;)
        {
          unsigned int subdirindex;
          uint8_t     *subdirentry;

          /* Make sure that the sector containing the of the
           * subdirectory sector is in the cache
           */

          ret = fat_fscacheread(fs, dirinfo.dir.fd_currsector);
          if (ret < 0)
            {
              return ret;
            }

          /* Get a reference to the next entry in the directory */

          subdirindex = (dirinfo.dir.fd_index & DIRSEC_NDXMASK(fs)) * 32;
          subdirentry = &fs->fs_buffer[subdirindex];

          /* Is this the last entry in the direcory? */

          if (subdirentry[DIR_NAME] == DIR0_ALLEMPTY)
            {
              /* Yes then the directory is empty.  Break out of the
               * loop and delete the directory.
               */

              break;
            }

          /* Check if the next entry refers to a file or directory */

          if (subdirentry[DIR_NAME] != DIR0_EMPTY &&
              !(DIR_GETATTRIBUTES(subdirentry) & FATATTR_VOLUMEID))
            {
              /* The directory is not empty */

              return -ENOTEMPTY;
            }

          /* Get the next directgory entry */

          ret = fat_nextdirentry(fs, &dirinfo.dir);
          if (ret < 0)
            {
              return ret;
            }
        }
    }
  else
    {
      /* It is a file. Check if we are be asked to remove a directory
       * or a file.
       */

      if (directory)
        {
          /* We are asked to remove a directory */

          return -ENOTDIR;
        }
    }

  /* Make sure that the directory containing the entry to be deleted is
   * in the cache.
   */

  ret = fat_fscacheread(fs, dirsector);
  if (ret < 0)
    {
      return ret;
    }

  /* Mark the directory entry 'deleted' */

  dirinfo.fd_entry[DIR_NAME] = DIR0_EMPTY;
  fs->fs_dirty = true;

  /* And remove the cluster chain making up the subdirectory */

  ret = fat_removechain(fs, dircluster);
  if (ret < 0)
    {
      return ret;
    }

  /* Update the FSINFO sector (FAT32) */

  ret = fat_updatefsinfo(fs);
  if (ret < 0)
    {
      return ret;
    }

  return OK;
}

/****************************************************************************
 * Name: fat_fscacheflush
 *
 * Desciption: Flush any dirty sector if fs_buffer as necessary
 *
 ****************************************************************************/

int fat_fscacheflush(struct fat_mountpt_s *fs)
{
  int ret;

  /* Check if the fs_buffer is dirty.  In this case, we will write back the
   * contents of fs_buffer.
   */

  if (fs->fs_dirty)
  {
      /* Write the dirty sector */

      ret = fat_hwwrite(fs, fs->fs_buffer, fs->fs_currentsector, 1);
      if (ret < 0)
      {
          return ret;
      }

      /* Does the sector lie in the FAT region? */

      if (fs->fs_currentsector < fs->fs_fatbase + fs->fs_nfatsects)
      {
          /* Yes, then make the change in the FAT copy as well */
          int i;

          for (i = fs->fs_fatnumfats; i >= 2; i--)
          { 
              fs->fs_currentsector += fs->fs_nfatsects;
              ret = fat_hwwrite(fs, fs->fs_buffer, fs->fs_currentsector, 1);
              if (ret < 0)
              {
                  return ret;
              }
          }
      }

      /* No longer dirty */

      fs->fs_dirty = false;
  }
  return OK;
}

/****************************************************************************
 * Name: fat_fscacheread
 *
 * Desciption: Read the specified sector into the sector cache, flushing any
 *   existing dirty sectors as necessary.
 *
 ****************************************************************************/

int fat_fscacheread(struct fat_mountpt_s *fs, size_t sector)
{
  int ret;

  /* fs->fs_currentsector holds the current sector that is buffered in
   * fs->fs_buffer. If the requested sector is the same as this sector, then
   * we do nothing. Otherwise, we will have to read the new sector.
   */

    if (fs->fs_currentsector != sector)
      {
        /* We will need to read the new sector.  First, flush the cached
         * sector if it is dirty.
         */

        ret = fat_fscacheflush(fs);
        if (ret < 0)
          {
              return ret;
          }

        /* Then read the specified sector into the cache */

        ret = fat_hwread(fs, fs->fs_buffer, sector, 1);
        if (ret < 0)
          {
            return ret;
          }

        /* Update the cached sector number */

        fs->fs_currentsector = sector;
    }

    return OK;
}

/****************************************************************************
 * Name: fat_ffcacheflush
 *
 * Desciption: Flush any dirty sectors as necessary
 *
 ****************************************************************************/

int fat_ffcacheflush(struct fat_mountpt_s *fs, struct fat_file_s *ff)
{
  int ret;

  /* Check if the ff_buffer is dirty.  In this case, we will write back the
   * contents of ff_buffer.
   */

  if (ff->ff_cachesector &&
      ff->ff_bflags && (FFBUFF_DIRTY|FFBUFF_VALID) == (FFBUFF_DIRTY|FFBUFF_VALID))
    {
      /* Write the dirty sector */

      ret = fat_hwwrite(fs, ff->ff_buffer, ff->ff_cachesector, 1);
      if (ret < 0)
        {
          return ret;
        }

      /* No longer dirty, but still valid */

      ff->ff_bflags &= ~FFBUFF_DIRTY;
    }

  return OK;
}

/****************************************************************************
 * Name: fat_ffcacheread
 *
 * Desciption: Read the specified sector into the sector cache, flushing any
 *   existing dirty sectors as necessary.
 *
 ****************************************************************************/

int fat_ffcacheread(struct fat_mountpt_s *fs, struct fat_file_s *ff, size_t sector)
{
  int ret;

  /* ff->ff_cachesector holds the current sector that is buffered in
   * ff->ff_buffer. If the requested sector is the same as this sector, then
   * we do nothing. Otherwise, we will have to read the new sector.
   */

  if (ff->ff_cachesector != sector || (ff->ff_bflags & FFBUFF_VALID) == 0)
      {
        /* We will need to read the new sector.  First, flush the cached
         * sector if it is dirty.
         */

        ret = fat_ffcacheflush(fs, ff);
        if (ret < 0)
          {
              return ret;
          }

        /* Then read the specified sector into the cache */

        ret = fat_hwread(fs, ff->ff_buffer, sector, 1);
        if (ret < 0)
          {
            return ret;
          }

        /* Update the cached sector number */

        ff->ff_cachesector = sector;
        ff->ff_bflags |= FFBUFF_VALID;
    }
    return OK;
}

/****************************************************************************
 * Name: fat_ffcacheread
 *
 * Desciption: Invalidate the current file buffer contents
 *
 ****************************************************************************/

int fat_ffcacheinvalidate(struct fat_mountpt_s *fs, struct fat_file_s *ff)
{
  int ret;

  /* Is there anything valid in the buffer now? */

  if ((ff->ff_bflags & FFBUFF_VALID) != 0)
      {
        /* We will invalidate the buffered sector */

        ret = fat_ffcacheflush(fs, ff);
        if (ret < 0)
          {
              return ret;
          }

        /* Then discard the current cache contents */

        ff->ff_bflags     &= ~FFBUFF_VALID;
        ff->ff_cachesector = 0;
    }
    return OK;
}

/****************************************************************************
 * Name: fat_updatefsinfo
 *
 * Desciption: Flush evertyhing buffered for the mountpoint and update
 *   the FSINFO sector, if appropriate
 *
 ****************************************************************************/

int fat_updatefsinfo(struct fat_mountpt_s *fs)
{
  int ret;

  /* Flush the fs_buffer if it is dirty */

  ret = fat_fscacheflush(fs);
  if (ret == OK)
    {
      /* The FSINFO sector only has to be update for the case of a FAT32 file
       * system.  Check if the file system type.. If this is a FAT32 file
       * system then the fs_fsidirty flag will indicate if the FSINFO sector
       * needs to be re-written.
       */

      if (fs->fs_type == FSTYPE_FAT32 && fs->fs_fsidirty)
        {
          /* Create an image of the FSINFO sector in the fs_buffer */

          memset(fs->fs_buffer, 0, fs->fs_hwsectorsize);
          FSI_PUTLEADSIG(fs->fs_buffer, 0x41615252);
          FSI_PUTSTRUCTSIG(fs->fs_buffer, 0x61417272);
          FSI_PUTFREECOUNT(fs->fs_buffer, fs->fs_fsifreecount);
          FSI_PUTNXTFREE(fs->fs_buffer, fs->fs_fsinextfree);
          FSI_PUTTRAILSIG(fs->fs_buffer, BOOT_SIGNATURE32);

          /* Then flush this to disk */

          fs->fs_currentsector = fs->fs_fsinfo;
          fs->fs_dirty         = true;
          ret                  = fat_fscacheflush(fs);

          /* No longer dirty */

          fs->fs_fsidirty = false;
        }
    }
  return ret;
}

/****************************************************************************
 * Name: fat_nfreeclusters
 *
 * Desciption: Get the number of free clusters
 *
 ****************************************************************************/

int fat_nfreeclusters(struct fat_mountpt_s *fs, size_t *pfreeclusters)
{
  uint32_t nfreeclusters;

  /* If number of the first free cluster is valid, then just return that value. */

  if (fs->fs_fsifreecount <= fs->fs_nclusters - 2)
    {
      *pfreeclusters = fs->fs_fsifreecount;
      return OK;
    }

  /* Otherwise, we will have to count the number of free clusters */

  nfreeclusters = 0;
  if (fs->fs_type == FSTYPE_FAT12)
    {
      size_t sector;

      /* Examine every cluster in the fat */

      for (sector = 2; sector < fs->fs_nclusters; sector++)
        {

          /* If the cluster is unassigned, then increment the count of free clusters */

          if ((uint16_t)fat_getcluster(fs, sector) == 0)
            {
              nfreeclusters++;
            }
        }
    }
  else
    {
      unsigned int cluster;
      size_t       fatsector;
      unsigned int offset;
      int          ret;

      fatsector    = fs->fs_fatbase;
      offset       = fs->fs_hwsectorsize;

      /* Examine each cluster in the fat */

      for (cluster = fs->fs_nclusters; cluster > 0; cluster--)
        {
          /* If we are starting a new sector, then read the new sector in fs_buffer */

          if (offset >= fs->fs_hwsectorsize)
            {
              ret = fat_fscacheread(fs, fatsector++);
              if (ret < 0)
                {
                  return ret;
                }

              /* Reset the offset to the next FAT entry.
               * Increment the sector number to read next time around.
               */

              offset = 0;
              fatsector++;
            }

          /* FAT16 and FAT32 differ only on the size of each cluster start
           * sector number in the FAT.
           */

          if (fs->fs_type == FSTYPE_FAT16)
            {
              if (FAT_GETFAT16(fs->fs_buffer, offset) == 0)
                {
                  nfreeclusters++;
                }
              offset += 2;
            }
          else
            {
              if (FAT_GETFAT32(fs->fs_buffer, offset) == 0)
                {
                  nfreeclusters++;
                }

              offset += 4;
            }
        }
    }

    fs->fs_fsifreecount = nfreeclusters;
    if (fs->fs_type == FSTYPE_FAT32)
      {
        fs->fs_fsidirty = true;
      }

    *pfreeclusters = nfreeclusters;
    return OK;
}

/****************************************************************************
 * Name: fat_nfreeclusters
 *
 * Desciption:
 *   Given the file position, set the correct current sector to access.
 *
 ****************************************************************************/

int fat_currentsector(struct fat_mountpt_s *fs, struct fat_file_s *ff,
                      off_t position)
{
  int sectoroffset;

  if (position <= ff->ff_size )
    {
      /* sectoroffset is the sector number offset into the current cluster */

      sectoroffset = SEC_NSECTORS(fs, position) & CLUS_NDXMASK(fs);

      /* The current cluster is the first sector of the cluster plus
       * the sector offset
        */

      ff->ff_currentsector = fat_cluster2sector(fs, ff->ff_currentcluster)
                           + sectoroffset;

      /* The remainder is the number of sectors left in the cluster to be
       * read/written
       */

      ff->ff_sectorsincluster = fs->fs_fatsecperclus - sectoroffset;

      fvdbg("position=%d currentsector=%d sectorsincluster=%d\n",
            position, ff->ff_currentsector, ff->ff_sectorsincluster);

      return OK;
    }

  /* The position does not lie within the file */

  return -ENOSPC;
}