summaryrefslogtreecommitdiff
path: root/nuttx/drivers/mtd/smart.c
blob: b99bed493fe820858f9a543b4a9cce002bc53b66 (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
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
/****************************************************************************
 * drivers/mtd/smart.c
 *
 * Sector Mapped Allocation for Really Tiny (SMART) Flash block driver.
 *
 *   Copyright (C) 2013-2014 Ken Pettit. All rights reserved.
 *   Author: Ken Pettit <pettitkd@gmail.com>
 *
 * 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 <sys/ioctl.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <debug.h>
#include <errno.h>

#include <crc8.h>
#include <crc16.h>
#include <crc32.h>
#include <nuttx/kmalloc.h>
#include <nuttx/fs/fs.h>
#include <nuttx/fs/ioctl.h>
#include <nuttx/mtd/mtd.h>
#include <nuttx/mtd/smart.h>
#include <nuttx/fs/smart.h>

/****************************************************************************
 * Private Definitions
 ****************************************************************************/

//#define CONFIG_SMART_LOCAL_CHECKFREE

#define SMART_STATUS_COMMITTED    0x80
#define SMART_STATUS_RELEASED     0x40
#define SMART_STATUS_CRC          0x20
#define SMART_STATUS_SIZEBITS     0x1C
#define SMART_STATUS_VERBITS      0x03

#if defined(CONFIG_SMART_CRC_16)
#define SMART_STATUS_VERSION      0x02
#elif defined(CONFIG_SMART_CRC_32)
#define SMART_STATUS_VERSION      0x03
#else
#define SMART_STATUS_VERSION      0x01
#endif

#define SMART_SECTSIZE_256        0x00
#define SMART_SECTSIZE_512        0x04
#define SMART_SECTSIZE_1024       0x08
#define SMART_SECTSIZE_2048       0x0C
#define SMART_SECTSIZE_4096       0x10
#define SMART_SECTSIZE_8192       0x14
#define SMART_SECTSIZE_16384      0x18

#define SMART_FMT_STAT_UNKNOWN    0
#define SMART_FMT_STAT_FORMATTED  1
#define SMART_FMT_STAT_NOFMT      2

#define SMART_FMT_POS1            sizeof(struct smart_sect_header_s)
#define SMART_FMT_POS2            (SMART_FMT_POS1 + 1)
#define SMART_FMT_POS3            (SMART_FMT_POS1 + 2)
#define SMART_FMT_POS4            (SMART_FMT_POS1 + 3)

#define SMART_FMT_SIG1            'S'
#define SMART_FMT_SIG2            'M'
#define SMART_FMT_SIG3            'R'
#define SMART_FMT_SIG4            'T'

#define SMART_FMT_VERSION_POS     (SMART_FMT_POS1 + 4)
#define SMART_FMT_NAMESIZE_POS    (SMART_FMT_POS1 + 5)
#define SMART_FMT_ROOTDIRS_POS    (SMART_FMT_POS1 + 6)
#define SMARTFS_FMT_WEAR_POS      36
#define SMART_WEAR_LEVEL_FORMAT_SIG 32
#define SMART_PARTNAME_SIZE         4

#define SMART_FIRST_DIR_SECTOR      3       /* First root directory sector */
#define SMART_FIRST_ALLOC_SECTOR    12      /* First logical sector number we will
                                             * use for assignment of requested Alloc
                                             * sectors.  All enries below this are
                                             * reserved (some for root dir entries,
                                             * other for our use, such as format
                                             * sector, etc. */

#if defined(CONFIG_MTD_SMART_READAHEAD) || (defined(CONFIG_DRVR_WRITABLE) && \
    defined(CONFIG_MTD_SMART_WRITEBUFFER))
#  define SMART_HAVE_RWBUFFER 1
#endif

#ifndef CONFIG_MTD_SMART_SECTOR_SIZE
#  define  CONFIG_MTD_SMART_SECTOR_SIZE 1024
#endif

#ifndef offsetof
#define offsetof(type, member) ( (size_t) &( ( (type *) 0)->member))
#endif

#define SMART_MAX_ALLOCS        6
//#define CONFIG_MTD_SMART_PACK_COUNTS

#ifndef CONFIG_MTD_SMART_ALLOC_DEBUG
#define smart_malloc(d, b, n)   kmm_malloc(b)
#define smart_free(d, p)        kmm_free(p)
#endif

#define SMART_WEAR_FULL_RELOCATE_THRESHOLD  8
#define SMART_WEAR_REORG_THRESHOLD          14
#define SMART_WEAR_MIN_LEVEL                5
#define SMART_WEAR_FORCE_REORG_THRESHOLD    1
#define SMART_WEAR_BIT_DIVIDE               1
#define SMART_WEAR_ZERO_MASK                0x0F
#define SMART_WEAR_BLOCK_MASK               0x01

/* Bit mapping for wear level bits */
/* These are defined to allow updating the wear leveling with the minimum
 * number of sector relocations / maximum use of 1 --> 0 transitions when
 * incrementing the wear level.
 *
 * 0:   1111        8:  1011
 * 1:   1110        9:  1010
 * 2:   1100       10:  0010
 * 3:   1000       11:  1101
 * 4:   0111       12:  1001
 * 5:   0110       13:  0001
 * 6:   0100       14:  0011
 * 7:   0000       15:  0101
 */

static const uint8_t gWearLevelToBitMap4[] =
{
  0x0F, 0x0E, 0x0C, 0x08,     /* Single bit erased (x3) */
  0x07, 0x06, 0x04, 0x00,     /* Single bit erased (x3) */
  0x0B, 0x0A, 0x02,           /* Single bit erased (x2) */
  0x0D, 0x09, 0x01,           /* Single bit erased (x2) */
  0x03,
  0x05
};

/* Map a Wear Level bit pattern back to the wear level */

static const uint8_t gWearBitToLevelMap4[] =
{
  7, 13, 10, 14, 6, 15, 5, 4,
  3, 12, 9,  8,  2, 11, 1, 0
};

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

#ifdef CONFIG_MTD_SMART_MINIMIZE_RAM
struct smart_cache_s
{
  uint16_t              logical;          /* Logical sector number */
  uint16_t              physical;         /* Associated physical sector */
  uint16_t              birth;            /* The "birthday" of this entry */
};
#endif

/* When CRC is enabled, we allocate sectors in memory only and only write
 * to the device when an actual writesector is performed.  If during the
 * alloc process we do a physical write, we would either have to hold off on
 * writing the CRC value (which creates an invalid state on the device) or
 * we would have to perform a write, release re-write every time which would
 * increase the wear of the device 2x.
 */

#ifdef CONFIG_MTD_SMART_ENABLE_CRC
struct smart_allocsector_s
{
  struct smart_allocsector_s  *next;      /* Pointer to next alloc sector */
  uint16_t              logical;          /* Logical sector number */
  uint16_t              physical;         /* Associated physical sector */
};
#endif

struct smart_struct_s
{
  FAR struct mtd_dev_s *mtd;              /* Contained MTD interface */
  struct mtd_geometry_s geo;              /* Device geometry */

#if defined(CONFIG_FS_PROCFS) && !defined(CONFIG_FS_PROCFS_EXCLUDE_SMARTFS)
  uint32_t              unusedsectors;    /* Count of unused sectors (i.e. free when erased) */
  uint32_t              blockerases;      /* Count of unused sectors (i.e. free when erased) */
#endif
  uint16_t              neraseblocks;     /* Number of erase blocks or sub-sectors */
  uint16_t              lastallocblock;   /* Last  block we allocated a sector from */
  uint16_t              freesectors;      /* Total number of free sectors */
  uint16_t              releasesectors;   /* Total number of released sectors */
  uint16_t              mtdBlksPerSector; /* Number of MTD blocks per SMART Sector */
  uint16_t              sectorsPerBlk;    /* Number of sectors per erase block */
  uint16_t              sectorsize;       /* Sector size on device */
  uint16_t              totalsectors;     /* Total number of sectors on device */
  uint32_t              erasesize;        /* Size of an erase block */
  FAR uint8_t          *releasecount;     /* Count of released sectors per erase block */
  FAR uint8_t          *freecount;        /* Count of free sectors per erase block */
  FAR char             *rwbuffer;         /* Our sector read/write buffer */
  char                  partname[SMART_PARTNAME_SIZE]; /* Optional partition name */
  uint8_t               formatversion;    /* Format version on the device */
  uint8_t               formatstatus;     /* Indicates the status of the device format */
  uint8_t               namesize;         /* Length of filenames on this device */
  uint8_t               debuglevel;       /* Debug reporting level */
  uint8_t               availSectPerBlk;  /* Number of usable sectors per erase block */
#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
  uint8_t               rootdirentries;   /* Number of root directory entries */
  uint8_t               minor;            /* Minor number of the block entry */
#endif
#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
  uint8_t               wearflags;        /* Indicates force erase of static blocks needed */
  uint8_t               minwearlevel;     /* Min level in the wear level bits */
  uint8_t               maxwearlevel;     /* Max level in the wear level bits */
  uint8_t              *wearstatus;       /* Array of wear leveling bits */
  uint32_t              uneven_wearcount; /* Number of times the the wear level has gone over max */
#endif
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
  FAR struct smart_allocsector_s  *allocsector; /* Pointer to first alloc sector */
#endif
#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  FAR uint16_t         *sMap;             /* Virtual to physical sector map */
#else
  FAR uint8_t          *sBitMap;          /* Virtual sector used bit-map */
  FAR struct smart_cache_s *sCache;       /* Sector cache */
  uint16_t              cache_entries;    /* Number of valid entries in the cache */
  uint16_t              cache_lastlog;    /* Keep track of the last sector accessed */
  uint16_t              cache_lastphys;   /* Keep the physical sector number also */
  uint16_t              cache_nextbirth;  /* Sector cache aging value */
#endif
#ifdef CONFIG_MTD_SMART_SECTOR_ERASE_DEBUG
  FAR uint8_t          *erasecounts;      /* Number of erases for each erase block */
#endif
#ifdef CONFIG_MTD_SMART_ALLOC_DEBUG
  size_t                bytesalloc;
  struct smart_alloc_s  alloc[SMART_MAX_ALLOCS];   /* Array of memory allocations */
#endif
};

#define SMART_WEARFLAGS_FORCE_REORG    0x01
#define SMART_WEARFLAGS_WRITE_NEEDED   0x02

#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
struct smart_multiroot_device_s
{
  FAR struct smart_struct_s*    dev;
  uint8_t                       rootdirnum;
};
#endif

/* Format 1 sector header definition */

#if SMART_STATUS_VERSION == 1
#define SMART_FMT_VERSION           1
struct smart_sect_header_s
{
  uint8_t               logicalsector[2]; /* The logical sector number */
  uint8_t               seq;              /* Incrementing sequence number */
  uint8_t               crc8;             /* CRC-8 or seq number MSB */
  uint8_t               status;           /* Status of this sector:
                                           * Bit 7:   1 = Not commited
                                           *          0 = commited
                                           * Bit 6:   1 = Not released
                                           *          0 = released
                                           * Bit 5:   Sector CRC enable
                                           * Bit 4-2: Sector size on volume
                                           * Bit 1-0: Format version (0x1) */
};
typedef uint8_t crc_t;

/* Format 2 sector header definition.  This is for a 16-bit CRC */

#elif SMART_STATUS_VERSION == 2
#define SMART_FMT_VERSION           2
struct smart_sect_header_s
{
  uint8_t               logicalsector[2]; /* The logical sector number */
  uint8_t               crc16[2];         /* CRC-16 for this sector */
  uint8_t               status;           /* Status of this sector:
                                           * Bit 7:   1 = Not commited
                                           *          0 = commited
                                           * Bit 6:   1 = Not released
                                           *          0 = released
                                           * Bit 5:   Sector CRC enable
                                           * Bit 4-2: Sector size on volume
                                           * Bit 1-0: Format version (0x2) */
  uint8_t               seq;              /* Incrementing sequence number */
};
typedef uint16_t crc_t;

/* Format 3 (32-bit) sector header definition.  Actually, this format
 * isn't used yet and will likely be changed to a format to support
 * NAND devices (possibly with an 18-bit sector size, allowing up to
 * 256K sectors on a larger NAND device, though this would take a fair
 * amount of RAM for management).
 */

#elif SMART_STATUS_VERSION == 3
#error "32-Bit mode not supported yet"
#define SMART_FMT_VERSION           3
struct smart_sect_header_s
{
  uint8_t               logicalsector[4]; /* The logical sector number */
  uint8_t               crc32[4];         /* CRC-32 for this sector */
  uint8_t               status;           /* Status of this sector:
                                           * Bit 7:   1 = Not commited
                                           *          0 = commited
                                           * Bit 6:   1 = Not released
                                           *          0 = released
                                           * Bit 5:   Sector CRC enable
                                           * Bit 4-2: Sector size on volume
                                           * Bit 1-0: Format version (0x3) */
  uint8_t               seq;              /* Incrementing sequence number */
};
typedef uint32_t crc_t;

#endif


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

static int     smart_open(FAR struct inode *inode);
static int     smart_close(FAR struct inode *inode);
static ssize_t smart_reload(struct smart_struct_s *dev, FAR uint8_t *buffer,
                 off_t startblock, size_t nblocks);
static ssize_t smart_read(FAR struct inode *inode, unsigned char *buffer,
                 size_t start_sector, unsigned int nsectors);
#ifdef CONFIG_FS_WRITABLE
static ssize_t smart_write(FAR struct inode *inode, const unsigned char *buffer,
                 size_t start_sector, unsigned int nsectors);
#endif
static int     smart_geometry(FAR struct inode *inode, struct geometry *geometry);
static int     smart_ioctl(FAR struct inode *inode, int cmd, unsigned long arg);

static int smart_findfreephyssector(FAR struct smart_struct_s *dev, uint8_t canrelocate);

#ifdef CONFIG_FS_WRITABLE
static int smart_writesector(FAR struct smart_struct_s *dev, unsigned long arg);
#endif
static int smart_readsector(FAR struct smart_struct_s *dev, unsigned long arg);

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
static int smart_read_wearstatus(FAR struct smart_struct_s *dev);
static int smart_relocate_static_data(FAR struct smart_struct_s *dev, uint16_t block);
#endif

static int smart_relocate_sector(FAR struct smart_struct_s *dev,
    uint16_t oldsector, uint16_t newsector);

/****************************************************************************
 * Private Data
 ****************************************************************************/

static const struct block_operations g_bops =
{
  smart_open,     /* open     */
  smart_close,    /* close    */
  smart_read,     /* read     */
#ifdef CONFIG_FS_WRITABLE
  smart_write,    /* write    */
#else
  NULL,           /* write    */
#endif
  smart_geometry, /* geometry */
  smart_ioctl     /* ioctl    */
};

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

/****************************************************************************
 * Name: smart_open
 *
 * Description: Open the block device
 *
 ****************************************************************************/

static int smart_open(FAR struct inode *inode)
{
  fvdbg("Entry\n");
  return OK;
}

/****************************************************************************
 * Name: smart_close
 *
 * Description: close the block device
 *
 ****************************************************************************/

static int smart_close(FAR struct inode *inode)
{
  fvdbg("Entry\n");
  return OK;
}

/****************************************************************************
 * Name: smart_malloc
 *
 * Description:  Perform allocations and keep track of amount of allocated
 *               memory for this context.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_ALLOC_DEBUG
FAR static void* smart_malloc(FAR struct smart_struct_s *dev,
                    size_t bytes, const char *name)
{
  void*   ret = kmm_malloc(bytes);
  uint8_t x;

  /* Keep track of the total allocation */

  if (ret != NULL)
    {
      dev->bytesalloc += bytes;
    }

  /* Keep track of individual allocs */

  for (x = 0; x < SMART_MAX_ALLOCS; x++)
    {
      if (dev->alloc[x].ptr == NULL)
        {
          dev->alloc[x].ptr = ret;
          dev->alloc[x].size = bytes;
          dev->alloc[x].name = name;
          break;
        }
    }

  fdbg("SMART alloc: %ld\n", dev->bytesalloc);
  return ret;
}
#endif

/****************************************************************************
 * Name: smart_free
 *
 * Description:  Perform smart memory free operation.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_ALLOC_DEBUG
static void smart_free(FAR struct smart_struct_s *dev, FAR void* ptr)
{
  uint8_t x;

  for (x = 0; x < SMART_MAX_ALLOCS; x++)
    {
      if (dev->alloc[x].ptr == ptr)
        {
          dev->alloc[x].ptr = NULL;
          dev->bytesalloc -= dev->alloc[x].size;
          kmm_free(ptr);
          break;
        }
    }
}
#endif

/****************************************************************************
 * Name: smart_set_count
 *
 * Description: Set either the freecount or releasecount value for the
 *              specified eraseblock (depending on which pointer is passed).
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
static void smart_set_count(FAR struct smart_struct_s *dev, FAR uint8_t* pCount,
                            uint16_t block, uint8_t count)
{
  if (dev->sectorsPerBlk > 16)
    {
      pCount[block] = count;
    }
  else
    {
      /* Save the lower 4 bits of the count in a shared byte */

      if (block & 0x01)
        {
          pCount[block >> 1] = (pCount[block >> 1] & 0xF0) | (count & 0x0F);
        }
      else
        {
          pCount[block >> 1] = (pCount[block >> 1] & 0x0F) | ((count & 0x0F) << 4);
        }

      /* If we have 16 sectors per block, then the upper bit (representing 16)
       * all get packed into shared bytes.
       */

      if (dev->sectorsPerBlk == 16)
        {
          if (count == 16)
            {
              pCount[(dev->geo.neraseblocks >> 1) + (block>>3)] |= 1 << (block & 0x07);
            }
          else
            {
              pCount[(dev->geo.neraseblocks >> 1) + (block>>3)] &= ~(1 << (block & 0x07));
            }
        }
    }
}
#endif

/****************************************************************************
 * Name: smart_get_count
 *
 * Description: Get either the freecount or releasecount value for the
 *              specified eraseblock (depending on which pointer is passed).
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
static uint8_t smart_get_count(FAR struct smart_struct_s *dev,
                    FAR uint8_t* pCount, uint16_t block)
{
  uint8_t   count;

  if (dev->sectorsPerBlk > 16)
    {
      count = pCount[block];
    }
  else
    {
      /* Save the lower 4 bits of the count in a shared byte */

      if (block & 0x01)
        {
          count = pCount[block >> 1] & 0x0F;
        }
      else
        {
          count = pCount[block >> 1] >> 4;
        }

      /* If we have 16 sectors per block, then the upper bit (representing 16)
       * all get packed into shared bytes.
       */

      if (dev->sectorsPerBlk == 16)
        {
          if (pCount[(dev->geo.neraseblocks >> 1) + (block>>3)] & (1 << (block & 0x07)))
            {
              count |= 0x10;
            }
        }
    }

  return count;
}
#endif

/****************************************************************************
 * Name: smart_add_count
 *
 * Description: Add the specified value to and eraseblock count.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
static void smart_add_count(struct smart_struct_s *dev, uint8_t* pCount,
                            uint16_t block, int adder)
{
  int16_t   value;

  value = smart_get_count(dev, pCount, block) + adder;
  smart_set_count(dev, pCount, block, value);
}
#endif

/****************************************************************************
 * Name: smart_checkfree
 *
 * Description: A debug routine for validating the free sector count used
 *              during development of the wear leveling code.
 *
 ****************************************************************************/

#ifdef CONFIG_SMART_LOCAL_CHECKFREE
int smart_checkfree(FAR struct smart_struct_s *dev, int lineno)
{
  uint16_t        x, freecount;
#ifdef CONFIG_DEBUG_FS
  uint16_t        blockfree, blockrelease;
  static uint16_t prev_freesectors = 0;
  static uint16_t prev_releasesectors = 0;
  static uint8_t  *prev_freecount = NULL;
  static uint8_t  *prev_releasecount = NULL;
#endif

  freecount = 0;
  for (x = 0; x < dev->neraseblocks; x++)
    {
#ifdef CONFIG_MTD_SMART_PACK_COUNTS
      freecount += smart_get_count(dev, dev->freecount, x);
#else
      freecount += dev->freecount[x];
#endif
    }

  /* Test if the calculated freesectors equals the reported value */

#ifdef CONFIG_DEBUG_FS
  if (freecount != dev->freesectors)
    {
      fdbg("Free count incorrect in line %d!  Calculated=%d, dev->freesectors=%d\n",
           lineno, freecount, dev->freesectors);

      /* Determine what changed from the last time which caused this error */

      fdbg("   ... Prev freesectors=%d, prev releasesectors=%d\n",
           prev_freesectors, prev_releasesectors);

      if (prev_freecount)
        {
          for (x = 0; x < dev->neraseblocks; x++)
            {
#ifdef CONFIG_MTD_SMART_PACK_COUNTS
              blockfree = smart_get_count(dev, dev->freecount, x);
              blockrelease = smart_get_count(dev, dev->releasecount, x);
#else
              blockfree = dev->freecount[x];
              blockrelease = dev->releasecount[x];
#endif
              if (prev_freecount[x] != blockfree || prev_releasecount[x] != blockrelease)
                {
                  /* This block's values are different from the last time ... report it */

                  fdbg("   ... Block %d:  Old Free=%d, old release=%d,    New free=%d, new release = %d\n",
                      x, prev_freecount[x], prev_releasecount[x], blockfree, blockrelease);
                }
            }
        }

      /* Modifiy the freesector count to reflect the actual calculated freecount
         to get us back in line.
       */

      dev->freesectors = freecount;
      return -EIO;
    }

  /* Make a copy of the freecount and releasecount arrays to compare the
   * differences between successive calls so we can evaluate what changed
   * in the event an error is detected.
   */

  if (prev_freecount == NULL)
    {
      prev_freecount = (FAR uint8_t *) smart_malloc(dev, dev->neraseblocks << 1, "Free backup");
      prev_releasecount = prev_freecount + dev->neraseblocks;
    }

  if (prev_freecount != NULL)
    {
      for (x = 0; x < dev->neraseblocks; x++)
        {
#ifdef CONFIG_MTD_SMART_PACK_COUNTS
          prev_freecount[x] = smart_get_count(dev, dev->freecount, x);
          prev_releasecount[x] = smart_get_count(dev, dev->releasecount, x);
#else
          prev_freecount[x] = dev->freecount[x];
          prev_releasecount[x] = dev->releasecount[x];
#endif
        }
    }

  /* Save the previous freesectors count */

  prev_freesectors = dev->freesectors;
  prev_releasesectors = dev->releasesectors;
#endif

  return OK;
}
#endif

/****************************************************************************
 * Name: smart_reload
 *
 * Description:  Read the specified numer of sectors
 *
 ****************************************************************************/

static ssize_t smart_reload(struct smart_struct_s *dev, FAR uint8_t *buffer,
                            off_t startblock, size_t nblocks)
{
  ssize_t nread;
  ssize_t mtdBlocks, mtdStartBlock;

  /* Calculate the number of MTD blocks to read */

  mtdBlocks = nblocks * dev->mtdBlksPerSector;

  /* Calculate the first MTD block number */

  mtdStartBlock = startblock * dev->mtdBlksPerSector;

  /* Read the full erase block into the buffer */

  fvdbg("Read %d blocks starting at block %d\n", mtdBlocks, mtdStartBlock);
  nread = MTD_BREAD(dev->mtd, mtdStartBlock, mtdBlocks, buffer);
  if (nread != mtdBlocks)
    {
      fdbg("Read %d blocks starting at block %d failed: %d\n",
           nblocks, startblock, nread);
    }

  return nread;
}

/****************************************************************************
 * Name: smart_read
 *
 * Description:  Read the specified numer of sectors
 *
 ****************************************************************************/

static ssize_t smart_read(FAR struct inode *inode, unsigned char *buffer,
                          size_t start_sector, unsigned int nsectors)
{
  struct smart_struct_s *dev;

  fvdbg("SMART: sector: %d nsectors: %d\n", start_sector, nsectors);

  DEBUGASSERT(inode && inode->i_private);
#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
  dev = ((struct smart_multiroot_device_s*) inode->i_private)->dev;
#else
  dev = (struct smart_struct_s *)inode->i_private;
#endif
  return smart_reload(dev, buffer, start_sector, nsectors);
}

/****************************************************************************
 * Name: smart_write
 *
 * Description: Write (or buffer) the specified number of sectors
 *
 ****************************************************************************/

#ifdef CONFIG_FS_WRITABLE
static ssize_t smart_write(FAR struct inode *inode,
                FAR const unsigned char *buffer,
                size_t start_sector, unsigned int nsectors)
{
  FAR struct smart_struct_s *dev;
  off_t  alignedblock;
  off_t  mask;
  off_t  blkstowrite;
  off_t  offset;
  off_t  nextblock;
  off_t  mtdBlksPerErase;
  off_t  eraseblock;
  size_t remaining;
  size_t nxfrd;
  int    ret;
  off_t  mtdstartblock, mtdblockcount;

  fvdbg("sector: %d nsectors: %d\n", start_sector, nsectors);

  DEBUGASSERT(inode && inode->i_private);
#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
  dev = ((FAR struct smart_multiroot_device_s*) inode->i_private)->dev;
#else
  dev = (FAR struct smart_struct_s *)inode->i_private;
#endif

  /* I think maybe we need to lock on a mutex here */

  /* Get the aligned block.  Here is is assumed: (1) The number of R/W blocks
   * per erase block is a power of 2, and (2) the erase begins with that same
   * alignment.
   */

  mask         = dev->sectorsPerBlk - 1;
  alignedblock = ((start_sector + mask) & ~mask) * dev->mtdBlksPerSector;

  /* Convert SMART blocks into MTD blocks */

  mtdstartblock = start_sector * dev->mtdBlksPerSector;
  mtdblockcount = nsectors * dev->mtdBlksPerSector;
  mtdBlksPerErase = dev->mtdBlksPerSector * dev->sectorsPerBlk;

  fvdbg("mtdsector: %d mtdnsectors: %d\n", mtdstartblock, mtdblockcount);

  /* Start at first block to be written */

  remaining = mtdblockcount;
  nextblock = mtdstartblock;
  offset = 0;

  /* Loop for all blocks to be written */

  while (remaining > 0)
    {
      /* If this is an aligned block, then erase the block */

      if (alignedblock == nextblock)
        {
          /* Erase the erase block */

          eraseblock = alignedblock / mtdBlksPerErase;
          ret = MTD_ERASE(dev->mtd, eraseblock, 1);
          if (ret < 0)
            {
              fdbg("Erase block=%d failed: %d\n", eraseblock, ret);

              /* Unlock the mutex if we add one */

              return ret;
            }
        }

      /* Calculate the number of blocks to write. */

      blkstowrite = mtdBlksPerErase;
      if (nextblock != alignedblock)
        {
          blkstowrite = alignedblock - nextblock;
        }

      if (blkstowrite > remaining)
        {
          blkstowrite = remaining;
        }

      /* Try to write to the sector. */

      fdbg("Write MTD block %d from offset %d\n", nextblock, offset);
      nxfrd = MTD_BWRITE(dev->mtd, nextblock, blkstowrite, &buffer[offset]);
      if (nxfrd != blkstowrite)
        {
          /* The block is not empty!!  What to do? */

          fdbg("Write block %d failed: %d.\n", nextblock, nxfrd);

          /* Unlock the mutex if we add one */

          return -EIO;
        }

      /* Then update for amount written */

      nextblock += blkstowrite;
      remaining -= blkstowrite;
      offset += blkstowrite * dev->geo.blocksize;
      alignedblock += mtdBlksPerErase;
    }

  return nsectors;
}
#endif /* CONFIG_FS_WRITABLE */

/****************************************************************************
 * Name: smart_geometry
 *
 * Description: Return device geometry
 *
 ****************************************************************************/

static int smart_geometry(FAR struct inode *inode, struct geometry *geometry)
{
  FAR struct smart_struct_s *dev;
  uint32_t  erasesize;

  fvdbg("Entry\n");

  DEBUGASSERT(inode);
  if (geometry)
    {
#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
      dev = ((FAR struct smart_multiroot_device_s*) inode->i_private)->dev;
#else
      dev = (FAR struct smart_struct_s *)inode->i_private;
#endif
      geometry->geo_available     = true;
      geometry->geo_mediachanged  = false;
#ifdef CONFIG_FS_WRITABLE
      geometry->geo_writeenabled  = true;
#else
      geometry->geo_writeenabled  = false;
#endif

      erasesize = dev->geo.erasesize;
      if (erasesize == 0)
        {
          erasesize = 262144;
        }

      geometry->geo_nsectors      = dev->geo.neraseblocks * erasesize /
                                     dev->sectorsize;
      geometry->geo_sectorsize    = dev->sectorsize;

      fvdbg("available: true mediachanged: false writeenabled: %s\n",
            geometry->geo_writeenabled ? "true" : "false");
      fvdbg("nsectors: %d sectorsize: %d\n",
            geometry->geo_nsectors, geometry->geo_sectorsize);

      return OK;
    }

  return -EINVAL;
}

/****************************************************************************
 * Name: smart_setsectorsize
 *
 * Description: Sets the device's sector size and recalculates sector size
 *              dependant variables.
 *
 ****************************************************************************/

static int smart_setsectorsize(FAR struct smart_struct_s *dev, uint16_t size)
{
  uint32_t  erasesize;
  uint32_t  totalsectors;
  uint32_t  allocsize;

  /* Validate the size isn't zero so we don't divide by zero below */

  if (size == 0)
    {
      size = CONFIG_MTD_SMART_SECTOR_SIZE;
    }

  if (size == dev->sectorsize)
    {
      return OK;
    }

  erasesize = dev->geo.erasesize;
  dev->neraseblocks = dev->geo.neraseblocks;

  /* Most FLASH devices have erase size of 64K, but geo.erasesize is only
   * 16 bits, so it will be zero
   */

  if (erasesize == 0)
    {
      erasesize = 262144;
    }

  dev->erasesize = erasesize;
  dev->sectorsize = size;
  dev->mtdBlksPerSector = dev->sectorsize / dev->geo.blocksize;
  if (erasesize / dev->sectorsize > 256)
    {
      /* We can't throw a dbg message here becasue it is too early.
       * set the erasesize to zero and exit, then we will detect
       * it during mksmartfs or mount.
       */

      dev->erasesize = 0;
      dev->sectorsPerBlk = 256;
      dev->availSectPerBlk = 255;
    }
  else
    {
      /* Set the sectors per erase block and available sectors per erase block */

      dev->sectorsPerBlk = erasesize / dev->sectorsize;
      if (dev->sectorsPerBlk == 256)
        {
          dev->availSectPerBlk = 255;
        }
      else
        {
          dev->availSectPerBlk = dev->sectorsPerBlk;
        }
    }

#if defined(CONFIG_FS_PROCFS) && !defined(CONFIG_FS_PROCFS_EXCLUDE_SMARTFS)
  dev->unusedsectors = 0;
  dev->blockerases = 0;
#endif

  /* Release any existing rwbuffer and sMap */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  if (dev->sMap != NULL)
    {
      smart_free(dev, dev->sMap);
      dev->sMap = NULL;
    }
#else
  if (dev->sBitMap != NULL)
    {
      smart_free(dev, dev->sBitMap);
      dev->sBitMap = NULL;
    }

  dev->cache_entries = 0;
  dev->cache_lastlog = 0xFFFF;
  dev->cache_nextbirth = 0;
#endif

  if (dev->rwbuffer != NULL)
    {
      smart_free(dev, dev->rwbuffer);
      dev->rwbuffer = NULL;
    }

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
  if (dev->wearstatus != NULL)
    {
      smart_free(dev, dev->wearstatus);
      dev->wearstatus = NULL;
    }
#endif

  /* Allocate a virtual to physical sector map buffer.  Also allocate
   * the storage space for releasecount and freecounts.
   */

  totalsectors = dev->neraseblocks * dev->sectorsPerBlk;

  /* Validate the number of total sectors is small enough for a uint16_t */

  if (totalsectors > 65536)
    {
      dbg("Invalid SMART sector count %ld\n", totalsectors);
      return -EINVAL;
    }
  else if (totalsectors == 65536)
    {
      /* Special case.  We allow 65536 sectors and simply waste 2 sectors
       * to allow a smaller sector size with almost maximum flash usage.
       */

      totalsectors -= 2;
    }

  dev->totalsectors = (uint16_t) totalsectors;

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  allocsize = dev->neraseblocks << 1;
  dev->sMap = (FAR uint16_t *) smart_malloc(dev, totalsectors * sizeof(uint16_t) +
              allocsize, "Sector map");
  if (!dev->sMap)
    {
      fdbg("Error allocating SMART virtual map buffer\n");
      goto errexit;
    }

  dev->releasecount = (FAR uint8_t *) dev->sMap + (totalsectors * sizeof(uint16_t));
  dev->freecount = dev->releasecount + dev->neraseblocks;
#else
  dev->sBitMap = (FAR uint8_t *) smart_malloc(dev, (totalsectors+7) >> 3, "Sector Bitmap");
  if (dev->sBitMap == NULL)
    {
      fdbg("Error allocating SMART sector cache\n");
      goto errexit;
    }

  /* Calculate the alloc size of the freesector and release sector arrays */

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
  if (dev->sectorsPerBlk > 16)
    {
      allocsize = dev->neraseblocks << 1;
    }
  else if (dev->sectorsPerBlk == 16)
    {
      allocsize = dev->neraseblocks + (dev->neraseblocks >> 2);
    }
  else
    {
      allocsize = dev->neraseblocks;
    }

#else
  allocsize = dev->neraseblocks << 1;
#endif

  /* Allocate the sector cache */

  if (dev->sCache == NULL)
    {
      dev->sCache = (FAR struct smart_cache_s *) smart_malloc(dev,
        CONFIG_MTD_SMART_SECTOR_CACHE_SIZE * sizeof(struct smart_cache_s) +
        allocsize, "Sector Cache");
    }

  if (!dev->sCache)
    {
      fdbg("Error allocating SMART sector cache\n");
      goto errexit;
    }

  dev->releasecount = (FAR uint8_t *) dev->sCache + (CONFIG_MTD_SMART_SECTOR_CACHE_SIZE *
      sizeof(struct smart_cache_s));

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
  if (dev->sectorsPerBlk > 16)
    {
      dev->freecount = dev->releasecount + dev->neraseblocks;
    }
  else if (dev->sectorsPerBlk == 16)
    {
      dev->freecount = dev->releasecount + (dev->neraseblocks >> 1) + (dev->neraseblocks >> 3);
    }
  else
    {
      dev->freecount = dev->releasecount + (dev->neraseblocks >> 1);
    }

#else
  dev->freecount = dev->releasecount + dev->neraseblocks;
#endif

#endif  /* CONFIG_MTD_SMART_MINIMIZE_RAM */

#ifdef CONFIG_MTD_SMART_SECTOR_ERASE_DEBUG
  /* Allocate a buffer to hold the erase counts */

  if (dev->erasecounts == NULL)
    {
      dev->erasecounts = (FAR uint8_t *) smart_malloc(dev, dev->neraseblocks, "Erase counts");
    }

  if (!dev->erasecounts)
    {
      fdbg("Error allocating erase count array\n");
      goto errexit;
    }

  memset(dev->erasecounts, 0, dev->neraseblocks);
#endif

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
  /* Allocate the wear leveling status array */

  dev->wearstatus = (FAR uint8_t *) smart_malloc(dev, dev->neraseblocks >>
      SMART_WEAR_BIT_DIVIDE, "Wear status");
  if (!dev->wearstatus)
    {
      fdbg("Error allocating wear level status array\n");
      goto errexit;
    }

  memset(dev->wearstatus, CONFIG_SMARTFS_ERASEDSTATE, dev->neraseblocks >>
         SMART_WEAR_BIT_DIVIDE);
  dev->wearflags = 0;
  dev->uneven_wearcount = 0;
#endif

  /* Allocate a read/write buffer */

  dev->rwbuffer = (FAR char *) smart_malloc(dev, size, "RW Buffer");
  if (!dev->rwbuffer)
    {
      fdbg("Error allocating SMART read/write buffer\n");
      goto errexit;
    }

  return OK;

  /* On error for any allocation, we jump here and free anything that had
   * previously been allocated.
   */

errexit:

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  if (dev->sMap)
    {
      smart_free(dev, dev->sMap);
    }
#else
  if (dev->sBitMap)
    {
      smart_free(dev, dev->sBitMap);
    }

  if (dev->sCache)
    {
      smart_free(dev, dev->sCache);
    }
#endif

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
  if (dev->wearstatus)
    {
      smart_free(dev, dev->wearstatus);
    }
#endif

#ifdef CONFIG_MTD_SMART_SECTOR_ERASE_DEBUG
  if (dev->erasecounts)
    {
      smart_free(dev, dev->erasecounts);
    }
#endif

  kmm_free(dev);
  return -ENOMEM;
}

/****************************************************************************
 * Name: smart_bytewrite
 *
 * Description: Writes a non-page size count of bytes to the underlying
 *              MTD device.  If the MTD driver supports a direct impl of
 *              write, then it uses it, otherwise it does a read-modify-write
 *              and depends on the architecture of the flash to only program
 *              bits that actually changed.
 *
 ****************************************************************************/

static ssize_t smart_bytewrite(FAR struct smart_struct_s *dev, size_t offset,
        int nbytes, FAR const uint8_t *buffer)
{
  ssize_t       ret;

#ifdef CONFIG_MTD_BYTE_WRITE
  /* Check if the underlying MTD device supports write */

  if (dev->mtd->write != NULL)
    {
      /* Use the MTD's write method to write individual bytes */

      ret = dev->mtd->write(dev->mtd, offset, nbytes, buffer);
    }
  else
#endif
    {
      /* Perform block-based read-modify-write */

      uint32_t  startblock;
      uint16_t  nblocks;

      /* First calculate the start block and number of blocks affected */

      startblock = offset / dev->geo.blocksize;
      nblocks    = (offset - startblock * dev->geo.blocksize + nbytes +
                    dev->geo.blocksize-1) / dev->geo.blocksize;

      DEBUGASSERT(nblocks <= dev->mtdBlksPerSector);

      /* Do a block read */

      ret = MTD_BREAD(dev->mtd, startblock, nblocks, (FAR uint8_t *) dev->rwbuffer);
      if (ret < 0)
        {
          fdbg("Error %d reading from device\n", -ret);
          goto errout;
        }

      /* Modify the data */

      memcpy(&dev->rwbuffer[offset - startblock * dev->geo.blocksize], buffer, nbytes);

      /* Write the data back to the device */

      ret = MTD_BWRITE(dev->mtd, startblock, nblocks, (FAR uint8_t *) dev->rwbuffer);
      if (ret < 0)
        {
          fdbg("Error %d writing to device\n", -ret);
          goto errout;
        }
    }

  ret = nbytes;

errout:
  return ret;
}

/****************************************************************************
 * Name: smart_add_sector_to_cache
 *
 * Description: Adds a logical to physical sector maaping to the sector
 *              map cache.  The cache is used to minimize RAM by eliminating
 *              a one-to-one mapping of all logical sectors and only keeping
 *              a fixed number of mappings per the
 *              CONFIG_MTD_SMART_SECTOR_CACHE_SIZE parameter.  Sectors are
 *              automatically managed and removed based on the time since
 *              they were accessed last.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_MINIMIZE_RAM
static int smart_add_sector_to_cache(FAR struct smart_struct_s *dev,
            uint16_t logical, uint16_t physical, int line)
{
  uint16_t    index, x;
  uint16_t    oldest;

  /* If we aren't full yet, just add the sector to the end of the list */

  index = 1;
  if (dev->cache_entries < CONFIG_MTD_SMART_SECTOR_CACHE_SIZE)
    {
      index = dev->cache_entries++;
    }
  else
    {
      /* Cache is full.  We must find the least accessed entry and replace it */

      oldest = 0xFFFF;
      for (x = 0; x < CONFIG_MTD_SMART_SECTOR_CACHE_SIZE; x++)
        {
          /* Never replace cache entries for system sectors */

          if (dev->sCache[x].logical < SMART_FIRST_ALLOC_SECTOR)
            continue;

          /* If the hit count is zero, then choose this entry */

          if (dev->sCache[x].birth < oldest)
            {
              oldest = dev->sCache[x].birth;
              index = x;
            }
        }
    }

  /* Now add the sector at index */

  dev->sCache[index].logical = logical;
  dev->sCache[index].physical = physical;
  dev->sCache[index].birth = dev->cache_nextbirth++;
  dev->cache_lastlog = logical;
  dev->cache_lastphys = physical;
  if (dev->debuglevel > 1)
    {
      dbg("Add Cache sector:  Log=%d, Phys=%d at index %d from line %d\n",
          logical, physical, index, line);
    }

  /* Test if the birthdays need to be adjusted */

  if (oldest >= CONFIG_MTD_SMART_SECTOR_CACHE_SIZE + 1024)
    {
      for (x = 0; x < dev->cache_entries; x++)
        {
          dev->sCache[x].birth -= 1024;
        }

      dev->cache_nextbirth -= 1024;
    }

  return index;
}
#endif

/****************************************************************************
 * Name: smart_cache_lookup
 *
 * Description: Perform a cache lookup for the requested logical sector.
 *              If the sector is in the cache, then update the hitcount and
 *              return the physical mapping.  If a cache miss occurs, then
 *              the routine will scan the volume to find the logical sector
 *              and add / replace a cache entry with the newly located sector.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_MINIMIZE_RAM
static uint16_t smart_cache_lookup(FAR struct smart_struct_s *dev, uint16_t logical)
{
  int       ret;
  uint16_t  block, sector;
  uint16_t  x, physical, logicalsector;
  struct    smart_sect_header_s header;
  size_t    readaddress;

  physical = 0xFFFF;

  /* Test if searching for the last sector used */

  if (logical == dev->cache_lastlog)
    {
      return dev->cache_lastphys;
    }

  /* First search for the entry in the cache */

  for (x = 0; x < dev->cache_entries; x++)
    {
      if (dev->sCache[x].logical == logical)
        {
          /* Entry found in the cache.  Grab the physical mapping. */

          physical = dev->sCache[x].physical;
          break;
        }
    }

  /* If the entry wasn't found in the cache, then we must search the volume
   * for it and add it to the cache.
   */

  if (physical == 0xFFFF)
    {
      /* Now scan the MTD device.  Instead of scanning start to end, we
       * span the erase blocks and read one sector from each at a time.
       * this helps speed up the search on volumes that aren't full
       * because of sector allocation scheme will use the lower sector
       * numbers in each erase block first.
       */

      for (sector = 0; sector < dev->sectorsPerBlk && physical == 0xFFFF; sector++)
        {
          /* Now scan across each erase block */

          for (block = 0; block < dev->geo.neraseblocks; block++)
            {
              /* Calculate the read address for this sector */

              readaddress = block * dev->erasesize +
                  sector * CONFIG_MTD_SMART_SECTOR_SIZE;

              /* Read the header for this sector */

              ret = MTD_READ(dev->mtd, readaddress,
                  sizeof(struct smart_sect_header_s), (FAR uint8_t *) &header);
              if (ret != sizeof(struct smart_sect_header_s))
                {
                  goto err_out;
                }

              /* Get the logical sector number for this physical sector */

              logicalsector = *((FAR uint16_t *) header.logicalsector);
#if CONFIG_SMARTFS_ERASEDSTATE == 0x00
              if (logicalsector == 0)
                {
                  continue;
                }
#endif

              /* Test if this sector has been committed */

              if ((header.status & SMART_STATUS_COMMITTED) ==
                      (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_COMMITTED))
                {
                  continue;
                }

              /* Test if this sector has been release and skip it if it has */

              if ((header.status & SMART_STATUS_RELEASED) !=
                      (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_RELEASED))
                {
                  continue;
                }

              if ((header.status & SMART_STATUS_VERBITS) != SMART_STATUS_VERSION)
                {
                  continue;
                }

              /* Test if this is the sector we are looking for */

              if (logicalsector == logical)
                {
                  /* This is the sector we are looking for!  Add it to the cache */

                  physical = block * dev->sectorsPerBlk + sector;
                  smart_add_sector_to_cache(dev, logical, physical, __LINE__ );
                  break;
                }
            }
        }
    }

  /* Update the last logical sector found variable */

  dev->cache_lastlog = logical;
  dev->cache_lastphys = physical;

err_out:
  return physical;
}
#endif

/****************************************************************************
 * Name: smart_update_cache
 *
 * Description: Updates a cache entry (if present) replacing the logical
 *              sector's physical sector mapping with the new one provided.
 *              This does not affect the hit count.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_MINIMIZE_RAM
static void smart_update_cache(FAR struct smart_struct_s *dev, uint16_t
    logical, uint16_t physical)
{
  uint16_t    x;

  /* Scan through all cache entries and find the logical sector entry */

  for (x = 0; x < dev->cache_entries; x++)
    {
      if (dev->sCache[x].logical == logical)
        {
          /* Entry found.  Update it's physical mapping */

          dev->sCache[x].physical = physical;

          /* If we are freeing a sector, then remove the logical entry from
             the cache.
           */

          if (physical == 0xFFFF)
            {
                dev->sCache[x].logical = dev->sCache[dev->cache_entries-1].logical;
                dev->sCache[x].physical = dev->sCache[dev->cache_entries-1].physical;
                dev->cache_entries--;
            }

          if (dev->debuglevel > 1)
            {
              dbg("Update Cache:  Log=%d, Phys=%d at index %d\n", logical, physical, x);
            }

          break;
        }
    }

  if (dev->cache_lastlog == logical)
    {
      dev->cache_lastphys = physical;
    }
}
#endif

/****************************************************************************
 * Name: smart_get_wear_level
 *
 * Description: Gets the wear level of the specified block.  Wear levels are
 *              encoded to minimize the number of zero to one transitions,
 *              possibly allowing updates to made on NOR devices that have
 *              no CRC enabled.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
static uint8_t smart_get_wear_level(FAR struct smart_struct_s *dev, uint16_t block)
{
  uint8_t   bits;

  bits = dev->wearstatus[block >> SMART_WEAR_BIT_DIVIDE];
  if (block & 0x01)
    {
      /* Use the upper nibble */

      bits >>= 4;
    }
  else
    {
      /* Use the lower nibble */

      bits &= 0x0F;
    }

  /* Lookup and return the level using the BitToLevel map */

  return gWearBitToLevelMap4[bits];
}
#endif

/****************************************************************************
 * Name: smart_find_wear_minmax
 *
 * Description: Find the minimum and maximum wear levels.  This is used when
 *              we increment the wear level of a minimum value block so that
 *              we can detect if a new minimum exists and perform normalization
 *              of the wear-levels.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
static void smart_find_wear_minmax(FAR struct smart_struct_s *dev)
{
  uint16_t   x;
  unsigned char level;

  dev->minwearlevel = 15;
  dev->maxwearlevel = 0;

  /* Loop through all erase blocks and find min / max level */

  for (x = 0; x < dev->geo.neraseblocks; x++)
    {
      /* Find wear level of the minimum worn block */

      level = smart_get_wear_level(dev, x);
      if (level < dev->minwearlevel)
        {
          dev->minwearlevel = level;
        }

      /* Find wear level of the maximum worn block */

      if (level > dev->maxwearlevel)
        {
          dev->maxwearlevel = level;
        }
    }

#ifdef CONFIG_MTD_SMART_SECTOR_ERASE_DEBUG
  /* Also adjust the erase counts */
  level = 255;
  for (x = 0; x < dev->geo.neraseblocks; x++)
    {
      if (dev->erasecounts[x] < level)
        {
          level = dev->erasecounts[x];
        }
    }

  if (level != 0)
    {
      for (x = 0; x < dev->geo.neraseblocks; x++)
        {
          dev->erasecounts[x] -= level;
        }
    }

#endif
}
#endif

/****************************************************************************
 * Name: smart_set_wear_level
 *
 * Description: Sets the wear level of the specified block.  The wear level
 *              is a 4-bit field packed 2 entries per byte and is mapped to
 *              a bit field which minimizes the number of 0 to 1 transitions
 *              such that entries can be updated on a NOR flash withough the
 *              need to relocated the format sector (assuming CRC is not
 *              enabled, in which case a relocated is needed for ANY change).
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
static int smart_set_wear_level(FAR struct smart_struct_s *dev, uint16_t block,
                                uint8_t level)
{
  uint8_t   bits, oldlevel;

  /* Get the old wear level to test if we need to update min / max */

  oldlevel = smart_get_wear_level(dev, block);

  /* Get the bit map for this wear level from the static map array */

  if (level > 15)
    {
      dbg("Fatal Design Error!  Wear level > 15, block=%d\n", block);

      /* This is a design flaw, but we still allow processing, otherwise we
       * will corrupt the volume.  It's better to have a few blocks that are
       * worn a bit more than to create an error condition on the volume.
       *
       * Set the level to the maximum value and add to the un-even wear count
       * to keep track of the number of times this has happened.
       */

      level = 15;
      dev->uneven_wearcount++;
    }

  bits = gWearLevelToBitMap4[level];

  if (block & 0x01)
    {
      /* Use the upper nibble */

      dev->wearstatus[block >> SMART_WEAR_BIT_DIVIDE] &= 0x0F;
      dev->wearstatus[block >> SMART_WEAR_BIT_DIVIDE] |= bits << 4;
    }
  else
    {
      /* Use the lower nibble */

      dev->wearstatus[block >> SMART_WEAR_BIT_DIVIDE] &= 0xF0;
      dev->wearstatus[block >> SMART_WEAR_BIT_DIVIDE] |= bits;
    }

  /* Mark wear bits as dirty */

  dev->wearflags |= SMART_WEARFLAGS_WRITE_NEEDED;

  /* Test if min / max need to be updated */

  if (oldlevel + 1 == level)
    {
      /* Test if max needs to be updated */

      if (level > dev->maxwearlevel)
        {
          dev->maxwearlevel = level;
        }

      /* Test if this was the min level.  If it was, then
         we need to rescan for min. */

      if (oldlevel == dev->minwearlevel)
        {
          smart_find_wear_minmax(dev);

          if (oldlevel != dev->minwearlevel)
              fvdbg("##### New min wear level = %d\n", dev->minwearlevel);
        }
    }

  return 0;
}
#endif

/****************************************************************************
 * Name: smart_scan
 *
 * Description: Performs a scan of the MTD device searching for format
 *              information and fills in logical sector mapping, freesector
 *              count, etc.
 *
 ****************************************************************************/

static int smart_scan(FAR struct smart_struct_s *dev)
{
  int       sector;
  int       ret;
  uint16_t  totalsectors;
  uint16_t  sectorsize, prerelease;
  uint16_t  logicalsector;
  uint16_t  loser;
  uint32_t  readaddress;
  uint32_t  offset;
  uint16_t  seq1;
  uint16_t  seq2;
  struct    smart_sect_header_s header;
#ifdef CONFIG_MTD_SMART_MINIMIZE_RAM
  int       dupsector;
  uint16_t  duplogsector;
#endif
#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
  int       x;
  char      devname[22];
  FAR struct smart_multiroot_device_s *rootdirdev;
#endif

  fvdbg("Entry\n");

  /* Find the sector size on the volume by reading headers from
   * sectors of decreasing size.  On a formatted volume, the sector
   * size is saved in the header status byte of seach sector, so
   * by starting with the largest supported sector size and
   * decreasing from there, we will be sure to find data that is
   * a header and not sector data.
   */

  sectorsize = 0xFFFF;
  offset = 16384;

  while (sectorsize == 0xFFFF)
    {
      readaddress = 0;

      while (readaddress < dev->erasesize * dev->geo.neraseblocks)
        {
          /* Read the next sector from the device */

          ret = MTD_READ(dev->mtd, 0, sizeof(struct smart_sect_header_s),
                         (FAR uint8_t *) &header);
          if (ret != sizeof(struct smart_sect_header_s))
            {
              goto err_out;
            }

          if (header.status != CONFIG_SMARTFS_ERASEDSTATE)
            {
              sectorsize = (header.status & SMART_STATUS_SIZEBITS) << 7;
              break;
            }

          readaddress += offset;
        }

      offset >>= 1;
      if (offset < 256 && sectorsize == 0xFFFF)
        {
          sectorsize = CONFIG_MTD_SMART_SECTOR_SIZE;
        }
    }

  /* Now set the sectorsize and other sectorsize derived variables */

  ret = smart_setsectorsize(dev, sectorsize);
  if (ret != OK)
    {
      goto err_out;
    }

  /* Initialize the device variables */

  totalsectors = dev->totalsectors;
  dev->formatstatus = SMART_FMT_STAT_NOFMT;
  dev->freesectors = dev->availSectPerBlk * dev->geo.neraseblocks;
  dev->releasesectors = 0;

  /* Initialize the freecount and releasecount arrays */

  for (sector = 0; sector < dev->neraseblocks; sector++)
    {
      if (sector == dev->neraseblocks - 1 && dev->totalsectors == 65534)
        {
          prerelease = 2;
        }
      else
        {
          prerelease = 0;
        }

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
      smart_set_count(dev, dev->freecount, sector, dev->availSectPerBlk - prerelease);
      smart_set_count(dev, dev->releasecount, sector, prerelease);
#else
      dev->freecount[sector] = dev->availSectPerBlk - prerelease;
      dev->releasecount[sector] = prerelease;
#endif
    }

  /* Initialize the sector map */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  for (sector = 0; sector < totalsectors; sector++)
    {
      dev->sMap[sector] = -1;
    }
#else
  /* Clear all logical sector used bits */

  memset(dev->sBitMap, 0, (dev->totalsectors + 7) >> 3);
#endif

  /* Now scan the MTD device */

  for (sector = 0; sector < totalsectors; sector++)
    {
      fvdbg("Scan sector %d\n", sector);

      /* Calculate the read address for this sector */

      readaddress = sector * dev->mtdBlksPerSector * dev->geo.blocksize;

      /* Read the header for this sector */

      ret = MTD_READ(dev->mtd, readaddress, sizeof(struct smart_sect_header_s),
                     (FAR uint8_t *) &header);
      if (ret != sizeof(struct smart_sect_header_s))
        {
          goto err_out;
        }

      /* Get the logical sector number for this physical sector */

      logicalsector = *((FAR uint16_t *) header.logicalsector);
#if CONFIG_SMARTFS_ERASEDSTATE == 0x00
      if (logicalsector == 0)
        {
          logicalsector = -1;
        }
#endif

      /* Test if this sector has been committed */

      if ((header.status & SMART_STATUS_COMMITTED) ==
              (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_COMMITTED))
        {
          continue;
        }

      /* This block is commited, therefore not free.  Update the
       * erase block's freecount.
       */

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
      smart_add_count(dev, dev->freecount, sector / dev->sectorsPerBlk, -1);
#else
      dev->freecount[sector / dev->sectorsPerBlk]--;
#endif
      dev->freesectors--;

      /* Test if this sector has been release and if it has,
       * update the erase block's releasecount.
       */

      if ((header.status & SMART_STATUS_RELEASED) !=
              (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_RELEASED))
        {
          /* Keep track of the total number of released sectors and
           * released sectors per erase block.
           */

          dev->releasesectors++;
#ifdef CONFIG_MTD_SMART_PACK_COUNTS
          smart_add_count(dev, dev->releasecount, sector / dev->sectorsPerBlk, 1);
#else
          dev->releasecount[sector / dev->sectorsPerBlk]++;
#endif
          continue;
        }

      if ((header.status & SMART_STATUS_VERBITS) != SMART_STATUS_VERSION)
        {
          continue;
        }

      /* Validate the logical sector number is in bounds */

      if (logicalsector >= totalsectors)
        {
          /* Error in logical sector read from the MTD device */

          fdbg("Invalid logical sector %d at physical %d.\n",
               logicalsector, sector);
          continue;
        }

      /* If this is logical sector zero, then read in the signature
       * information to validate the format signature.
       */

      if (logicalsector == 0)
        {
          /* Read the sector data */

          ret = MTD_READ(dev->mtd, readaddress, 32,
                         (FAR uint8_t*) dev->rwbuffer);
          if (ret != 32)
            {
              fdbg("Error reading physical sector %d.\n", sector);
              goto err_out;
            }

          /* Validate the format signature */

          if (dev->rwbuffer[SMART_FMT_POS1] != SMART_FMT_SIG1 ||
              dev->rwbuffer[SMART_FMT_POS2] != SMART_FMT_SIG2 ||
              dev->rwbuffer[SMART_FMT_POS3] != SMART_FMT_SIG3 ||
              dev->rwbuffer[SMART_FMT_POS4] != SMART_FMT_SIG4)
           {
             /* Invalid signature on a sector claiming to be sector 0!
              * What should we do?  Release it?*/

             continue;
           }

          /* Mark the volume as formatted and set the sector size */

          dev->formatstatus = SMART_FMT_STAT_FORMATTED;
          dev->namesize = dev->rwbuffer[SMART_FMT_NAMESIZE_POS];
          dev->formatversion = dev->rwbuffer[SMART_FMT_VERSION_POS];

#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
          dev->rootdirentries = dev->rwbuffer[SMART_FMT_ROOTDIRS_POS];

          /* If rootdirentries is greater than 1, then we need to register
           * additional block devices.
           */

          for (x = 1; x < dev->rootdirentries; x++)
            {
              if (dev->partname[0] != '\0')
                {
                  snprintf(dev->rwbuffer, sizeof(devname), "/dev/smart%d%sd%d",
                          dev->minor, dev->partname, x+1);
                }
              else
                {
                  snprintf(devname, sizeof(devname), "/dev/smart%dd%d", dev->minor,
                           x + 1);
                }

              /* Inode private data is a reference to a struct containing
               * the SMART device structure and the root directory number.
               */

              rootdirdev = (struct smart_multiroot_device_s*) smart_malloc(dev,
                                sizeof(*rootdirdev), "Root Dir");
              if (rootdirdev == NULL)
                {
                  fdbg("Memory alloc failed\n");
                  ret = -ENOMEM;
                  goto err_out;
                }

              /* Populate the rootdirdev */

              rootdirdev->dev = dev;
              rootdirdev->rootdirnum = x;
              ret = register_blockdriver(dev->rwbuffer, &g_bops, 0, rootdirdev);

              /* Inode private data is a reference to the SMART device structure */

              ret = register_blockdriver(devname, &g_bops, 0, rootdirdev);
            }
#endif
        }

      /* Test for duplicate logical sectors on the device */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
      if (dev->sMap[logicalsector] != 0xFFFF)
#else
      if (dev->sBitMap[logicalsector >> 3] & (1 << (logicalsector & 0x07)))
#endif
        {
          /* Uh-oh, we found more than 1 physical sector claiming to be
           * the same logical sector.  Use the sequence number information
           * to resolve who wins.
           */


#if SMART_STATUS_VERSION == 1
          if (header.status & SMART_STATUS_CRC)
            {
              seq2 = header.seq;
            }
          else
            {
              seq2 = *((FAR uint16_t *) &header.seq);
            }
#else
          seq2 = header.seq;
#endif

          /* We must re-read the 1st physical sector to get it's seq number */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
          readaddress = dev->sMap[logicalsector]  * dev->mtdBlksPerSector * dev->geo.blocksize;
#else
          /* For minimize RAM, we have to rescan to find the 1st sector claiming to
           * be this logical sector.
           */

          for (dupsector = 0; dupsector < sector; dupsector++)
            {
              /* Calculate the read address for this sector */

              readaddress = dupsector * dev->mtdBlksPerSector * dev->geo.blocksize;

              /* Read the header for this sector */

              ret = MTD_READ(dev->mtd, readaddress, sizeof(struct smart_sect_header_s),
                             (FAR uint8_t *) &header);
              if (ret != sizeof(struct smart_sect_header_s))
                {
                  goto err_out;
                }

              /* Get the logical sector number for this physical sector */

              duplogsector = *((FAR uint16_t *) header.logicalsector);
#if CONFIG_SMARTFS_ERASEDSTATE == 0x00
              if (duplogsector == 0)
                {
                  duplogsector = -1;
                }
#endif

              /* Test if this sector has been committed */

              if ((header.status & SMART_STATUS_COMMITTED) ==
                      (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_COMMITTED))
                {
                  continue;
                }

              /* Test if this sector has been release and skip it if it has */

              if ((header.status & SMART_STATUS_RELEASED) !=
                      (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_RELEASED))
                {
                  continue;
                }

              if ((header.status & SMART_STATUS_VERBITS) != SMART_STATUS_VERSION)
                {
                  continue;
                }

              /* Now compare if this logical sector matches the current sector */

              if (duplogsector == logicalsector)
                {
                  break;
                }
            }
#endif

          ret = MTD_READ(dev->mtd, readaddress, sizeof(struct smart_sect_header_s),
                  (FAR uint8_t *) &header);
          if (ret != sizeof(struct smart_sect_header_s))
            {
              goto err_out;
            }

#if SMART_STATUS_VERSION == 1
          if (header.status & SMART_STATUS_CRC)
            {
              seq1 = header.seq;
            }
          else
            {
              seq1 = *((FAR uint16_t *) &header.seq);
            }
#else
          seq1 = header.seq;
#endif

          /* Now determine who wins */

          if ((seq1 > 0xFFF0 && seq2 < 10) || seq2 > seq1)
            {
              /* Seq 2 is the winner ... bigger or it wrapped */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
              loser = dev->sMap[logicalsector];
              dev->sMap[logicalsector] = sector;
#else
              loser = dupsector;
#endif
            }
          else
            {
              /* We keep the original mapping and seq2 is the loser */

              loser = sector;
            }

          /* Now release the loser sector */

          readaddress = loser  * dev->mtdBlksPerSector * dev->geo.blocksize;
          ret = MTD_READ(dev->mtd, readaddress, sizeof(struct smart_sect_header_s),
                  (FAR uint8_t *) &header);
          if (ret != sizeof(struct smart_sect_header_s))
            {
              goto err_out;
            }

#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
          header.status &= ~SMART_STATUS_RELEASED;
#else
          header.status |= SMART_STATUS_RELEASED;
#endif
          offset = readaddress + offsetof(struct smart_sect_header_s, status);
          ret = smart_bytewrite(dev, offset, 1, &header.status);
          if (ret < 0)
            {
              fdbg("Error %d releasing duplicate sector\n", -ret);
              goto err_out;
            }
        }

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
      /* Update the logical to physical sector map */

      dev->sMap[logicalsector] = sector;
#else
      /* Mark the logical sector as used in the bitmap */
      dev->sBitMap[logicalsector >> 3] |= 1 << (logicalsector & 0x07);

      if (logicalsector < SMART_FIRST_ALLOC_SECTOR)
        {
          smart_add_sector_to_cache(dev, logicalsector, sector, __LINE__ );
        }
#endif
    }

#if defined (CONFIG_MTD_SMART_WEAR_LEVEL) && (SMART_STATUS_VERSION == 1)
#ifdef CONFIG_MTD_SMART_CONVERT_WEAR_FORMAT

  /* We need to check if we are converting an older format with incorrect
   * wear leveling data in sector zero to the new format.  The old format
   * put all zeros in the wear level bit locations, but the new (better)
   * way is to leave them 0xFF.
   */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  sector = dev->sMap[0];
#else
  sector = smart_cache_lookup(dev, 0);
#endif

  /* Validate the sector is valid ... may be an unformatted device */

  if (sector != 0xFFFF)
    {
      /* Read the sector data */

      ret = MTD_BREAD(dev->mtd, sector * dev->mtdBlksPerSector,
              dev->mtdBlksPerSector, (uint8_t *) dev->rwbuffer);
      if (ret != dev->mtdBlksPerSector)
        {
          fdbg("Error reading physical sector %d.\n", sector);
          goto err_out;
        }


      /* Check for old format wear leveling */
      if (dev->rwbuffer[SMART_WEAR_LEVEL_FORMAT_SIG] == 0)
        {
          /* Old format detected.  We must relocate sector zero and fill it in with 0xFF */

          uint16_t newsector = smart_findfreephyssector(dev, FALSE);
          if (newsector == 0xFFFF)
            {
              /* Unable to find a free sector!!! */

              fdbg("Can't find a free sector for relocation\n");
              ret = -ENOSPC;
              goto err_out;
            }

          memset(&dev->rwbuffer[SMART_WEAR_LEVEL_FORMAT_SIG], 0xFF,
              dev->mtdBlksPerSector * dev->geo.blocksize -
              SMART_WEAR_LEVEL_FORMAT_SIG);

          smart_relocate_sector(dev, sector, newsector);

          /* Update the free and release sector counts */

          dev->freesectors--;
          dev->releasesectors++;

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
          dev->sMap[0] = newsector;
          dev->freecount[newsector / dev->sectorsPerBlk]--;
          dev->releasecount[sector / dev->sectorsPerBlk]++;
#else
          smart_update_cache(dev, 0, newsector);
          smart_add_count(dev, dev->freecount, newsector / dev->sectorsPerBlk, -1);
          smart_add_count(dev, dev->releasecount, sector / dev->sectorsPerBlk, 1);
#endif

        }
    }

#endif  /* CONFIG_MTD_SMART_CONVERT_WEAR_FORMAT */
#endif  /* CONFIG_MTD_SMART_WEAR_LEVEL && SMART_STATUS_VERSION == 1 */

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
  /* Read the wear leveling status bits */

  smart_read_wearstatus(dev);
#endif

  fdbg("SMART Scan\n");
  fdbg("   Erase size:   %10d\n", dev->sectorsPerBlk * dev->sectorsize);
  fdbg("   Erase count:  %10d\n", dev->neraseblocks);
  fdbg("   Sect/block:   %10d\n", dev->sectorsPerBlk);
  fdbg("   MTD Blk/Sect: %10d\n", dev->mtdBlksPerSector);
#ifdef CONFIG_MTD_SMART_ALLOC_DEBUG
  fdbg("   Allocations:\n");
  for (sector = 0; sector < SMART_MAX_ALLOCS; sector++)
    {
      if (dev->alloc[sector].ptr != NULL)
        {
          fdbg("       %s: %d\n", dev->alloc[sector].name, dev->alloc[sector].size);
        }
    }
#endif

  ret = OK;

err_out:
  return ret;
}

/****************************************************************************
 * Name: smart_getformat
 *
 * Description:  Populates the SMART format structure based on the format
 *               information for the inode.
 *
 ****************************************************************************/

#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
static inline int smart_getformat(FAR struct smart_struct_s *dev,
                                  FAR struct smart_format_s *fmt,
                                  uint8_t rootdirnum)
#else
static inline int smart_getformat(FAR struct smart_struct_s *dev,
                                  FAR struct smart_format_s *fmt)
#endif
{
  int ret;

  fvdbg("Entry\n");
  DEBUGASSERT(fmt);

  /* Test if we know the format status or not.  If we don't know the
   * status, then we must perform a scan of the device to search
   * for the format marker
   */

  if (dev->formatstatus != SMART_FMT_STAT_FORMATTED)
    {
      /* Perform the scan */

      ret = smart_scan(dev);

      if (ret != OK)
        {
          goto err_out;
        }
    }

  /* Now fill in the structure */

  if (dev->formatstatus == SMART_FMT_STAT_FORMATTED)
    {
      fmt->flags = SMART_FMT_ISFORMATTED;
    }
  else
    {
      fmt->flags = 0;
    }

  fmt->sectorsize = dev->sectorsize;
  fmt->availbytes = dev->sectorsize - sizeof(struct smart_sect_header_s);
  fmt->nsectors = dev->totalsectors;

  fmt->nfreesectors = dev->freesectors;
  fmt->namesize = dev->namesize;
#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
  fmt->nrootdirentries = dev->rootdirentries;
  fmt->rootdirnum = rootdirnum;
#endif

  /* Add the released sectors to the reported free sector count */

  fmt->nfreesectors += dev->releasesectors;

  /* Subtract the reserved sector count */

  fmt->nfreesectors -= dev->sectorsPerBlk + 4;

  ret = OK;

err_out:
  return ret;
}

/****************************************************************************
 * Name: smart_erase_block_if_empty
 *
 * Description:  Tests the specified erase block if it contains all free or
 *               released sectors and erases it.
 *
 ****************************************************************************/

static void smart_erase_block_if_empty(FAR struct smart_struct_s *dev,
        uint16_t block, uint8_t forceerase)
{
  uint16_t  freecount, releasecount, prerelease;

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
  releasecount = smart_get_count(dev, dev->releasecount, block);
  freecount = smart_get_count(dev, dev->freecount, block);
#else
  releasecount = dev->releasecount[block];
  freecount = dev->freecount[block];
#endif

  if ((freecount + releasecount == dev->availSectPerBlk && freecount < 1) || forceerase)
    {
      /* Erase the block */

#if defined(CONFIG_FS_PROCFS) && !defined(CONFIG_FS_PROCFS_EXCLUDE_SMARTFS)
      dev->unusedsectors += freecount;
      dev->blockerases++;
#endif
      MTD_ERASE(dev->mtd, block, 1);

#ifdef CONFIG_MTD_SMART_SECTOR_ERASE_DEBUG
      if (dev->erasecounts)
        {
          dev->erasecounts[block]++;
        }
#endif

      /* If wear leveling enabled, then we must add one to the wear status */

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
      smart_set_wear_level(dev, block, smart_get_wear_level(dev, block) + 1);
#endif

      /* If we have a device with 65534 sectors, then disallow the last two
       * physical sector if this is the last erase block on the device.
       */

      if (block == dev->geo.neraseblocks - 1 && dev->totalsectors == 65534)
        {
          prerelease = 2;
        }
      else
        {
          prerelease = 0;
        }

      dev->freesectors += dev->availSectPerBlk - prerelease - freecount;
      dev->releasesectors -= releasecount - prerelease;

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
      smart_set_count(dev, dev->releasecount, block, prerelease);
      smart_set_count(dev, dev->freecount, block, dev->availSectPerBlk-prerelease);
#else
      dev->releasecount[block] = prerelease;
      dev->freecount[block] = dev->availSectPerBlk - prerelease;
#endif  /* CONFIG_MTD_SMART_PACK_COUNTS */

      /* Now that we have erased this block and updated the release / free counts,
       * if we are in WEAR LEVELING enabled mode, we must check if this erase block's
       * wear level has reached the threshold to warrant moving a minimum wear level
       * block's data into it (i.e. relocating static data to this block so it will
       * be worn less).
       */

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
      if (!forceerase)
        {
          smart_relocate_static_data(dev, block);
        }
#endif

#ifdef CONFIG_SMART_LOCAL_CHECKFREE
      if (smart_checkfree(dev, __LINE__) != OK)
        {
          fdbg("   ...while eraseing block %d\n", block);
        }
#endif
    }
}

/****************************************************************************
 * Name: smart_relocate_static_data
 *
 * Description:  Tests if the specified block has reached the wear threshold
 *               for static data relocation and if it has, relocates a less
 *               worn block to it.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
static int smart_relocate_static_data(FAR struct smart_struct_s *dev, uint16_t block)
{
  uint16_t    freecount, x, sector, minblock;
  uint16_t    nextsector, newsector, mincount;
  int         ret;
  FAR struct  smart_sect_header_s *header;
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
  FAR struct smart_allocsector_s *allocsector;
#endif

  /* Now that we have erased this block and updated the release / free counts,
   * if we are in WEAR LEVELING enabled mode, we must check if this erase block's
   * wear level has reached the threshold to warrant moving a minimum wear level
   * block's data into it (i.e. relocating static data to this block so it will
   * be worn less).
   */

  ret = OK;
  header = (FAR struct smart_sect_header_s *) dev->rwbuffer;

#ifdef CONFIG_SMART_LOCAL_CHECKFREE
  if (smart_checkfree(dev, __LINE__) != OK)
    {
      fdbg("   ...about to relocate static data %d\n", block);
    }
#endif

  if (smart_get_wear_level(dev, block) >= SMART_WEAR_FULL_RELOCATE_THRESHOLD)
    {
      /* Okay, this block is getting too worn.  Move a minimum wear level
       * block to it in it's entirity.
       */

      /* Scan all erase blocks (or until we find a minimum wear level block
       * with no free + released blocks.
       */

      freecount = dev->sectorsPerBlk + 1;
      minblock = dev->geo.neraseblocks;
      mincount = 0;
      for (x = 0; x < dev->geo.neraseblocks; x++)
        {
          if (smart_get_wear_level(dev, x) == dev->minwearlevel)
            {
              /* Don't allow the format sector or directory sector to
               * be moved into a worn block.  First get the format and
               * dir sectors.
               */

              mincount++;

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
              if (smart_get_count(dev, dev->releasecount, x) +
                  smart_get_count(dev, dev->freecount, x) < freecount)
                {
                  freecount = smart_get_count(dev, dev->releasecount, x) +
                    smart_get_count(dev, dev->freecount, x);
                  minblock = x;
                }
#else
              if (dev->freecount[x] + dev->releasecount[x] < freecount)
                {
                  freecount = dev->freecount[x] + dev->releasecount[x];
                  minblock = x;
                }
#endif

              /* Break if freecount reaches zero */

              if (freecount == 0)
                {
                  /* We found a minimum wear-level block with no free sectors.
                   * relocate this block to the more highly worn block.
                   */

                  break;
                }
            }
        }

      /* Okay, now move block 'x' to block 'block' and erase block 'x' */

      x = minblock;

      /* We are resuing nextsector and newsector variables here simply as
       * variables for displaying debug data.  I have learned through my
       * years of programming that this is a really good way to create
       * spaghetti code, but I didn't want to add stack variables just
       * for debug data, and I *know* these variables aren't being used
       * yet.
       */

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
      nextsector = smart_get_count(dev, dev->freecount, x);
      newsector = smart_get_count(dev, dev->releasecount, x);
#else
      nextsector = dev->freecount[x];
      newsector = dev->releasecount[x];
#endif
      fvdbg("Moving block %d, wear %d, free %d, released %d to block %d, wear %d\n",
              x, smart_get_wear_level(dev, x),
              nextsector, newsector,
              block, smart_get_wear_level(dev, block));

      nextsector = block * dev->sectorsPerBlk;
      for (sector = x * dev->sectorsPerBlk; sector <
         x * dev->sectorsPerBlk + dev->availSectPerBlk; sector++)
        {
          /* Read the next sector from this erase block */

          ret = MTD_BREAD(dev->mtd, sector * dev->mtdBlksPerSector,
              dev->mtdBlksPerSector, (FAR uint8_t *) dev->rwbuffer);
          if (ret != dev->mtdBlksPerSector)
            {
              fdbg("Error reading sector %d\n", sector);
              ret = -EIO;
              goto errout;
            }

          /* Test if the block is in use */

#ifdef CONFIG_MTD_SMART_ENABLE_CRC

          /* Check if there is a temporary alloc for this physical sector */

          allocsector = dev->allocsector;
          while (allocsector)
            {
              if (allocsector->physical == sector)
                {
                  break;
                }

              allocsector = allocsector->next;
            }

          /* If we found a temp allocation, just update the mapped physical
           * location and move on to the next block ... there is no data to
           * move yet.
           */

          if (allocsector)
            {
              /* Get next sector from 'block' */

              newsector = nextsector++;
              if (newsector == 0xFFFF)
                {
                  /* Unable to find a free sector!!! */

                  fdbg("Can't find a free sector for relocation\n");
                  ret = -ENOSPC;
                  goto errout;
                }

              /* Update the temporary allocation's physical sector */

              allocsector->physical = newsector;
              *((FAR uint16_t *) header->logicalsector) = allocsector->logical;
            }
          else
#endif
            {
              if (((header->status & SMART_STATUS_COMMITTED) ==
                  (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_COMMITTED)) ||
                  ((header->status & SMART_STATUS_RELEASED) !=
                   (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_RELEASED)))
                {
                  /* This sector doesn't have live data (free or released).
                   * just continue to the next sector and don't move it.
                   */

                  continue;
                }

              /* Find a new sector where it can live, NOT in this erase block */

              newsector = nextsector++;

              /* Relocate the sector data */

              if ((ret = smart_relocate_sector(dev, sector, newsector)) < 0)
                {
                  goto errout;
                }
            }

          dev->freesectors--;

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
          dev->sMap[*((FAR uint16_t *) header->logicalsector)] = newsector;
#else
          smart_update_cache(dev, *((FAR uint16_t *) header->logicalsector), newsector);
#endif

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
          smart_add_count(dev, dev->freecount, block, -1);
#else
          dev->freecount[block]--;
#endif  /* CONFIG_MTD_SMART_PACK_COUNTS */
        }

#ifdef CONFIG_SMART_LOCAL_CHECKFREE
      if (smart_checkfree(dev, __LINE__) != OK)
        {
          fdbg("   ...about to erase static block %d\n", block);
        }
#endif

      /* Now erase the block we just relocated, force erasing it */

      smart_erase_block_if_empty(dev, x, TRUE);
    }

#ifdef CONFIG_SMART_LOCAL_CHECKFREE
  if (smart_checkfree(dev, __LINE__) != OK)
    {
      fdbg("   ...done erasing static block %d\n", block);
    }
#endif

errout:
  return ret;
}
#endif

/****************************************************************************
 * Name: smart_calc_sector_crc
 *
 * Description:  Calculate the CRC value for the sector data in the RW buffer
 *               based on the configured CRC size.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_ENABLE_CRC
static crc_t smart_calc_sector_crc(FAR struct smart_struct_s *dev)
{
  crc_t     crc = 0;

#ifdef CONFIG_SMART_CRC_8

  /* Calculate CRC on data region of the sector */

  crc = crc8((uint8_t *) &dev->rwbuffer[sizeof(struct smart_sect_header_s)],
      dev->mtdBlksPerSector * dev->geo.blocksize - sizeof(struct smart_sect_header_s));

  /* Add logical sector number and seq to the CRC calculation */

  crc = crc8part((uint8_t *) dev->rwbuffer, 3, crc);

  /* Add status to the CRC calculation */

  crc = crc8part((uint8_t *) &dev->rwbuffer[offsetof(struct smart_sect_header_s,
        status)], 1, crc);

#elif defined(CONFIG_SMART_CRC_16)
  /* Calculate CRC on data region of the sector */

  crc = crc16((uint8_t *) &dev->rwbuffer[sizeof(struct smart_sect_header_s)],
      dev->mtdBlksPerSector * dev->geo.blocksize - sizeof(struct smart_sect_header_s));

  /* Add logical sector number to the CRC calculation */

  crc = crc16part((uint8_t *) dev->rwbuffer, 2, crc);

  /* Add status and seq to the CRC calculation */

  crc = crc16part((uint8_t *) &dev->rwbuffer[offsetof(struct smart_sect_header_s,
        status)], 2, crc);

#elif defined(CONFIG_SMART_CRC_32)
  /* Calculate CRC on data region of the sector */

  crc = crc32((uint8_t *) &dev->rwbuffer[sizeof(struct smart_sect_header_s)],
      dev->mtdBlksPerSector * dev->geo.blocksize - sizeof(struct smart_sect_header_s));

  /* Add logical sector number, status and seq to the CRC calculation */

  crc = crc32part((uint8_t *) dev->rwbuffer, 6, crc);
#else
#error "Unknown CRC size!"
#endif

  return crc;
}
#endif  /* CONFIG_MTD_SMART_ENABLE_CRC  */

/****************************************************************************
 * Name: smart_llformat
 *
 * Description:  Performs a low-level format of the flash device.  This
 *               involves erasing the device and writing a valid sector
 *               zero (logical) with proper format signature.
 *
 ****************************************************************************/

#ifdef CONFIG_FS_WRITABLE
static inline int smart_llformat(FAR struct smart_struct_s *dev, unsigned long arg)
{
  FAR struct  smart_sect_header_s  *sectorheader;
  size_t      wrcount;
  int         x;
  int         ret;
  uint8_t     sectsize, prerelease;

  fvdbg("Entry\n");

  smart_setsectorsize(dev, CONFIG_MTD_SMART_SECTOR_SIZE);

  /* Check for invalid format */
  if (dev->erasesize == 0)
    {
      if (dev->geo.erasesize == 0)
        {
          dev->erasesize = 262144;
        }
      else
        {
          dev->erasesize = dev->geo.erasesize;
        }

      dbg("ERROR:  Invalid geometery ... Sectors per erase block must be 256 or less\n");
      dbg("        Erase block size    = %d\n", dev->erasesize);
      dbg("        Sector size         = %d\n", dev->sectorsize);
      dbg("        Sectors/erase block = %d\n", dev->erasesize / dev->sectorsize);

      return -EINVAL;
    }

  /* Erase the MTD device */

  ret = MTD_IOCTL(dev->mtd, MTDIOC_BULKERASE, 0);
  if (ret < 0)
    {
      return ret;
    }

  /* Now construct a logical sector zero header to write to the device. */

  sectorheader = (FAR struct smart_sect_header_s *) dev->rwbuffer;
  memset(dev->rwbuffer, CONFIG_SMARTFS_ERASEDSTATE, dev->sectorsize);
#if SMART_STATUS_VERSION == 1
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
  /* CRC enabled.  Using an 8-bit sequence number */

  sectorheader->seq = 0;
#else
  /* CRC not enabled.  Using a 16-bit sequence number */

  *((FAR uint16_t *) &sectorheader->seq) = 0;
#endif
#else   /* SMART_STATUS_VERSION == 1 */
  sectorheader->seq = 0;
#endif  /* SMART_STATUS_VERSION == 1 */

  /* Set the sector size of this sector */

  sectsize = (CONFIG_MTD_SMART_SECTOR_SIZE >> 9) << 2;

  /* Set the sector logical sector to zero and setup the header status */

#if ( CONFIG_SMARTFS_ERASEDSTATE == 0xFF )
  *((FAR uint16_t *) sectorheader->logicalsector) = 0;
  sectorheader->status = (uint8_t) ~(SMART_STATUS_COMMITTED | SMART_STATUS_VERBITS |
          SMART_STATUS_SIZEBITS) | SMART_STATUS_VERSION |
          sectsize;
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
  sectorheader->status &= ~SMART_STATUS_CRC;
#endif  /* CONFIG_MTD_SMART_ENABLE_CRC */

#else   /* CONFIG_SMARTFS_ERASEDSTATE == 0xFF */
  *((FAR uint16_t *) sectorheader->logicalsector) = 0xFFFF;
  sectorheader->status = (uint8_t) (SMART_STATUS_COMMITTED | SMART_STATUS_VERSION |
          sectsize);
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
  sectorheader->status |= SMART_STATUS_CRC;
#endif  /* CONFIG_MTD_SMART_ENABLE_CRC */
#endif  /* CONFIG_SMARTFS_ERASEDSTATE == 0xFF */

  /* Now add the format signature to the sector */

  dev->rwbuffer[SMART_FMT_POS1] = SMART_FMT_SIG1;
  dev->rwbuffer[SMART_FMT_POS2] = SMART_FMT_SIG2;
  dev->rwbuffer[SMART_FMT_POS3] = SMART_FMT_SIG3;
  dev->rwbuffer[SMART_FMT_POS4] = SMART_FMT_SIG4;

  dev->rwbuffer[SMART_FMT_VERSION_POS] = SMART_FMT_VERSION;
  dev->rwbuffer[SMART_FMT_NAMESIZE_POS] = CONFIG_SMARTFS_MAXNAMLEN;

  /* Record the number of root directory entries we have */

  dev->rwbuffer[SMART_FMT_ROOTDIRS_POS] = (uint8_t) arg;

#ifdef CONFIG_SMART_CRC_8
  sectorheader->crc8 = smart_calc_sector_crc(dev);
#elif defined(CONFIG_SMART_CRC_16)
  *((uint16_t *) sectorheader->crc16) = smart_calc_sector_crc(dev);
#elif defined(CONFIG_SMART_CRC_32)
  *((uint32_t *) sectorheader->crc32) = smart_calc_sector_crc(dev);
#endif

  /* Write the sector to the flash */

  wrcount = MTD_BWRITE(dev->mtd, 0, dev->mtdBlksPerSector,
          (FAR uint8_t *) dev->rwbuffer);
  if (wrcount != dev->mtdBlksPerSector)
    {
      /* The block is not empty!!  What to do? */

      fdbg("Write block 0 failed: %d.\n", wrcount);

      /* Unlock the mutex if we add one */

      return -EIO;
    }

  /* Now initialize our internal control variables */

  ret = smart_setsectorsize(dev, CONFIG_MTD_SMART_SECTOR_SIZE);
  if (ret != OK)
    {
      return ret;
    }

  dev->formatstatus = SMART_FMT_STAT_UNKNOWN;
  dev->freesectors = dev->availSectPerBlk * dev->geo.neraseblocks - 1;
  dev->releasesectors = 0;
#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
  dev->uneven_wearcount = 0;
#endif

  /* Initialize the released and free counts */

  for (x = 0; x < dev->neraseblocks; x++)
    {
      /* Test for a geometry with 65536 sectors.  We allow this, though
         we never use the last two sectors in this mode.
       */

      if (x == dev->neraseblocks && dev->totalsectors == 65534)
        {
          prerelease = 2;
        }
      else
        {
          prerelease = 0;
        }
#ifdef CONFIG_MTD_SMART_PACK_COUNTS
      smart_set_count(dev, dev->releasecount, x, prerelease);
      smart_set_count(dev, dev->freecount, x, dev->availSectPerBlk-prerelease);
#else
      dev->releasecount[x] = prerelease;
      dev->freecount[x] = dev->availSectPerBlk-prerelease;
#endif
    }

  /* Account for the format sector */

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
  smart_set_count(dev, dev->freecount, 0, dev->availSectPerBlk - 1);
#else
  dev->freecount[0]--;
#endif

  /* Now initialize the logical to physical sector map */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  dev->sMap[0] = 0;     /* Logical sector zero = physical sector 0 */
  for (x = 1; x < dev->totalsectors; x++)
    {
      /* Mark all other logical sectors as non-existant */

      dev->sMap[x] = -1;
    }
#endif

#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS

  /* Un-register any extra directory device entries */

  for (x = 2; x < 8; x++)
    {
      snprintf(dev->rwbuffer, 18, "/dev/smart%dd%d", dev->minor, x);
      unregister_blockdriver(dev->rwbuffer);
    }
#endif

  return OK;
}
#endif /* CONFIG_FS_WRITABLE */

/****************************************************************************
 * Name: smart_relocate_sector
 *
 * Description:  Relocates the specified sector to the new sector location.
 *
 ****************************************************************************/

static int smart_relocate_sector(FAR struct smart_struct_s *dev,
    uint16_t oldsector, uint16_t newsector)
{
  int         ret;
  size_t      offset;
  FAR struct  smart_sect_header_s *header;
  uint8_t     newstatus;

  header = (FAR struct smart_sect_header_s *) dev->rwbuffer;

  /* Increment the sequence number and clear the "commit" flag */

#if SMART_STATUS_VERSION == 1
  if (header->status & SMART_STATUS_CRC)
    {
#endif
      /* Using 8-bit sequence */

      header->seq++;
      if (header->seq == 0xFF)
        {
          header->seq = 1;
        }
#if SMART_STATUS_VERSION == 1
    }
  else
    {
      /* Using 16-bit sequence and no CRC */

      (*((FAR uint16_t *) &header->seq))++;
      if (*((FAR uint16_t *) &header->seq) == 0xFFFF)
        {
          *((FAR uint16_t *) &header->seq) = 1;
        }
    }
#endif

  /* When CRC is enabled, we must pre-commit the sector and also
   * calculate an updated CRC for the sector prior to writing
   * since we changed the sequence number.
   */

#ifdef CONFIG_MTD_SMART_ENABLE_CRC

  /* First pre-commit the sector */

#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
  header->status &= ~(SMART_STATUS_COMMITTED | SMART_STATUS_CRC);
#else
  header->status |= SMART_STATUS_COMMITTED | SMART_STATUS_CRC;
#endif

  /* Now calculate the new CRC */

#ifdef CONFIG_SMART_CRC_8
  header->crc8 = smart_calc_sector_crc(dev);
#elif defined(CONFIG_SMART_CRC_16)
  *((uint16_t *) header->crc16) = smart_calc_sector_crc(dev);
#elif defined(CONFIG_SMART_CRC_32)
  *((uint32_t *) header->crc32) = smart_calc_sector_crc(dev);
#endif

  /* Write the data to the new physical sector location */

  ret = MTD_BWRITE(dev->mtd, newsector * dev->mtdBlksPerSector,
                   dev->mtdBlksPerSector, (FAR uint8_t *) dev->rwbuffer);

#else   /* CONFIG_MTD_SMART_ENABLE_CRC */

#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
  header->status |= SMART_STATUS_COMMITTED;
#else
  header->status &= ~SMART_STATUS_COMMITTED;
#endif

  /* Write the data to the new physical sector location */

  ret = MTD_BWRITE(dev->mtd, newsector * dev->mtdBlksPerSector,
                   dev->mtdBlksPerSector, (FAR uint8_t *) dev->rwbuffer);

  /* Commit the sector */

  offset = newsector * dev->mtdBlksPerSector * dev->geo.blocksize +
      offsetof(struct smart_sect_header_s, status);
#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
  newstatus = header->status & ~SMART_STATUS_COMMITTED;
#else
  newstatus = header->status | SMART_STATUS_COMMITTED;
#endif
  ret = smart_bytewrite(dev, offset, 1, &newstatus);
  if (ret < 0)
    {
      fdbg("Error %d committing new sector %d\n" -ret, newsector);
      goto errout;
    }
#endif  /* CONFIG_MTD_SMART_ENABLE_CRC */

  /* Release the old physical sector */

#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
  newstatus = header->status & ~(SMART_STATUS_RELEASED | SMART_STATUS_COMMITTED);
#else
  newstatus = header->status | SMART_STATUS_RELEASED | SMART_STATUS_COMMITTED;
#endif
  offset = oldsector * dev->mtdBlksPerSector * dev->geo.blocksize +
      offsetof(struct smart_sect_header_s, status);
  ret = smart_bytewrite(dev, offset, 1, &newstatus);
  if (ret < 0)
    {
      fdbg("Error %d releasing old sector %d\n" -ret, oldsector);
    }

#ifndef CONFIG_MTD_SMART_ENABLE_CRC
errout:
#endif

  return ret;
}

/****************************************************************************
 * Name: smart_relocate_block
 *
 * Description:  Relocates the specified MTD erase block by moving any
 *               active sectors to a different erase block and then erases
 *               the selected block.
 *
 ****************************************************************************/

static int smart_relocate_block(FAR struct smart_struct_s *dev, uint16_t block)
{
  uint16_t    newsector, oldrelease;
  int         x;
  int         ret;
  FAR struct  smart_sect_header_s *header;
  uint8_t     prerelease;
  uint16_t    freecount;
#if defined(CONFIG_SMART_LOCAL_CHECKFREE) && defined(CONFIG_DEBUG_FS)
  uint16_t    releasecount;
#endif
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
  FAR struct smart_allocsector_s *allocsector;
#endif

  /* Perform collection on block with the most released sectors.
   * First mark the block as having no free sectors so we don't
   * try to move sectors into the block we are trying to erase.
   */

  header = (FAR struct smart_sect_header_s *) dev->rwbuffer;

#ifdef CONFIG_SMART_LOCAL_CHECKFREE
  if (smart_checkfree(dev, __LINE__) != OK)
    {
      fdbg("   ...while relocating block %d, free=%d\n", block, dev->freesectors);
    }
#endif

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
  freecount = smart_get_count(dev, dev->freecount, block);

#if defined(CONFIG_FS_PROCFS) && !defined(CONFIG_FS_PROCFS_EXCLUDE_SMARTFS)
#if defined(CONFIG_SMART_LOCAL_CHECKFREE) && defined(CONFIG_DEBUG_FS)
  releasecount = smart_get_count(dev, dev->releasecount, block);
#endif
#endif

  /* Ensure we aren't relocating a block containing the only free sectors */

  if (freecount >= dev->freesectors)
    {
      fdbg("Program bug!  Relocating the only block (%d) with free sectors!\n", block);
      ret = -EIO;
      goto errout;
    }

  smart_set_count(dev, dev->freecount, block, 0);

#else /* CONFIG_MTD_SMART_PACK_COUNTS */

  freecount = dev->freecount[block];
#if defined(CONFIG_FS_PROCFS) && !defined(CONFIG_FS_PROCFS_EXCLUDE_SMARTFS)
#if defined(CONFIG_SMART_LOCAL_CHECKFREE) && defined(CONFIG_DEBUG_FS)
  releasecount = dev->releasecount[block];
#endif
#endif
  dev->freecount[block] = 0;
#endif

  /* Next move all live data in the block to a new home. */

  for (x = block * dev->sectorsPerBlk; x <
     block * dev->sectorsPerBlk + dev->availSectPerBlk; x++)
    {
      /* Read the next sector from this erase block */

      ret = MTD_BREAD(dev->mtd, x * dev->mtdBlksPerSector,
          dev->mtdBlksPerSector, (FAR uint8_t *) dev->rwbuffer);
      if (ret != dev->mtdBlksPerSector)
        {
          fdbg("Error reading sector %d\n", x);
          ret = -EIO;
          goto errout;
        }

      /* Test if the block is in use */

#ifdef CONFIG_MTD_SMART_ENABLE_CRC

      /* Check if there is a temporary alloc for this physical sector */

      allocsector = dev->allocsector;
      while (allocsector)
        {
          if (allocsector->physical == x)
            break;
          allocsector = allocsector->next;
        }

      /* If we found a temp allocation, just update the mapped physical
       * location and move on to the next block ... there is no data to
       * move yet.
       */

      if (allocsector)
        {
          newsector = smart_findfreephyssector(dev, FALSE);
          if (newsector == 0xFFFF)
            {
              /* Unable to find a free sector!!! */

              fdbg("Can't find a free sector for relocation\n");
              ret = -ENOSPC;
              goto errout;
            }

          /* Update the temporary allocation's physical sector */

          allocsector->physical = newsector;
          *((FAR uint16_t *) header->logicalsector) = allocsector->logical;
        }
      else
#endif
        {
          if (((header->status & SMART_STATUS_COMMITTED) ==
              (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_COMMITTED)) ||
              ((header->status & SMART_STATUS_RELEASED) !=
               (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_RELEASED)))
            {
              /* This sector doesn't have live data (free or released).
               * just continue to the next sector and don't move it.
               */

              continue;
            }

          /* Find a new sector where it can live, NOT in this erase block */

          newsector = smart_findfreephyssector(dev, FALSE);
          if (newsector == 0xFFFF)
            {
              /* Unable to find a free sector!!! */

              fdbg("Can't find a free sector for relocation\n");
              ret = -ENOSPC;
              goto errout;
            }

          /* Relocate the sector data */

          if ((ret = smart_relocate_sector(dev, x, newsector)) < 0)
            goto errout;
        }

      /* Update the variables */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
      dev->sMap[*((FAR uint16_t *) header->logicalsector)] = newsector;
#else
      smart_update_cache(dev, *((FAR uint16_t *) header->logicalsector), newsector);
#endif

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
      smart_add_count(dev, dev->freecount, newsector / dev->sectorsPerBlk, -1);
#else
      dev->freecount[newsector / dev->sectorsPerBlk]--;
#endif
    }

  /* Now erase the erase block */

  MTD_ERASE(dev->mtd, block, 1);
#if defined(CONFIG_FS_PROCFS) && !defined(CONFIG_FS_PROCFS_EXCLUDE_SMARTFS)
  dev->unusedsectors += freecount;
  dev->blockerases++;
#endif

#ifdef CONFIG_MTD_SMART_SECTOR_ERASE_DEBUG
  if (dev->erasecounts)
    {
      dev->erasecounts[block]++;
    }
#endif

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL

  /* Update the new wear level count */

  smart_set_wear_level(dev, block, smart_get_wear_level(dev, block) + 1);
#endif

  /* Update the free and release sectors for this erase block. */

  if (x == dev->neraseblocks && dev->totalsectors == 65534)
    {
      /* We can't use the last two sectors on a 65536 sector device,
         so "pre-release" them so they never get allocated.
       */

      prerelease = 2;
    }
  else
    {
      prerelease = 0;
    }

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
  oldrelease = smart_get_count(dev, dev->releasecount, block);
  dev->freesectors += oldrelease-prerelease;
  dev->releasesectors -= oldrelease-prerelease;
  smart_set_count(dev, dev->freecount, block, dev->availSectPerBlk-prerelease);
  smart_set_count(dev, dev->releasecount, block, prerelease);
#else
  oldrelease = dev->releasecount[block];
  dev->freesectors += oldrelease-prerelease;
  dev->releasesectors -= oldrelease-prerelease;
  dev->freecount[block] = dev->availSectPerBlk-prerelease;
  dev->releasecount[block] = prerelease;
#endif

#ifdef CONFIG_SMART_LOCAL_CHECKFREE
  if (smart_checkfree(dev, __LINE__) != OK)
    {
      fdbg("   ...while relocating block %d, free=%d, release=%d, oldrelease=%d\n", block, freecount, releasecount, oldrelease);
    }
#endif

  /* Test if this erase causes the block to reach the full relocate
   * threshold requiring static data relocation.
   */

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
  smart_relocate_static_data(dev, block);
#endif

  return OK;

errout:
  /* Restore the block's freecount if error */

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
  smart_set_count(dev, dev->freecount, block, freecount);
#else
  dev->freecount[block] = freecount;
#endif
  return ret;
}

/****************************************************************************
 * Name: smart_findfreephyssector
 *
 * Description:  Finds a free physical sector based on free and released
 *               count logic, taking into account reserved sectors.
 *
 ****************************************************************************/

static int smart_findfreephyssector(FAR struct smart_struct_s *dev,
    uint8_t canrelocate)
{
  uint16_t  count, allocfreecount, allocblock;
#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
  uint16_t  wornfreecount, wornblock;
  uint8_t   wearlevel, wornlevel;
  uint8_t   maxwearlevel;
#endif
  uint16_t  physicalsector;
  uint16_t  x, block;
  uint32_t  readaddr;
  struct    smart_sect_header_s header;
  int       ret;

  /* Determine which erase block we should allocate the new
   * sector from. This is based on the number of free sectors
   * available in each erase block. */

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
retry:
#endif
  allocfreecount = 0;
  allocblock = 0xFFFF;
#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
  wornfreecount = 0;
  wornblock = 0xFFFF;
  wornlevel = 15;
  maxwearlevel = 0;
#endif
  physicalsector = 0xFFFF;
  if (++dev->lastallocblock >= dev->neraseblocks)
    {
      dev->lastallocblock = 0;
    }

  block = dev->lastallocblock;
  for (x = 0; x < dev->neraseblocks; x++)
    {
      /* Test if this block has more free blocks than the
       * currently selected block
       */

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
      count = smart_get_count(dev, dev->freecount, block);
#else
      count = dev->freecount[block];
#endif

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
      /* Keep track of the block with the max free sectors that is worn */

      wearlevel = smart_get_wear_level(dev, block);
      if (wearlevel >= SMART_WEAR_FULL_RELOCATE_THRESHOLD)
        {
          if (wearlevel > maxwearlevel && count > 0)
            {
              maxwearlevel = wearlevel;
            }

          if (count > wornfreecount || (count > 0 && wearlevel < wornlevel))
            {
              /* Keep track of this block.  If there are only worn blocks with
               * free sectors left, then we will use it.
               */

              if (x < dev->neraseblocks - 1 || !wornfreecount)
                {
                  wornfreecount = count;
                  wornblock = block;
                  wornlevel = wearlevel;
                }
            }
        }
      else
#endif

      if (count > allocfreecount)
        {
          /* Assign this block to alloc from */

          if (x < dev->neraseblocks - 1 || !allocfreecount)
            {
              allocblock = block;
              allocfreecount = count;
            }
        }
      if (++block >= dev->neraseblocks)
        block = 0;
    }

  /* Check if we found an allocblock. */

  if (allocblock == 0xFFFF)
    {
      /* No un-worn blocks with free sectors */

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL

      /* If we are allowed to relocate unworn blocks then do so now */

      if (canrelocate && wornfreecount < (dev->sectorsPerBlk >> 2) && wornlevel == maxwearlevel)
        {
          /* Relocate up to 8 unworn blocks */

          block = 0;
          for (x = 0; x < 8; )
            {
              if (smart_get_wear_level(dev, block) < SMART_WEAR_FORCE_REORG_THRESHOLD)
                {
                  if (smart_relocate_block(dev, block) < 0)
                    {
                      fdbg("Error relocating block while finding free phys sector\n");
                      return -1;
                    }

                  x++;
                }

              block++;
            }
          if (x > 0)
            {
              /* Disable relocate for retry */

              canrelocate = FALSE;
              goto retry;
            }
        }
      else
        {
          dev->wearflags |= SMART_WEARFLAGS_FORCE_REORG;
        }

      /* Test if we found a worn block with free sectors */

      if (wornblock != 0xFFFF)
        {
          allocblock = wornblock;
        }
      else
#endif

      {
        dbg("Program bug!  Expected a free sector, free=%d\n", dev->freesectors);
        for (x = 0; x < dev->neraseblocks; x++)
          {
            printf("%d ", dev->freecount[x]);
          }

        /* No free sectors found!  Bug? */

        return -1;
      }
    }

  /* Now find a free physical sector within this selected
   * erase block to allocate. */

  for (x = allocblock * dev->sectorsPerBlk;
       x < allocblock * dev->sectorsPerBlk + dev->availSectPerBlk; x++)
    {
      /* Check if this physical sector is available. */

#ifdef CONFIG_MTD_SMART_ENABLE_CRC
      /* First check if there is a temporary alloc in place */

      FAR struct smart_allocsector_s* allocsect;
      allocsect = dev->allocsector;

      while (allocsect)
        {
          if (allocsect->physical == x)
            break;
          allocsect = allocsect->next;
        }

      /* If we found this physical sector above, then continue on
       * to the next physical sector in this block ... this one has
       * a temporary allocation assigned.
       */

      if (allocsect)
        {
          continue;
        }
#endif

      /* Now check on the physical media */

      readaddr = x * dev->mtdBlksPerSector * dev->geo.blocksize;
      ret = MTD_READ(dev->mtd, readaddr, sizeof(struct smart_sect_header_s),
              (FAR uint8_t *) &header);
      if (ret != sizeof(struct smart_sect_header_s))
        {
          fdbg("Error reading phys sector %d\n", physicalsector);
          return -1;
        }

      if ((*((FAR uint16_t *) header.logicalsector) == 0xFFFF) &&
#if SMART_STATUS_VERSION == 1
          (*((FAR uint16_t *) &header.seq) == 0xFFFF) &&
#else
          (header.seq == CONFIG_SMARTFS_ERASEDSTATE) &&
#endif
          ((header.status & SMART_STATUS_COMMITTED) ==
           (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_COMMITTED)))
        {
          physicalsector = x;
          dev->lastallocblock = allocblock;
          break;
        }
    }

  if (physicalsector == 0xFFFF)
    {
      dbg("Program bug!  Expected a free sector\n");
    }

  if (physicalsector >= dev->totalsectors)
    {
      dbg("Program bug!  Selected sector too big!!!\n");
    }

  return physicalsector;
}

/****************************************************************************
 * Name: smart_garbagecollect
 *
 * Description:  Performs garbage collection if needed.  This is determined
 *               by the count of released sectors relative to free and
 *               total sectors.
 *
 ****************************************************************************/

#ifdef CONFIG_FS_WRITABLE
static int smart_garbagecollect(FAR struct smart_struct_s *dev)
{
  uint16_t  collectblock;
  uint16_t  releasemax;
  bool      collect = TRUE;
  int       x;
  int       ret;
#ifdef CONFIG_MTD_SMART_PACK_COUNTS
  uint8_t   count;
#endif

  while (collect)
    {
      collect = FALSE;

      /* Test if the released sectors count is greater than the
       * free sectors.  If it is, then we will do garbage collection.
       */

      if (dev->releasesectors > dev->freesectors && dev->freesectors <
          (dev->totalsectors >> 5))
        {
          collect = TRUE;
        }

      /* Test if we have more reached our reserved free sector limit */

      if (dev->freesectors <= (dev->sectorsPerBlk << 0) + 4)
        {
          collect = TRUE;
        }

      /* Test if we need to garbage collect */

      if (collect)
        {
          /* Find the block with the most released sectors */

          collectblock = 0xFFFF;
          releasemax = 0;
          for (x = 0; x < dev->neraseblocks; x++)
            {
#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
              /* Don't collect blocks that have been worn completely */

              if (smart_get_wear_level(dev, x) >= SMART_WEAR_REORG_THRESHOLD)
                {
                  continue;
                }
#endif

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
              count = smart_get_count(dev, dev->releasecount, x);
              if (count > releasemax)
                {
                  releasemax = count;
                  collectblock = x;
                }
#else
              if (dev->releasecount[x] > releasemax)
                {
                  releasemax = dev->releasecount[x];
                  collectblock = x;
                }
#endif
          }
          //releasemax = smart_get_count(dev, dev->releasecount, collectblock);

          if (collectblock == 0xFFFF)
            {
              /* Need to collect, but no sectors with released blocks! */

              ret = -ENOSPC;
              goto errout;
            }

#ifdef CONFIG_SMART_LOCAL_CHECKFREE
          if (smart_checkfree(dev, __LINE__) != OK)
            {
              fdbg("   ...before collecting block %d\n", collectblock);
            }
#endif

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
          fvdbg("Collecting block %d, free=%d released=%d, totalfree=%d, totalrelease=%d\n",
              collectblock, smart_get_count(dev, dev->freecount, collectblock),
              smart_get_count(dev, dev->releasecount, collectblock), dev->freesectors, dev->releasesectors);
#else
          fvdbg("Collecting block %d, free=%d released=%d\n",
              collectblock, dev->freecount[collectblock],
              dev->releasecount[collectblock]);
#endif

          /* Relocate the active data in the collection block */

          ret = smart_relocate_block(dev, collectblock);

#ifdef CONFIG_SMART_LOCAL_CHECKFREE
          if (smart_checkfree(dev, __LINE__) != OK)
            {
              fdbg("   ...while collecting block %d\n", collectblock);
            }
#endif

          if (ret != OK)
            {
              goto errout;
            }
        }
    }

  return OK;

errout:
  return ret;
}
#endif /* CONFIG_FS_WRITABLE */

/****************************************************************************
 * Name: smart_write_wearstatus
 *
 * Description:  Writes the wear leveling status bits to sector zero (and
 *               possibly others if it doesn't fit) such that is is persisted
 *               across OS reboots.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
static int smart_write_wearstatus(struct smart_struct_s *dev)
{
  uint16_t  sector;
  uint16_t  remaining, towrite;
  struct smart_read_write_s req;
  int       ret;
  uint8_t   buffer[8], write_buffer = 0;

  sector = 0;
  remaining = dev->geo.neraseblocks >> 1;
  memset(buffer, 0xFF, sizeof(buffer));

#if defined(CONFIG_FS_PROCFS) && !defined(CONFIG_FS_PROCFS_EXCLUDE_SMARTFS)
  if (dev->blockerases > 0)
    {
      *((uint32_t *) buffer) = dev->blockerases;
      write_buffer = 1;
    }
#endif

  /* Write the uneven wear count just prior to the wear bits */

  if (dev->uneven_wearcount != 0)
    {
      *((uint32_t *) &buffer[4]) = dev->uneven_wearcount;
      write_buffer = 1;
    }

  /* Test if we need to write either total block erase count or
     uneven wearcount (or both)
   */

  if (write_buffer)
    {
      req.logsector = sector;
      req.offset = SMARTFS_FMT_WEAR_POS - 8;
      req.count = sizeof(buffer);
      req.buffer = buffer;
      ret = smart_writesector(dev, (unsigned long) &req);
      if (ret != OK)
        {
          goto errout;
        }
    }

  /* Write all wear level bits to logical sector zero, one, two */

  while (remaining)
    {
      /* Calculate the number of bytes to write to this sector */

      towrite = remaining;
      if (towrite > dev->sectorsize - SMARTFS_FMT_WEAR_POS)
        {
          towrite = dev->sectorsize - SMARTFS_FMT_WEAR_POS;
        }

      /* Setup the sector write request (we are our own client) */

      req.logsector = sector;
      req.offset = SMARTFS_FMT_WEAR_POS;
      req.count = towrite;
      req.buffer = &dev->wearstatus[(dev->geo.neraseblocks >> SMART_WEAR_BIT_DIVIDE) -
                    remaining];

      /* Write the sector */

      ret = smart_writesector(dev, (unsigned long) &req);
      if (ret != OK)
        {
          goto errout;
        }

      /* Decrement the remaining count */

      remaining -= towrite;
      if (remaining)
        {
          /* Data doesn't fit in a single sector.  Use the reserved sectors */

          sector++;
          if (sector >= SMART_FIRST_DIR_SECTOR)
            {
              /* Error, wear status bit too large! */
              fdbg("Invalid geometry - wear level status too large\n");
              ret = -EINVAL;
              goto errout;
            }
        }
    }

  /* Now clear the NEEDS_WRITE wear status bit */

  dev->wearflags &= ~SMART_WEARFLAGS_WRITE_NEEDED;
  ret = OK;

errout:
  return ret;
}
#endif

/****************************************************************************
 * Name: smart_read_wearstatus
 *
 * Description:  Reads the wear leveling status bits from sector zero (and
 *               possibly others if it doesn't fit) such that is is persisted
 *               across OS reboots.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
static inline int smart_read_wearstatus(FAR struct smart_struct_s *dev)
{
  uint16_t  sector;
  uint16_t  remaining, toread;
  struct smart_read_write_s req;
  int       ret;
  uint8_t   buffer[8];

  /* Prepare to read the total block erases and uneven wearcount values */

  sector = 0;
  req.logsector = sector;
  req.offset = SMARTFS_FMT_WEAR_POS - 8;
  req.count = sizeof(buffer);
  req.buffer = buffer;
  ret = smart_readsector(dev, (unsigned long) &req);
  if (ret != sizeof(buffer))
    {
      goto errout;
    }

  /* Get the uneven wearcount value */

  dev->uneven_wearcount = *((uint32_t *) &buffer[4]);

  /* Check for erased state */

#if ( CONFIG_SMARTFS_ERASEDSTATE == 0xFF )
  if (dev->uneven_wearcount == 0xFFFFFFFF)
    {
      dev->uneven_wearcount = 0;
    }
#endif

#if defined(CONFIG_FS_PROCFS) && !defined(CONFIG_FS_PROCFS_EXCLUDE_SMARTFS)
  /* Get the block erases count */

  dev->blockerases = *((uint32_t *) buffer);
#if ( CONFIG_SMARTFS_ERASEDSTATE == 0xFF )
  if (dev->blockerases == 0xFFFFFFFF)
    {
      dev->blockerases = 0;
    }
#endif
#endif

  /* Read all wear level bits from the flash */

  remaining = dev->geo.neraseblocks >> 1;
  while (remaining)
    {
      /* Calculate number of bytes to read from this sector */

      toread = remaining;
      if (toread > dev->sectorsize - SMARTFS_FMT_WEAR_POS)
        {
          toread = dev->sectorsize - SMARTFS_FMT_WEAR_POS;
        }

      /* Setup the sector read request (we are our own client) */

      req.logsector = sector;
      req.offset = SMARTFS_FMT_WEAR_POS;
      req.count = toread;
      req.buffer = &dev->wearstatus[(dev->geo.neraseblocks >> SMART_WEAR_BIT_DIVIDE) -
                    remaining];

      /* Read the sector */

      ret = smart_readsector(dev, (unsigned long) &req);
      if (ret != toread)
        {
          goto errout;
        }

      /* Decrement the remaining count */

      remaining -= toread;
      if (remaining)
        {
          /* Data doesn't fit in a single sector.  Use the reserved sectors */

          sector++;
          if (sector >= SMART_FIRST_DIR_SECTOR)
            {
              /* Error, wear status bit too large! */

              fdbg("Invalid geometry - wear level status too large\n");
              ret = -EINVAL;
              goto errout;
            }
        }
    }

  /* Now interrogate the status bits */

  smart_find_wear_minmax(dev);

#ifdef CONFIG_MTD_SMART_SECTOR_ERASE_DEBUG
  /* Set the erase counts equal to the wear levels */

  for (sector = 0; sector < dev->geo.neraseblocks; sector++)
    {
      dev->erasecounts[sector] = smart_get_wear_level(dev, sector);
    }
#endif

  ret = OK;

errout:
  return ret;
}
#endif

/****************************************************************************
 * Name: smart_write_alloc_sector
 *
 * Description:  Writes a newly allocated sector's header to the RW buffer
 *               and updates sector mapping variables.  If CRC isn't enabled
 *               it also writes the header to the device.
 *
 ****************************************************************************/

#ifdef CONFIG_FS_WRITABLE
static int smart_write_alloc_sector(FAR struct smart_struct_s *dev,
                    uint16_t logical, uint16_t physical)
{
  int       ret = 1;
  uint8_t   sectsize;
  FAR struct smart_sect_header_s  *header;

  memset(dev->rwbuffer, CONFIG_SMARTFS_ERASEDSTATE, dev->sectorsize);
  header = (FAR struct smart_sect_header_s *) dev->rwbuffer;
  *((FAR uint16_t *) header->logicalsector) = logical;
#if SMART_STATUS_VERSION == 1
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
  header->seq = 0;
#else
  *((FAR uint16_t *) &header->crc8) = 0;
#endif  /* CONFIG_MTD_SMART_ENABLE_CRC */
#else
  header->seq = 0;
#endif
  sectsize = dev->sectorsize >> 7;

#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
  header->status = ~(SMART_STATUS_COMMITTED | SMART_STATUS_SIZEBITS |
          SMART_STATUS_VERBITS) | SMART_STATUS_VERSION | sectsize;
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
  header->status &= ~SMART_STATUS_CRC;
#endif  /* CONFIG_MTD_SMART_ENABLE_CRC */
#else
  header->status = SMART_STATUS_COMMITTED | SMART_STATUS_VERSION | sectsize;
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
  header->status |= SMART_STATUS_CRC;
#endif  /* CONFIG_MTD_SMART_ENABLE_CRC */
#endif

  /* Write the header to the physical sector location */

#ifndef CONFIG_MTD_SMART_ENABLE_CRC
  fvdbg("Write MTD block %d\n", physical * dev->mtdBlksPerSector);
  ret = MTD_BWRITE(dev->mtd, physical * dev->mtdBlksPerSector, 1,
      (FAR uint8_t *) dev->rwbuffer);
  if (ret != 1)
    {
      /* The block is not empty!!  What to do? */

      fdbg("Write block %d failed: %d.\n", physical *
          dev->mtdBlksPerSector, ret);

      /* Unlock the mutex if we add one */

      return -EIO;
    }
#endif  /* CONFIG_MTD_SMART_ENABLE_CRC */

  return ret;
}
#endif

/****************************************************************************
 * Name: smart_validate_crc
 *
 * Description:  Validates the CRC data in the sector's header against the
 *               data in the sector.  Assumes the entire sector has been
 *               read into the RW buffer already.
 *
 ****************************************************************************/

#ifdef CONFIG_MTD_SMART_ENABLE_CRC
static int smart_validate_crc(FAR struct smart_struct_s *dev)
{
  crc_t       crc;
  FAR struct  smart_sect_header_s *header;

  /* Calculate CRC on data region of the sector */

  crc = smart_calc_sector_crc(dev);
  header = (FAR struct smart_sect_header_s *) dev->rwbuffer;

#ifdef CONFIG_SMART_CRC_8

  /* Test 8-bit CRC */

  if (crc != header->crc8)
    {
      return -EIO;
    }

#elif defined(CONFIG_SMART_CRC_16)

  /* Test 16-bit CRC */

  if (crc != *((uint16_t *) header->crc16))
    {
      return -EIO;
    }

#elif defined(CONFIG_SMART_CRC_32)

  if (crc != *((uint32_t *) header->crc32))
    {
      return -EIO;
    }

#endif

  /* CRC checkout out okay */

  return OK;
}
#endif

/****************************************************************************
 * Name: smart_writesector
 *
 * Description:  Writes data to the specified logical sector.  The sector
 *               should have already been allocated prior to the write.  If
 *               the logical sector already has data on the device, it will
 *               be released and a new physical sector will be created and
 *               mapped to the logical sector.
 *
 ****************************************************************************/

#ifdef CONFIG_FS_WRITABLE
static int smart_writesector(FAR struct smart_struct_s *dev,
                    unsigned long arg)
{
  int         ret;
  bool        needsrelocate = FALSE;
  uint32_t    mtdblock;
  uint16_t    physsector, oldphyssector, block;
  FAR struct  smart_read_write_s *req;
  FAR struct  smart_sect_header_s *header;
  size_t      offset;
  uint8_t     byte;
#if defined(CONFIG_MTD_SMART_WEAR_LEVEL) || !defined(CONFIG_MTD_SMART_ENABLE_CRC)
  uint16_t    x;
#endif
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
  FAR struct  smart_allocsector_s *allocsector;
#endif

  fvdbg("Entry\n");
  req = (FAR struct smart_read_write_s *) arg;
  DEBUGASSERT(req->offset <= dev->sectorsize);
  DEBUGASSERT(req->offset+req->count <= dev->sectorsize);

  /* Ensure the logical sector has been allocated */

  if (req->logsector >= dev->totalsectors)
    {
      fdbg("Logical sector %d too large\n", req->logsector);

      ret = -EINVAL;
      goto errout;
    }
  header = (FAR struct smart_sect_header_s *) dev->rwbuffer;

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
  /* Test if an adjustement to the wear levels is needed */

  if (dev->minwearlevel >= SMART_WEAR_MIN_LEVEL ||
      (dev->minwearlevel > 0 && dev->maxwearlevel >= SMART_WEAR_REORG_THRESHOLD))
    {
      /* Subtract dev->minwearlevel from all wear levels */

      offset = dev->minwearlevel;
      fvdbg("Reducing wear level bits by %d\n", offset);
      for (x = 0; x < dev->geo.neraseblocks; x++)
        {
          smart_set_wear_level(dev, x, smart_get_wear_level(dev, x) - offset);
        }

      dev->minwearlevel -= offset;
      dev->maxwearlevel -= offset;

      /* Now write the new wear bits to the flash */

      dev->wearflags &= ~SMART_WEARFLAGS_FORCE_REORG;
      dev->wearflags |= SMART_WEARFLAGS_WRITE_NEEDED;
  }
#endif

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  physsector = dev->sMap[req->logsector];
#else
  physsector = smart_cache_lookup(dev, req->logsector);
#endif
  if (physsector == 0xFFFF)
    {
      fdbg("Logical sector %d not allocated\n", req->logsector);
      ret = -EINVAL;
      goto errout;
    }

  /* Read the sector data into our buffer */

  mtdblock = physsector * dev->mtdBlksPerSector;
  ret = MTD_BREAD(dev->mtd, mtdblock, dev->mtdBlksPerSector, (FAR uint8_t *)
          dev->rwbuffer);
  if (ret != dev->mtdBlksPerSector)
    {
      fdbg("Error reading phys sector %d\n", physsector);
      ret = -EIO;
      goto errout;
    }

  /* Test if we need to relocate the sector to perform the write */

#ifdef CONFIG_MTD_SMART_ENABLE_CRC
  allocsector = dev->allocsector;
  while (allocsector)
    {
      /* Test if the requested logical sector is a temp alloc */

      if (allocsector->logical == req->logsector)
        {
          break;
        }

      allocsector = allocsector->next;
    }

  /* When CRC is enabled, then we always have to relocate the sector if
   * it is not a temporary alloc (i.e. initial alloc before the very first
   * write operation).
   */

  if (!allocsector)
    {
      needsrelocate = TRUE;
    }

#else
  /* When CRC is not enabled, we may be able to simply add the new data to
   * the sector if it doesn't conflict with existing data on the device.
   * Test if there is a conflict in the data.
   */

  for (x = 0; x < req->count; x++)
    {
      /* Test if the next byte can be written to the flash */

      byte = dev->rwbuffer[sizeof(struct smart_sect_header_s) + req->offset + x];
#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
      if (((byte ^ req->buffer[x]) | byte) != byte)
        {
          needsrelocate = TRUE;
          break;
        }
#else
      if (((byte ^ req->buffer[x]) | req->buffer[x]) != req->buffer[x])
        {
          needsrelocate = TRUE;
          break;
        }
#endif
    }
#endif  /* CONFIG_MTD_SMART_ENABLE_CRC */

  /* If we are not using CRC and on a device that supports re-writing
     bits from 1 to 0 without neededing a block erase, such as NOR
     FLASH, then we can simply update the data in place and don't need
     to relocate the sector.  Test if we need to relocate or not.
   */

  if (needsrelocate)
    {
      /* Find a new physical sector to save data to */

      oldphyssector = physsector;
      physsector = smart_findfreephyssector(dev, FALSE);
      if (physsector == 0xFFFF)
        {
          fdbg("Error relocating sector %d\n", req->logsector);
          ret = -EIO;
          goto errout;
        }

      /* Update the sequence number to indicate the sector was moved */

#if SMART_STATUS_VERSION == 1
      if (header->status & SMART_STATUS_CRC)
        {
#endif
          header->seq++;
          if (header->seq == 0xFF)
            {
              header->seq = 0;
            }
#if SMART_STATUS_VERSION == 1
        }
      else
        {
          (*((FAR uint16_t *) &header->seq))++;
          if (*((FAR uint16_t *) &header->seq) == 0xFFFF)
            *((FAR uint16_t *) &header->seq) = 1;
        }
#else
      header->seq++;
#endif
#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
      header->status |= SMART_STATUS_COMMITTED;
#else
      header->status &= SMART_STATUS_COMMITTED;
#endif
    }

#ifdef CONFIG_MTD_SMART_ENABLE_CRC
  /* When CRC is enabled and we have a temp alloc, then fill in the RW buffer
   * with the header information prior to copying the write data to the buf.
   */

  if (allocsector)
    {
      smart_write_alloc_sector(dev, allocsector->logical, allocsector->physical);

      /* Remove allocsector from the list and free the memory */

      if (dev->allocsector == allocsector)
        {
          /* We are the head item.  Remove ourselves as head */

          dev->allocsector = allocsector->next;
        }
      else
        {
          FAR struct smart_allocsector_s *prev;

          /* Start at head and find our entry */

          prev = dev->allocsector;
          while (prev && prev->next != allocsector)
            {
              /* Scan the list until we find this entry */

              prev = prev->next;
            }

          if (prev)
            {
              /* Remove from the list */

              prev->next = allocsector->next;
            }
        }

      /* Now free the memory */

      kmm_free(allocsector);
    }

  /* Now copy the data to the sector buffer. */

  memcpy(&dev->rwbuffer[sizeof(struct smart_sect_header_s) + req->offset],
          req->buffer, req->count);

  /* Commit the sector ahead of time.  The CRC will protect us */

#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
  header->status &= ~(SMART_STATUS_COMMITTED | SMART_STATUS_CRC);
#else
  header->status |= SMART_STATUS_COMMITTED | SMART_STATUS_CRC;
#endif

  /* Now calculate the CRC value for the sector */

#ifdef CONFIG_SMART_CRC_8
  header->crc8 = smart_calc_sector_crc(dev);
#elif defined(CONFIG_SMART_CRC_16)
  *((uint16_t *) header->crc16) = smart_calc_sector_crc(dev);
#elif defined(CONFIG_SMART_CRC_32)
  *((uint32_t *) header->crc32) = smart_calc_sector_crc(dev);
#endif

#else  /* CONFIG_MTD_SMART_ENABLE_CRC */

  /* Now copy the data to the sector buffer. */

  memcpy(&dev->rwbuffer[sizeof(struct smart_sect_header_s) + req->offset],
          req->buffer, req->count);

#endif  /* CONFIG_MTD_SMART_ENABLE_CRC */

  /* Now write the sector buffer to the device. */

  if (needsrelocate)
    {
      /* Write the entire sector to the new physical location, uncommitted. */

      ret = MTD_BWRITE(dev->mtd, physsector * dev->mtdBlksPerSector,
              dev->mtdBlksPerSector, (FAR uint8_t *) dev->rwbuffer);
      if (ret != dev->mtdBlksPerSector)
        {
          fdbg("Error writing to physical sector %d\n", physsector);
          ret = -EIO;
          goto errout;
        }

      /* Commit the new physical sector */

#ifndef CONFIG_MTD_SMART_ENABLE_CRC

#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
      byte = header->status & ~SMART_STATUS_COMMITTED;
#else
      byte = header->status | SMART_STATUS_COMMITTED;
#endif
      offset = physsector * dev->mtdBlksPerSector * dev->geo.blocksize +
          offsetof(struct smart_sect_header_s, status);
      ret = smart_bytewrite(dev, offset, 1, &byte);
      if (ret != 1)
        {
          fvdbg("Error committing physical sector %d\n", physsector);
          ret = -EIO;
          goto errout;
        }
#endif

      /* Release the old physical sector */

#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
      byte = header->status & ~(SMART_STATUS_RELEASED | SMART_STATUS_COMMITTED);
#else
      byte = header->status | SMART_STATUS_RELEASED | SMART_STATUS_COMMITTED;
#endif
      offset = mtdblock * dev->geo.blocksize +
          offsetof(struct smart_sect_header_s, status);
      ret = smart_bytewrite(dev, offset, 1, &byte);

      /* Update releasecount for released sector and freecount for the
       * newly allocated physical sector. */

      block = oldphyssector / dev->sectorsPerBlk;
#ifdef CONFIG_MTD_SMART_PACK_COUNTS
      smart_add_count(dev, dev->releasecount, block, 1);
      smart_add_count(dev, dev->freecount, physsector / dev->sectorsPerBlk, -1);
#else
      dev->releasecount[block]++;
      dev->freecount[physsector / dev->sectorsPerBlk]--;
#endif
      dev->freesectors--;
      dev->releasesectors++;

#ifdef CONFIG_SMART_LOCAL_CHECKFREE
      /* Perform debug free count checking enabled */

      smart_checkfree(dev, __LINE__);
#endif

      /* Update the sector map */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
      dev->sMap[req->logsector] = physsector;
#else
      smart_update_cache(dev, req->logsector, physsector);
#endif

      /* Test if releasing the sector created an empty erase block */

      smart_erase_block_if_empty(dev, block, FALSE);

      /* Since we performed a relocation, do garbage collection to
       * ensure we don't fill up our flash with released blocks.
       */

      smart_garbagecollect(dev);
    }
  else  /* needsrelocate */
    {
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
      /* Write the entire sector to FLASH when CRC enabled */

      ret = MTD_BWRITE(dev->mtd, physsector * dev->mtdBlksPerSector,
              dev->mtdBlksPerSector, (FAR uint8_t *) dev->rwbuffer);
      if (ret != dev->mtdBlksPerSector)
        {
          fdbg("Error writing to physical sector %d\n", physsector);
          ret = -EIO;
          goto errout;
        }

      /* Read the sector back and validate the CRC. */

      ret = MTD_BREAD(dev->mtd, physsector * dev->mtdBlksPerSector,
              dev->mtdBlksPerSector, (FAR uint8_t *) dev->rwbuffer);
      if (ret == dev->mtdBlksPerSector)
        {
          /* Validate the CRC of the read-back data */

          ret = smart_validate_crc(dev);
        }

      if (ret != OK)
        {
          /* TODO: Mark this as a bad block! */

          fdbg("Error validating physical sector %d\n", physsector);
          ret = -EIO;
          goto errout;
        }
#else
      /* Not relocated.  Just write the portion of the sector that needs
       * to be written. */

      offset = mtdblock * dev->geo.blocksize +
          sizeof(struct smart_sect_header_s) + req->offset;
      ret = smart_bytewrite(dev, offset, req->count, req->buffer);
#endif
    }

  ret = OK;

errout:
  return ret;
}
#endif /* CONFIG_FS_WRITABLE */

/****************************************************************************
 * Name: smart_readsector
 *
 * Description:  Reads data from the specified logical sector.  The sector
 *               should have already been allocated prior to the read.
 *
 ****************************************************************************/

static int smart_readsector(FAR struct smart_struct_s *dev,
                    unsigned long arg)
{
  int       ret;
  uint16_t  physsector;
  FAR struct smart_read_write_s *req;
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
#if SMART_STATUS_VERSION == 1
  FAR struct smart_sect_header_s *header;
#endif
#else
  uint32_t  readaddr;
  struct smart_sect_header_s header;
#endif

  fvdbg("Entry\n");
  req = (FAR struct smart_read_write_s *) arg;
  DEBUGASSERT(req->offset < dev->sectorsize);
  DEBUGASSERT(req->offset+req->count < dev->sectorsize);

  /* Ensure the logical sector has been allocated */

  if (req->logsector >= dev->totalsectors)
    {
      fdbg("Logical sector %d too large\n", req->logsector);

      ret = -EINVAL;
      goto errout;
    }

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  physsector = dev->sMap[req->logsector];
#else
  physsector = smart_cache_lookup(dev, req->logsector);
#endif
  if (physsector == 0xFFFF)
    {
      fdbg("Logical sector %d not allocated\n", req->logsector);
      ret = -EINVAL;
      goto errout;
    }

#ifdef CONFIG_MTD_SMART_ENABLE_CRC

    /* When CRC is enabled, we read the entire sector into RAM so we can
     * validate the CRC.
     */

    ret = MTD_BREAD(dev->mtd, physsector * dev->mtdBlksPerSector,
        dev->mtdBlksPerSector, (FAR uint8_t *) dev->rwbuffer);
    if (ret != dev->mtdBlksPerSector)
      {
        /* TODO:  Mark the block bad */

        fdbg("Error reading phys sector %d\n", physsector);
        ret = -EIO;
        goto errout;
      }

#if SMART_STATUS_VERSION == 1
  /* Test if this sector has CRC enabled or not */

  header = (FAR struct smart_sect_header_s *) dev->rwbuffer;
  if ((header->status & SMART_STATUS_CRC) == (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_CRC))
    {
      /* Format VERSION 1 supports either no CRC or 8-bit CRC.  Looks like
       * CRC not enabled for this sector, so skip the CRC test.
       */

    }
  else
#endif
    {
      /* Validate the read CRC against the calculated sector CRC */

      ret = smart_validate_crc(dev);
      if (ret != OK)
        {
          /* TODO: Mark the block bad */

          fdbg("Error validating sector %d CRC during read\n", physsector);
          ret = -EIO;
          goto errout;
        }
    }

  /* Copy data to the output buffer */

  memmove((FAR char *) req->buffer, &dev->rwbuffer[req->offset +
      sizeof(struct smart_sect_header_s)], req->count);
  ret = req->count;

#else /* CONFIG_MTD_SMART_ENABLE_CRC */

  /* Read the sector header data to validate as a sanity check */

  ret = MTD_READ(dev->mtd, physsector * dev->mtdBlksPerSector * dev->geo.blocksize,
          sizeof(struct smart_sect_header_s), (FAR uint8_t *) &header);
  if (ret != sizeof(struct smart_sect_header_s))
    {
      fvdbg("Error reading sector %d header\n", physsector);
      ret = -EIO;
      goto errout;
    }

  /* Do a sanity check on the header data */

  if (((*(FAR uint16_t *) header.logicalsector) != req->logsector) ||
      ((header.status & SMART_STATUS_COMMITTED) ==
       (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_COMMITTED)))
    {
      /* Error in sector header! How do we handle this? */

      fdbg("Error in logical sector %d header, phys=%d\n",
          req->logsector, physsector);
      ret = -EIO;
      goto errout;
    }

  /* Read the sector data into the buffer */

  readaddr = (uint32_t) physsector * dev->mtdBlksPerSector * dev->geo.blocksize +
    req->offset + sizeof(struct smart_sect_header_s);;

  ret = MTD_READ(dev->mtd, readaddr, req->count, (FAR uint8_t *)
          req->buffer);
  if (ret != req->count)
    {
      fdbg("Error reading phys sector %d\n", physsector);
      ret = -EIO;
      goto errout;
    }

#endif

errout:
    return ret;
}

/****************************************************************************
 * Name: smart_allocsector
 *
 * Description:  Allocates a new logical sector.  If an argument is given,
 *               then it tries to allocate the specified sector number.
 *
 ****************************************************************************/

#ifdef CONFIG_FS_WRITABLE
static inline int smart_allocsector(FAR struct smart_struct_s *dev,
                    unsigned long requested)
{
  int       x;
  uint16_t  logsector = 0xFFFF; /* Logical sector number selected */
  uint16_t  physicalsector;     /* The selected physical sector */
#ifndef CONFIG_MTD_SMART_ENABLE_CRC
  int       ret;
#endif

  /* Validate that we have enough sectors available to perform an
   * allocation.  We have to ensure we keep enough reserved sectors
   * on hand to do released sector garbage collection. */

  if (dev->freesectors <= (dev->sectorsPerBlk << 0) + 4)
    {
      /* Do a garbage collect and then test freesectors again */

      if (dev->releasesectors + dev->freesectors > dev->availSectPerBlk + 4)
        {

          for (x = 0; x < dev->availSectPerBlk; x++)
            {
              smart_garbagecollect(dev);

              if (dev->freesectors > dev->availSectPerBlk + 4)
                break;
            }

          if (dev->freesectors <= (dev->availSectPerBlk << 0) + 4)
            {
              /* No space left!! */

              return -ENOSPC;
            }
        }
      else
        {
          /* No space left!! */

          return -ENOSPC;
        }
    }

  /* Check if a specific sector is being requested and allocate that
   * sector if it isn't already in use */

  if ((requested > 2) && (requested < dev->totalsectors))
    {
      /* Validate the sector is not already allocated */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
      if (dev->sMap[requested] == (uint16_t) -1)
#else
      if (!(dev->sBitMap[requested >> 3] & (1 << (requested & 0x07))))
#endif
        {
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
          FAR struct smart_allocsector_s *allocsect;

          /* Ensure this logical sector doesn't have a temporary alloc */
          allocsect = dev->allocsector;
          while (allocsect)
            {
              if (allocsect->logical == requested)
                {
                  break;
                }

              allocsect = allocsect->next;
            }

          if (allocsect != NULL)
            {
            }
          else
#endif
            logsector = requested;
        }
    }

  /* Check if we need to scan for an available logical sector */

  if (logsector == 0xFFFF)
    {
      /* Loop through all sectors and find one to allocate */

      for (x = SMART_FIRST_ALLOC_SECTOR; x < dev->totalsectors; x++)
        {
#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
          if (dev->sMap[x] == (uint16_t) -1)
#else
          if (!(dev->sBitMap[x >> 3] & (1 << (x & 0x07))))
#endif
            {
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
              FAR struct smart_allocsector_s *allocsect;

              /* Ensure this logical sector doesn't have a temporary alloc
               * when CRC is enabled.  With CRC enabled, when a sector is
               * allocated, we don't actually update the FLASH until the
               * very end when we have all data so the CRC can be calculated.
               * Instead, we keep an in-memory linked list of allocated
               * sectors until the write sector occurs.
               */

              allocsect = dev->allocsector;
              while (allocsect)
                {
                  if (allocsect->logical == x)
                    {
                      break;
                    }

                  allocsect = allocsect->next;
                }

              if (allocsect != NULL)
                {
                  /* This logical sector has an in-memory temp alloc */

                  continue;
                }
#endif
              /* Unused logical sector found.  Use this one */

              logsector = x;
              break;
            }
        }
    }

  /* Test for an error allocating a sector */

  if (logsector == 0xFFFF)
    {
      /* Hmmm.  We think we had enough logical sectors, but
       * something happened and we didn't find any free
       * logical sectors.  What do do?  Report an error?
       * rescan and try again to "self heal" in case of a
       * bug in our code? */

      fdbg("No free logical sector numbers!  Free sectors = %d\n",
              dev->freesectors);

      return -EIO;
    }

  /* Check if we need to do garbage collection.  We have to
   * ensure we keep enough reserved free sectors to perform garbage
   * collection as it involves moving sectors from blocks with
   * released sectors into blocks with free sectors, then
   * erasing the vacated block. */

  smart_garbagecollect(dev);

  /* Find a free physical sector */

  physicalsector = smart_findfreephyssector(dev, FALSE);
  fvdbg("Alloc: log=%d, phys=%d, erase block=%d, free=%d, released=%d\n",
          logsector, physicalsector, physicalsector /
          dev->sectorsPerBlk, dev->freesectors, releasecount);

#ifdef CONFIG_MTD_SMART_ENABLE_CRC

  /* When CRC is enabled, we don't write the header to the device until
   * the data is written via writesector.  Just add the allocation to
   * our temporary allocsector list and we'll pick it up later.
   */

  {
    FAR struct smart_allocsector_s *allocsect = (FAR struct smart_allocsector_s *)
      kmm_malloc(sizeof(struct smart_allocsector_s));
    if (allocsect == NULL)
      {
        fdbg("Out of memory allocting sector\n");
        return -ENOMEM;
      }

    /* Fill in the struct and add to the list.  We are protected by the
     * smartfs layer's mutex, so no locking required.
     */

    allocsect->logical = logsector;
    allocsect->physical = physicalsector;
    allocsect->next = dev->allocsector;
    dev->allocsector = allocsect;
  }

#else /* CONFIG_MTD_SMART_ENABLE_CRC */

  /* Write the logical sector to the flash.  We will fill it in with data later. */

  ret = smart_write_alloc_sector(dev, logsector, physicalsector);
  if (ret != 1)
    {
      /* Error writing sector, return error */

      return ret;
    }
#endif  /* CONFIG_MTD_SMART_ENABLE_CRC */

  /* Map the sector and update the free sector counts */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  dev->sMap[logsector] = physicalsector;
#else
  dev->sBitMap[logsector >> 3] |= (1 << (logsector & 0x07));
  smart_add_sector_to_cache(dev, logsector, physicalsector, __LINE__ );
#endif

#ifdef CONFIG_MTD_SMART_PACK_COUNTS
  smart_add_count(dev, dev->freecount, physicalsector / dev->sectorsPerBlk, -1);
#else
  dev->freecount[physicalsector / dev->sectorsPerBlk]--;
#endif
  dev->freesectors--;

  /* Return the logical sector number */

  return logsector;
}
#endif /* CONFIG_FS_WRITABLE */

/****************************************************************************
 * Name: smart_freesector
 *
 * Description:  Frees a logical sector from the device.  Freeing (also
 *               called releasing) is performed by programming the released
 *               bit in the sector header's status byte.
 *
 ****************************************************************************/

#ifdef CONFIG_FS_WRITABLE
static inline int smart_freesector(FAR struct smart_struct_s *dev,
                    unsigned long logicalsector)
{
  int       ret;
  int       readaddr;
  uint16_t  physsector;
  uint16_t  block;
  struct    smart_sect_header_s  header;
  size_t    offset;

  /* Check if the logical sector is within bounds */

  if ((logicalsector > 2) && (logicalsector < dev->totalsectors))
    {
      /* Validate the sector is actually allocated */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
      if (dev->sMap[logicalsector] == (uint16_t) -1)
#else
      if (!(dev->sBitMap[logicalsector >> 3] & (1 << (logicalsector & 0x07))))
#endif
        {
          fdbg("Invalid release - sector %d not allocated\n", logicalsector);
          ret = -EINVAL;
          goto errout;
        }
    }

  /* Okay to release the sector.  Read the sector header info */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  physsector = dev->sMap[logicalsector];
#else
  physsector = smart_cache_lookup(dev, logicalsector);
#endif
  readaddr = physsector * dev->mtdBlksPerSector * dev->geo.blocksize;
  ret = MTD_READ(dev->mtd, readaddr, sizeof(struct smart_sect_header_s),
                 (FAR uint8_t *) &header);
  if (ret != sizeof(struct smart_sect_header_s))
    {
      goto errout;
    }

  /* Do a sanity check on the logical sector number */

  if (*((FAR uint16_t *) header.logicalsector) != (uint16_t) logicalsector)
    {
      /* Hmmm... something is wrong.  This should always match!  Bug in our code? */

      fdbg("Sector %d logical sector in header doesn't match\n", logicalsector);
      ret = -EINVAL;
      goto errout;
    }

  /* Mark the sector as released */

#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
  header.status &= ~SMART_STATUS_RELEASED;
#else
  header.status |= SMART_STATUS_RELEASED;
#endif

  /* Write the status back to the device */

  offset = readaddr + offsetof(struct smart_sect_header_s, status);
  ret = smart_bytewrite(dev, offset, 1, &header.status);
  if (ret != 1)
    {
      fdbg("Error updating physical sector %d status\n", physsector);
      goto errout;
    }

  /* Update the erase block's release count */

  dev->releasesectors++;
  block = physsector / dev->sectorsPerBlk;
#ifdef CONFIG_MTD_SMART_PACK_COUNTS
  smart_add_count(dev, dev->releasecount, block, 1);
#else
  dev->releasecount[block]++;
#endif

  /* Unmap this logical sector */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  dev->sMap[logicalsector] = (uint16_t) -1;
#else
  dev->sBitMap[logicalsector >> 3] &= ~(1 << (logicalsector & 0x07));
  smart_update_cache(dev, logicalsector, 0xFFFF);
#endif

  /* If this block has only released blocks, then erase it */

  smart_erase_block_if_empty(dev, block, FALSE);
  ret = OK;

errout:
  return ret;
}
#endif /* CONFIG_FS_WRITABLE */

/****************************************************************************
 * Name: smart_ioctl
 *
 * Description: Return device geometry
 *
 ****************************************************************************/

static int smart_ioctl(FAR struct inode *inode, int cmd, unsigned long arg)
{
  FAR struct smart_struct_s *dev ;
  int ret;
#if defined(CONFIG_FS_PROCFS) && !defined(CONFIG_FS_PROCFS_EXCLUDE_SMARTFS)
  FAR struct mtd_smart_procfs_data_s *procfs_data;
  FAR struct mtd_smart_debug_data_s *debug_data;
#endif

  fvdbg("Entry\n");
  DEBUGASSERT(inode && inode->i_private);

#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
  dev = ((FAR struct smart_multiroot_device_s*) inode->i_private)->dev;
#else
  dev = (FAR struct smart_struct_s *)inode->i_private;
#endif

  /* Process the ioctl's we care about first, pass any we don't respond
   * to directly to the underlying MTD device.
   */

  switch (cmd)
    {
    case BIOC_XIPBASE:
      /* The argument accompanying the BIOC_XIPBASE should be non-NULL.  If
       * DEBUG is enabled, we will catch it here instead of in the MTD
       * driver.
       */

#ifdef CONFIG_DEBUG
      if (arg == 0)
        {
          fdbg("ERROR: BIOC_XIPBASE argument is NULL\n");
          return -EINVAL;
        }
#endif

      /* Just change the BIOC_XIPBASE command to the MTDIOC_XIPBASE command. */

      cmd = MTDIOC_XIPBASE;
      break;

    case BIOC_GETFORMAT:

      /* Return the format information for the device */

#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
      ret = smart_getformat(dev, (FAR struct smart_format_s *) arg,
        ((FAR struct smart_multiroot_device_s*) inode->i_private)->rootdirnum);
#else
      ret = smart_getformat(dev, (FAR struct smart_format_s *) arg);
#endif
      goto ok_out;

    case BIOC_READSECT:

      /* Do a logical sector read and return the data */
      ret = smart_readsector(dev, arg);
      goto ok_out;

#ifdef CONFIG_FS_WRITABLE
    case BIOC_LLFORMAT:

      /* Perform a low-level format on the flash */

      ret = smart_llformat(dev, arg);
      goto ok_out;

    case BIOC_ALLOCSECT:

      /* Allocate a logical sector for the upper layer file system */

      ret = smart_allocsector(dev, arg);
      goto ok_out;

    case BIOC_FREESECT:

      /* Free the specified logical sector */

      ret = smart_freesector(dev, arg);
      goto ok_out;

    case BIOC_WRITESECT:

      /* Write to the sector */

      ret = smart_writesector(dev, arg);

#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
      if (dev->wearflags & SMART_WEARFLAGS_WRITE_NEEDED)
        {
          /* Write new wear status bits to the device */

          smart_write_wearstatus(dev);
        }
#endif

      goto ok_out;
#endif /* CONFIG_FS_WRITABLE */

#if defined(CONFIG_FS_PROCFS) && !defined(CONFIG_FS_PROCFS_EXCLUDE_SMARTFS)
    case BIOC_GETPROCFSD:

      /* Get ProcFS data */

      procfs_data = (FAR struct mtd_smart_procfs_data_s *) arg;
      procfs_data->totalsectors = dev->totalsectors;
      procfs_data->sectorsize = dev->sectorsize;
      procfs_data->freesectors = dev->freesectors;
      procfs_data->releasesectors = dev->releasesectors;
      procfs_data->namelen = dev->namesize;
      procfs_data->formatversion = dev->formatversion;
      procfs_data->unusedsectors = dev->unusedsectors;
      procfs_data->blockerases = dev->blockerases;
      procfs_data->sectorsperblk = dev->sectorsPerBlk;

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
      procfs_data->formatsector = dev->sMap[0];
      procfs_data->dirsector = dev->sMap[3];
#else
      procfs_data->formatsector = smart_cache_lookup(dev, 0);
      procfs_data->dirsector = smart_cache_lookup(dev, 3);
#endif

#ifdef CONFIG_MTD_SMART_SECTOR_ERASE_DEBUG
      procfs_data->neraseblocks = dev->geo.neraseblocks;
      procfs_data->erasecounts = dev->erasecounts;
#endif
#ifdef CONFIG_MTD_SMART_ALLOC_DEBUG
      procfs_data->allocs = dev->alloc;
      procfs_data->alloccount = SMART_MAX_ALLOCS;
#endif
#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
      procfs_data->uneven_wearcount = dev->uneven_wearcount;
#endif
      ret = OK;
      goto ok_out;
#endif

    case BIOC_DEBUGCMD:
#if defined(CONFIG_FS_PROCFS) && !defined(CONFIG_FS_PROCFS_EXCLUDE_SMARTFS)
      debug_data = (FAR struct mtd_smart_debug_data_s *) arg;
      switch (debug_data->debugcmd)
        {
        case SMART_DEBUG_CMD_SET_DEBUG_LEVEL:
          dev->debuglevel = debug_data->debugdata;
          dbg("Debug level set to %d\n", dev->debuglevel);

          ret = OK;
          goto ok_out;
        }
#endif

      break;
    }

  /* No other block driver ioctl commands are not recognized by this
   * driver.  Other possible MTD driver ioctl commands are passed through
   * to the MTD driver (unchanged).
   */

  ret = MTD_IOCTL(dev->mtd, cmd, arg);
  if (ret < 0)
    {
      fdbg("ERROR: MTD ioctl(%04x) failed: %d\n", cmd, ret);
    }

ok_out:
  return ret;
}

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

/****************************************************************************
 * Name: smart_initialize
 *
 * Description:
 *   Initialize to provide a block driver wrapper around an MTD interface
 *
 * Input Parameters:
 *   minor - The minor device number.  The MTD block device will be
 *      registered as as /dev/smartN where N is the minor number.
 *   mtd - The MTD device that supports the FLASH interface.
 *
 ****************************************************************************/

int smart_initialize(int minor, FAR struct mtd_dev_s *mtd, FAR const char *partname)
{
  FAR struct smart_struct_s *dev;
  int ret = -ENOMEM;
  uint32_t  totalsectors;
#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
  FAR struct smart_multiroot_device_s *rootdirdev = NULL;
#endif

  /* Sanity check */

#ifdef CONFIG_DEBUG
  if (minor < 0 || minor > 255 || !mtd)
    {
      return -EINVAL;
    }
#endif

  /* Allocate a SMART device structure */

  dev = (FAR struct smart_struct_s *)kmm_malloc(sizeof(struct smart_struct_s));
  if (dev)
    {
      /* Initialize the SMART device structure */

      dev->mtd = mtd;
#ifdef CONFIG_MTD_SMART_ALLOC_DEBUG
      dev->bytesalloc = 0;
      for (totalsectors = 0; totalsectors < SMART_MAX_ALLOCS; totalsectors++)
        {
          dev->alloc[totalsectors].ptr = NULL;
        }
#endif

      /* Get the device geometry. (casting to uintptr_t first eliminates
       * complaints on some architectures where the sizeof long is different
       * from the size of a pointer).
       */

      /* Set these to zero in case the device doesn't support them */

      ret = MTD_IOCTL(mtd, MTDIOC_GEOMETRY, (unsigned long)((uintptr_t)&dev->geo));
      if (ret < 0)
        {
          fdbg("MTD ioctl(MTDIOC_GEOMETRY) failed: %d\n", ret);
          goto errout;
        }

      /* Set the sector size to the default for now */

#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
      dev->sMap = NULL;
#else
      dev->sCache = NULL;
      dev->sBitMap = NULL;
#endif
      dev->rwbuffer = NULL;
#ifdef CONFIG_MTD_SMART_SECTOR_ERASE_DEBUG
      dev->erasecounts = NULL;
#endif
#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
      dev->wearstatus = NULL;
#endif
#ifdef CONFIG_MTD_SMART_ENABLE_CRC
      dev->allocsector = NULL;
#endif
      dev->sectorsize = 0;
      ret = smart_setsectorsize(dev, CONFIG_MTD_SMART_SECTOR_SIZE);
      if (ret != OK)
        {
          goto errout;
        }

      /* Calculate the totalsectors on this device and validate */

      totalsectors = dev->neraseblocks * dev->sectorsPerBlk;
      if (totalsectors > 65536)
        {
          fdbg("SMART Sector size too small for device\n");
          ret = -EINVAL;
          goto errout;
        }
      else if (totalsectors == 65536)
        {
          totalsectors -= 2;
        }

      dev->totalsectors = (uint16_t) totalsectors;
      dev->freesectors = (uint16_t) dev->availSectPerBlk * dev->geo.neraseblocks;
      dev->lastallocblock = 0;
      dev->debuglevel = 0;

      /* Mark the device format status an unknown */

      dev->formatstatus = SMART_FMT_STAT_UNKNOWN;
      dev->namesize = CONFIG_SMARTFS_MAXNAMLEN;
      if (partname)
        {
          strncpy(dev->partname, partname, SMART_PARTNAME_SIZE);
        }
      else
        {
          dev->partname[0] = '\0';
        }

#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
      dev->minor = minor;
#endif

      /* Create a MTD block device name */

#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
      if (partname != NULL)
        {
          snprintf(dev->rwbuffer, 18, "/dev/smart%d%sd1", minor, partname);
        }
      else
        {
          snprintf(dev->rwbuffer, 18, "/dev/smart%dd1", minor);
        }

      /* Inode private data is a reference to a struct containing
       * the SMART device structure and the root directory number.
       */

      rootdirdev = (FAR struct smart_multiroot_device_s*) smart_malloc(dev,
          sizeof(*rootdirdev), "Root Dir");
      if (rootdirdev == NULL)
        {
          fdbg("register_blockdriver failed: %d\n", -ret);
          ret = -ENOMEM;
          goto errout;
        }

      /* Populate the rootdirdev */

      rootdirdev->dev = dev;
      rootdirdev->rootdirnum = 0;
      ret = register_blockdriver(dev->rwbuffer, &g_bops, 0, rootdirdev);

#else
      if (partname != NULL)
        {
          snprintf(dev->rwbuffer, 18, "/dev/smart%d%s", minor, partname);
        }
      else
        {
          snprintf(dev->rwbuffer, 18, "/dev/smart%d", minor);
        }

      /* Inode private data is a reference to the SMART device structure */

      ret = register_blockdriver(dev->rwbuffer, &g_bops, 0, dev);
#endif

      if (ret < 0)
        {
          fdbg("register_blockdriver failed: %d\n", -ret);
          goto errout;
        }

      /* Do a scan of the device */

      smart_scan(dev);
    }

  return OK;

errout:
#ifndef CONFIG_MTD_SMART_MINIMIZE_RAM
  smart_free(dev, dev->sMap);
#else
  smart_free(dev, dev->sBitMap);
  smart_free(dev, dev->sCache);
#endif
  smart_free(dev, dev->rwbuffer);
#ifdef CONFIG_MTD_SMART_WEAR_LEVEL
  smart_free(dev, dev->wearstatus);
#endif
#ifdef CONFIG_MTD_SMART_SECTOR_ERASE_DEBUG
  smart_free(dev, dev->erasecounts);
#endif
#ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS
  if (rootdirdev)
    {
      smart_free(dev,rootdirdev);
    }
#endif

  kmm_free(dev);
  return ret;
}