rtfcore.c 139 KB
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
/*****************************************************************************
*  Copyright Statement:
*  --------------------
*  This software is protected by Copyright and the information contained
*  herein is confidential. The software may not be copied and the information
*  contained herein may not be used or disclosed except with the written
*  permission of MediaTek Inc. (C) 2010
*
*  BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
*  THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
*  RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON
*  AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
*  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
*  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
*  NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
*  SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
*  SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH
*  THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
*  NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S
*  SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
*  BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
*  LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
*  AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
*  OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO
*  MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
*  THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
*  WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF
*  LAWS PRINCIPLES.  ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND
*  RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER
*  THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC).
*
*****************************************************************************/

/*****************************************************************************
 *
 * Filename:
 * ---------
 *   fs_bl_main.c
 *
 * Project:
 * --------
 *   Maui
 *
 * Description:
 * ------------
 *   This file contains FS for Boot loader.
 *
 * Author:
 * -------
 * -------
 *============================================================================
 *             HISTORY
 * Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
 *------------------------------------------------------------------------------
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *------------------------------------------------------------------------------
 * Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
 *============================================================================
 ****************************************************************************/

/**************************************************************************/
/*                                                                        */
/*  File: RTFILES.C                              Copyright (c) 1998,2002  */
/*  Version: 4.0                                 On Time Informatik GmbH  */
/*                                                                        */
/*                                                                        */
/*                                      On Time        /////////////----- */
/*                                    Informatik GmbH /////////////       */
/* --------------------------------------------------/////////////        */
/*                                  Real-Time and System Software         */
/*                                                                        */
/**************************************************************************/
/*
 * Include
 */

#if defined(WIN32)
#include "windows.h"    // !NOTE! windows.h MUST be defined ahead of Rtfiles.h! Because Rtfiles.h will check _WINDOWS_ definition which is defined in windows.h!
#endif

#include "kal_release.h"
#include "kal_public_defs.h"
#include "kal_general_types.h"
#include "kal_public_api.h"
#include "kal_internal_api.h"    // for KAL_ERROR_FILESYS_INTERNAL_FAILED

#include "fs_gprot.h"
#include "fs_iprot.h"
#include "fs_internal_api.h"
#include "rtfiles.h"
#include "rtfex.h"
#include "rtfbuf.h"
#include "fs_utility.h"
#include "fs_kal.h"
#include "fs_trc.h"
#include "kal_trace.h"
#include "SST_sla.h"            // for SWLA hooker
#include "dcl.h"

#ifdef __FS_CARD_DOWNLOAD__
#include "bl_init.h"
#endif

/*
 * Macros
 */

#if (defined __FS_SYSDRV_ON_NAND__) && !(defined _NAND_FLASH_BOOTING_) && !(defined __EMMC_BOOTING__)
    /* Treat __FS_SYSDRV_ON_NAND__ equal _NAND_FLASH_BOOTING_ */
    #define _NAND_FLASH_BOOTING_
#endif

// Trace
#define fs_util_trace_err_noinfo(error_code) fs_util_trace_err_slim(error_code, rtfcore_c, __LINE__)


// Assert
#define fs_assert_local(expr) fs_assert(expr, rtfcore_c)
#define fs_ext_assert_local(expr, e1, e2, e3) fs_ext_assert(expr, rtfcore_c, e1, e2, e3)

#ifdef _MSC_VER
   #define INTERN _fastcall
#elif defined __BORLANDC__
   #define INTERN __fastcall
#else
   #define INTERN
#endif

#ifndef __FS_CARD_DOWNLOAD__
#define RTFINIT_BEGIN()  \
do \
{ \
   fs_assert_local(FS_MAX_DRIVES >= 1);\
   fs_assert_local(FS_MAX_BUFFERS >= 1);\
   fs_assert_local(FS_MAX_FILES >= 3);\
   fs_assert_local(FS_MAX_THREAD >= 2);\
   \
   RTFLock = RTFSYSAllocMutex("RTFiles");\
   \
   RTFSYSLockMutex(RTFLock, RTF_INFINITE);\
   RTFSYSLockMutex(RTFLock, RTF_INFINITE);\
}while(0)
#else
#define RTFINIT_BEGIN()
#endif /* __FS_CARD_DOWNLOAD__ */


#ifndef __FS_CARD_DOWNLOAD__
#define RTFINIT_END() \
do\
{\
    RTFSYSFreeMutex(RTFLock);\
    RTFSYSFreeMutex(RTFLock);\
}while(0)
#else
#define RTFINIT_END()
#endif /* __FS_CARD_DOWNLOAD__ */

/*
 * Globals
 */
UINT  OpenHintStamp;
int   TLSBlockIndex = -1;
kal_bool  NorPartition;
kal_bool  NandPartition;
const WCHAR dchar_dot[]={0x2e, 0}; /* . */
const WCHAR dchar_dot_dot[]={0x2e, 0x2e, 0}; /* .. */
const WCHAR dchar_start_dot_star[]={0x2a, 0x2e, 0x2a, 0}; /* *.* */
const WCHAR dchar_star[]={0x2a, 0}; /* *.* */
kal_bool gMT_Sanity = KAL_FALSE;
RTFMutex * RTFLock = NULL;

/*
 * Locals
 */
static const int DriveMapTBL[] =
{                       /* Pub 1, Pub 2, Sys 1, Sys 2 */
   /* NOR:NAND = 1:0 */      0x0,   0x0,  0x43,  0x0,   /* 0 0 C 0 */
   /* NOR:NAND = 2:0 */     0x43,   0x0,  0x44,  0x0,   /* C 0 D 0 */
   /* NOR:NAND = 0:1 */      0x0,   0x0,  0x43,  0x0,   /* 0 0 C 0 */
   /* NOR:NAND = 1:1 */     0x44,   0x0,  0x43,  0x0,   /* D 0 C 0 */
   /* NOR:NAND = 2:1 */     0x43,  0x44,  0x45,  0x0,   /* C D E 0 */
   /* NOR:NAND = 0:2 */     0x43,   0x0,  0x44,  0x0,   /* C 0 D 0 */
   /* NOR:NAND = 1:2 */     0x44,   0x0,  0x43, 0x45,   /* D 0 C E */
   /* NOR:NAND = 2:2 */     0x43,  0x44,  0x45, 0x46    /* C D E F */
};

/*
 * Declarations
 */
extern kal_bool     INT_QueryExceptionStatus(void);
extern kal_uint32   SaveAndSetIRQMask(void);
extern void         RestoreIRQMask(kal_uint32 irq);

int RTFAPI MTGetDrive(kal_uint32 Type, kal_uint32 Serial, kal_uint32 AltMask)
{
   UINT Count = 0;
   UINT NORCount = 0, NANDCount = 0, eMMCCount = 0, ExtCount = 0, CardCount = 0, SPlusCount = 0;
   int  Result = 0, TBLidx = -1;

#if ( defined(__NANDFDM_MULTI_INSTANCE__) && defined(__NAND_FDM_50__) )

#if defined(__NAND_SUPPORT_RAW_DISK__)

   /*
    * C (Hidden): Cust(for Wise, PXOs)
    * D (Hidden): Root(for Wise)
    * E (PUB1)  : User(for Wise)
    * F (SYS1)  : Root(for MAUI, NVRAM)
    * G (SYS2)  : Backup Partition
    * - (Hidden): LG Partition (No partition table and drive letter)
    * H (RMV)   : Memory card
    */

   if ((MT_DRIVE_I_SYSTEM == Type) && (2 == Serial))
   {
      return 'G';
   }
   else if ((MT_DRIVE_I_SYSTEM == Type) && (1 == Serial))
   {
      return 'F';
   }
   else if ((MT_DRIVE_V_NORMAL == Type) && ((1 == Serial) || (AltMask & MT_ONLY_ALT_SERIAL)))
   {
      return 'E';
   }
   else if (Type == MT_DRIVE_V_REMOVABLE)
   {
      return 'H';
   }

   if (AltMask & MT_NO_ALT_DRIVE)
   {
      Result = RTF_DRIVE_NOT_FOUND;
      goto getReturn;
   }

   if (AltMask & MT_DRIVE_V_NORMAL)
   {
      Result = 'E';
   }
   else if (AltMask & MT_DRIVE_V_REMOVABLE)
   {
      Result = 'H';
   }
   else if (AltMask & MT_DRIVE_I_SYSTEM)
   {
      Result = 'F';
   }

#else  /* !__NAND_SUPPORT_RAW_DISK__ */
   // Edward add
   if (Type == MT_DRIVE_I_SYSTEM)
   {
      return 'F';
   }
   else if ((Type == MT_DRIVE_V_NORMAL) && ((Serial == 1) || (AltMask & MT_ONLY_ALT_SERIAL)))
   {
      return 'E';
   }
   else if (Type == MT_DRIVE_V_REMOVABLE)
   {
      return 'G';
   }

   if (AltMask & MT_NO_ALT_DRIVE)
   {
      Result = RTF_DRIVE_NOT_FOUND;
      goto getReturn;
   }

   if (AltMask & MT_DRIVE_V_NORMAL)
   {
      Result = 'E';
   }
   else if (AltMask & MT_DRIVE_V_REMOVABLE)
   {
      Result = 'G';
   }
   else if (AltMask & MT_DRIVE_I_SYSTEM)
   {
      Result = 'F';
   }

#endif /* __NAND_SUPPORT_RAW_DISK__ */

   if (Result)
      return Result;
   else
      return RTF_DRIVE_NOT_FOUND;

   // Edward add end
#endif //( defined(__NANDFDM_MULTI_INSTANCE__) && defined(__NAND_FDM_50__) )

#define DEVTYPE_ALL_FLAGS (MT_DRIVE_I_SYSTEM | MT_DRIVE_V_NORMAL | MT_DRIVE_V_REMOVABLE | MT_DRIVE_V_EXTERNAL | MT_DRIVE_V_SIMPLUS)
   /* MTGetDrive - 1 Check parameter */
   if (((Type & DEVTYPE_ALL_FLAGS) == 0) ||
         ((Type & ~DEVTYPE_ALL_FLAGS) != 0) ||
         ((Type & (MT_DRIVE_I_SYSTEM | MT_DRIVE_V_NORMAL)) && (Serial > 2)) ||
         ((Type == MT_DRIVE_V_REMOVABLE) && (Serial > 2)) ||
         (Serial < 1) ||
         ((AltMask != MT_NO_ALT_DRIVE) && (AltMask & MT_NO_ALT_DRIVE)) ||
         ((AltMask != MT_ONLY_ALT_SERIAL) && (AltMask & MT_ONLY_ALT_SERIAL)) ||
         (AltMask & MT_DRIVE_V_EXTERNAL))
   {
      return RTF_PARAM_ERROR;
   }

#undef DEVTYPE_ALL_FLAGS

   /* MTGetDrive - 2 Count Drive in each type */
   SafeLock(MT_LOCK_RTF, NULL, RTF_INFINITE);

   for (Count = MT_BASE_DRIVE_INDEX; Count < FS_MAX_DRIVES; Count++)
   {
      if (gFS_Data.DriveTable[Count].Dev != NULL)
      {
         if (gFS_Data.DriveTable[Count].Dev->DeviceFlags & MT_DEVICE_NOR_FLASH)
         {
            NORCount++;
            //fs_assert_local(NORCount < 3);  // SLIM
         }
         else if (gFS_Data.DriveTable[Count].Dev->DeviceFlags & MT_DEVICE_NAND_FLASH)
         {
            NANDCount++;
            //fs_assert_local(NANDCount < 3); // SLIM
         }
         else if (gFS_Data.DriveTable[Count].Dev->DeviceFlags & FS_DEVICE_EMMC)
         {
            eMMCCount++;
            //fs_assert_local(eMMCCount < 3); // SLIM
         }
         else if ((gFS_Data.DriveTable[Count].Dev->DeviceFlags & (RTF_DEVICE_REMOVABLE | MT_DEVICE_EXTERNAL | MT_DEVICE_SIMPLUS)) == RTF_DEVICE_REMOVABLE)
         {
            CardCount++;
            //fs_assert_local(CardCount < 3); // SLIM
         }
         else if (gFS_Data.DriveTable[Count].Dev->DeviceFlags & MT_DEVICE_SIMPLUS)
         {
            SPlusCount++;
            //fs_assert_local(SPlusCount < 5); // SLIM
         }
         else if (gFS_Data.DriveTable[Count].Dev->DeviceFlags & MT_DEVICE_EXTERNAL)
         {
            ExtCount++;
         }
      }
      else
         break;
   }

   Count = NORCount + NANDCount + eMMCCount;

   fs_assert_local((Count > 0) && (Count < 5));

   if (eMMCCount > 0)
   {
      fs_assert_local(Count == eMMCCount);   // eMMC project should not have NOR and NAND drives

      NORCount = eMMCCount; // treat eMMC booting case as NOR booting for TBLidx calculation below.
   }

#ifndef _NAND_FLASH_BOOTING_    // should bypass EMMC booting case
   fs_assert_local(NORCount > 0);
#endif

#ifdef __FS_SHADOW_NAND__
   fs_assert_local(NANDCount < 2);
#endif

#ifdef __FS_SHADOW_CARD__
   fs_assert_local(CardCount < 2);
#endif

   /* Calculate TBLidx BASE */
   TBLidx = (NORCount + NANDCount * 3 - 1) * 4;
   /* 1 0 => 0; 0 1 => 2; 0 2 => 5 */

   /* Match type first */

   switch (Type)
   {
      case MT_DRIVE_I_SYSTEM: /* Match system drive */

         if (DriveMapTBL[TBLidx + 2 + Serial - 1] != 0x0)
         {
            Result = DriveMapTBL[TBLidx + 2 + Serial - 1];
            goto getReturn;
         }

         break;

      case MT_DRIVE_V_NORMAL: /* Match normal drive */

         if (DriveMapTBL[TBLidx + 0 + Serial - 1] != 0x0)
         {
            Result = DriveMapTBL[TBLidx + 0 + Serial - 1];
            goto getReturn;
         }

         break;

      case MT_DRIVE_V_REMOVABLE: /* Match removable drive */

         if (Serial <= CardCount)
         {
            Result = MT_BASE_DRIVE_LETTER + Count + Serial - 1;
            goto getReturn;
         }

         break;

      case MT_DRIVE_V_SIMPLUS: /* Match SIMPLUS drive ; No alternative match */

         if (Serial <= SPlusCount)
         {
            Result = MT_BASE_DRIVE_LETTER + Count + CardCount + Serial - 1;
         }
         else
         {
            Result = RTF_DRIVE_NOT_FOUND;
         }

         goto getReturn;

      case MT_DRIVE_V_EXTERNAL: /* Match external drive ; No alternative match */

         if (Serial <= ExtCount)
         {
            Result = MT_BASE_DRIVE_LETTER + Count + CardCount + SPlusCount + Serial - 1;
         }
         else
         {
            Result = RTF_DRIVE_NOT_FOUND;
         }

         goto getReturn;

      default:
         Result = RTF_PARAM_ERROR;
         goto getReturn;
   }//end of switch

   if (AltMask & MT_NO_ALT_DRIVE)
   {
      Result = RTF_DRIVE_NOT_FOUND;
      goto getReturn;
   }

   /* Match serial then */
   if (AltMask & MT_ONLY_ALT_SERIAL)
   {
      switch (Type)
      {
         case MT_DRIVE_I_SYSTEM: /* Match system drive */

            if ((Serial == 2) && (DriveMapTBL[TBLidx + 2] != 0x0))
            {
               Result = DriveMapTBL[TBLidx + 2];
               goto getReturn;
            }
            else if ((Serial == 1) && (DriveMapTBL[TBLidx + 3] != 0x0))
            {
               Result = DriveMapTBL[TBLidx + 3];
               goto getReturn;
            }

            break;

         case MT_DRIVE_V_NORMAL: /* Match normal drive */

            if ((Serial == 1) && (DriveMapTBL[TBLidx + 1] != 0x0))
            {
               Result = DriveMapTBL[TBLidx + 1];
               goto getReturn;
            }
            else if ((Serial == 2) && (DriveMapTBL[TBLidx + 0] != 0x0))
            {
               Result = DriveMapTBL[TBLidx + 0];
               goto getReturn;
            }

            break;

         case MT_DRIVE_V_REMOVABLE: /* Match removable drive */

            if (CardCount > 0)
            {
               Result = MT_BASE_DRIVE_LETTER + Count + CardCount - 1;
               goto getReturn;
            }

            break;

         default:
            Result = RTF_PARAM_ERROR;
            goto getReturn;
      }//end of switch
   }

   /* Match other alter last */
   if ((DriveMapTBL[TBLidx + 1]) && (AltMask & MT_DRIVE_V_NORMAL))
   {
      Result = DriveMapTBL[TBLidx + 1];
   }
   else if ((DriveMapTBL[TBLidx + 0]) && (AltMask & MT_DRIVE_V_NORMAL))
   {
      Result = DriveMapTBL[TBLidx + 0];
   }
   else if ((CardCount > 0) && (AltMask & MT_DRIVE_V_REMOVABLE))
   {
      Result = MT_BASE_DRIVE_LETTER + Count + CardCount - 1;
   }
   else if ((DriveMapTBL[TBLidx + 3]) && (AltMask & MT_DRIVE_I_SYSTEM))
   {
      Result = DriveMapTBL[TBLidx + 3];
   }
   else if ((DriveMapTBL[TBLidx + 2]) && (AltMask & MT_DRIVE_I_SYSTEM))
   {
      Result = DriveMapTBL[TBLidx + 2];
   }

getReturn:

   SafeUnlock(MT_LOCK_RTF);

   if (Result)
      return Result;

   fs_util_trace_err_noinfo(RTF_DRIVE_NOT_FOUND);

   return RTF_DRIVE_NOT_FOUND;
}


#if defined(__FS_IO_STATISTICS__)
// The caller must obtain RTFLock before invoke this function
static void rtf_core_io_statistic(kal_uint32 sectors, kal_uint32 time)
{
    kal_int32  task_index;
    kal_int32  thread_count;
    kal_taskid current_task;

    if (gFS_TaskIOStatistics==NULL) return;

    current_task = kal_get_current_thread_ID();
    thread_count = RTFSYSGetThreadCount();

    /* Find current task id is registered or not */
    for (task_index=0; task_index<thread_count; task_index++)
    {
        if (gFS_TaskList[task_index] == current_task) break;
    }

    if (task_index == thread_count) return;

    gFS_TaskIOStatistics[task_index].AccessCount++;
    gFS_TaskIOStatistics[task_index].SectorCount+=sectors;
    gFS_TaskIOStatistics[task_index].AccessTime+=(time/25);  // time unit: 1=25us
}
#else
#define rtf_core_io_statistic(sectors, time)
#endif // __FS_IO_STATISTICS__

void rtf_core_access_check(RTFDevice * Dev, RTFSector SectorAddress, UINT SectorCount)
{
     CheckMedia(Dev);

     if (Dev->DevData.ErrorCondition < RTF_NO_ERROR)
     {
        fs_util_trace_err_noinfo(Dev->DevData.ErrorCondition);
        //fs_util_trace_info4(TRACE_ERROR, FS_ERR_READSECTORS_DEVICE_ERROR, Sector, Sectors, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL, NULL);

        XRAISE(Dev->DevData.ErrorCondition);
     }

     if (Dev->DevData.MountState < Mounted)
     {
        fs_util_trace_err_noinfo(RTF_DRIVE_NOT_READY);
        //fs_util_trace_info4(TRACE_ERROR, FS_ERR_READSECTORS_DEV_NOT_READY, Sector, Sectors, Dev->DevData.MountState, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

        XRAISE(RTF_DRIVE_NOT_READY);
     }

     if((SectorAddress + SectorCount) > Dev->DevData.Geometry.Sectors)
     {
        fs_util_trace_err_noinfo(RTF_FAT_ALLOC_ERROR);
        //fs_util_trace_info4(TRACE_ERROR, FS_ERR_READSECTORS_OUT_OF_RANGE, Sector, Sectors, Dev->DevData.Geometry.Sectors, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

        XRAISE(RTF_FAT_ALLOC_ERROR);
     }
}

int rtf_core_read_sectors(RTFDevice * Dev, void * Data, RTFSector Sector, UINT Sectors, DWORD Flags)
{
   int volatile   Result;
   fs_util_time_init_with_duration();

   RTFSYSFreeMutex(RTFLock);

   XTRY
      case XCODE:
      {
         rtf_core_access_check(Dev, Sector, Sectors);

         fs_util_time_start();

         //fs_util_trace_info1(TRACE_GROUP_2, FS_INFO_READSECTORS_S, Sector, NULL);

         // SWLA hooker
         fs_util_swla_hook((FS_Device *)Dev, FS_DRV_READ, SA_start);

         Result = Dev->Driver->ReadSectors(Dev->DriverData, Sector, Sectors, Data);

         // SWLA hooker
         fs_util_swla_hook((FS_Device *)Dev, FS_DRV_READ, SA_stop);

         fs_util_time_stop();
         fs_util_time_set_duration();

         // IO Trace
         fs_util_trace_device_io(Dev->DeviceFlags | MT_IO_TRACE_READ, Sector, Sectors, fs_util_time_query_duration());

         if (Result < RTF_NO_ERROR)
         {
            fs_util_trace_err_noinfo(Result);
            fs_util_trace_info4(TRACE_ERROR, FS_ERR_READSECTORS_DRIVER_FAIL, Sector, Sectors, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL, NULL);

            XRAISE(Result);
         }
         break;
      }
      default:
         if (((Flags & NO_CRITICAL) == 0) &&
             (HandleCriticalError(Dev, XVALUE) == RTFRetry))
         {
            XHANDLED;
            XREEXECUTE;
         }

         if (MT_MSDC_MOUNT_ERROR == XVALUE)
         {
            MTErrHdlr_RemovableDeviceRWError(Dev);
            XVALUE = MT_MSDC_READ_SECTOR_ERROR;
         }

         if (Flags & NO_RAISE)
         {
            Result = XVALUE;
            Dev->DevData.ErrorCondition = RTF_NO_ERROR;
            XHANDLED;
         }

         break;
      case XFINALLY:
         RTFSYSLockMutex(RTFLock, RTF_INFINITE);
         fs_util_time_set_duration();
         rtf_core_io_statistic(Sectors, fs_util_time_query_duration());

         break;
   XEND
   return Result;
}

/*-----------------------------------*/

/*-----------------------------------*/
int rtf_core_write_sectors(RTFDevice * Dev, void * Data, RTFSector Sector, UINT Sectors, DWORD Flags, BYTE recoverable_flag)
{
   int volatile   Result;
   int            fs_block_type = FS_BLOCK_ENUM; /* Fix multi-access bug, Karen Hsu, 2004/07/08, ADD */
   int  (RTFAPI * DevWrite) (void * DriveData, RTFSector Sector, UINT Sectors, void * Buffer);

   fs_util_time_init_with_duration();

   RTFSYSFreeMutex(RTFLock);

   XTRY
      case XCODE:
      {
         rtf_core_access_check(Dev, Sector, Sectors);

         fs_block_type = (int)RTFSYSGetTLS(TLSBlockIndex);

         //fs_util_trace_info1(TRACE_GROUP_2, FS_INFO_WRITESECTORS_S, Sector, NULL);

         fs_util_time_start();

         // SWLA hooker
         fs_util_swla_hook((FS_Device *)Dev, FS_DRV_WRITE, SA_start);

         do {
             DevWrite = Dev->Driver->WriteSectors;

             if (recoverable_flag == RTF_RECOVERABLE_WRITE)
             {
                if (Dev->Driver->RecoverableWriteSectors)
                {
                   // Result = Dev->Driver->RecoverableWriteSectors(Dev->DriverData, Sector, Sectors, Data);
                   DevWrite = Dev->Driver->RecoverableWriteSectors;
                }
                else
                {
                   fs_util_trace_err_noinfo(MT_NO_PROTECTIONMODE);
                   fs_util_trace_info1(TRACE_ERROR, FS_ERR_WRITESECTORS_NO_PROTECTION_MODE, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

                   Result = FS_NO_PROTECTIONMODE;
                   break;
                }
             }
             else if (fs_block_type == FS_NON_BLOCK_ENUM)
             {
                if (Dev->Driver->NonBlockWriteSectors)
                {
                   //Result = Dev->Driver->NonBlockWriteSectors(Dev->DriverData, Sector, Sectors, Data);
                   DevWrite = Dev->Driver->NonBlockWriteSectors;
                }
             }

             Result = DevWrite(Dev->DriverData, Sector, Sectors, Data);
         } while (0);

         // SWLA hooker
         fs_util_swla_hook((FS_Device *)Dev, FS_DRV_WRITE, SA_stop);

         fs_util_time_stop();
         fs_util_time_set_duration();

         // IO Trace, mark 0x10000, as a write trace
         fs_util_trace_device_io(Dev->DeviceFlags | MT_IO_TRACE_WRITE, Sector, Sectors, fs_util_time_query_duration());


#if defined(_NAND_FLASH_BOOTING_)
         // For NAND flash bad block issue, Karen Hsu, 2004/02/20
         if (Result == RTF_BAD_SECTOR)
         {
            UINT drvIdx;

            fs_util_trace_err_noinfo(RTF_BAD_SECTOR);
            fs_util_trace_info4(TRACE_ERROR, FS_ERR_WRITESECTORS_BAD_SECTOR, Sector, Sectors, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL, NULL);

            for (drvIdx = MT_BASE_DRIVE_INDEX; drvIdx < FS_MAX_DRIVES; drvIdx++)
            {
               if (gFS_Data.DriveTable[drvIdx].Dev != NULL)
               {
                  if (gFS_Data.DriveTable[drvIdx].Dev == Dev)
                  {
                     kal_uint32 fatStart, dataStart;
                     fatStart = gFS_Data.DriveTable[drvIdx].FirstFATSector;
                     dataStart = gFS_Data.DriveTable[drvIdx].FirstDataSector;

                     if (Sector >= fatStart && Sector < dataStart)
                     {

                        fs_util_trace_err_noinfo(MT_SYSTEM_CRASH);
                        fs_util_trace_info4(TRACE_ERROR, FS_ERR_WRITESECTORS_SYSTEM_CRASH, Sector, Sectors, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL, NULL);

                        XRAISE(MT_SYSTEM_CRASH);
                     }
                  }
               }
               else break;
            }
         }
#endif // _NAND_FLASH_BOOTING_

         if (Result < RTF_NO_ERROR)
         {
            fs_util_trace_err_noinfo(Result);
            fs_util_trace_info4(TRACE_ERROR, FS_ERR_WRITESECTORS_DRIVER_FAIL, Sector, Sectors, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL, NULL);

            XRAISE(Result);
         }

         break;
      }
      default:

         if (((Flags & NO_CRITICAL) == 0) &&
               (HandleCriticalError(Dev, XVALUE) == RTFRetry))
         {
            XHANDLED;
            XREEXECUTE;
         }

         if (MT_MSDC_MOUNT_ERROR == XVALUE)
         {
            MTErrHdlr_RemovableDeviceRWError(Dev);
            XVALUE = MT_MSDC_WRITE_SECTOR_ERROR;
         }

         if (Flags & NO_RAISE)
         {
            Result = XVALUE;
            Dev->DevData.ErrorCondition = RTF_NO_ERROR;
            XHANDLED;
         }

         break;

      case XFINALLY:
         RTFSYSLockMutex(RTFLock, RTF_INFINITE);
         fs_util_time_set_duration();
         rtf_core_io_statistic(Sectors, fs_util_time_query_duration());

         break;
   XEND

   return Result;
}


#define RTF_CORE_DIR_ENTRY

DirEntry RTFAPI EntryType(const RTFDOSDirEntry * D)
{
   if (D->FileName[0] == '\0' || D->FileName[0] == '\xFF')
      return NeverUsed;
   if (D->FileName[0] == RTF_DELETED)
      return Available;
   if (D->Attributes == RTF_LONGNAME_ATTR)
      return Lfn;
   return InUse;
}

void MakePseudoRootDirEntry(RTFDrive * Drive, RTFDirEntry * DirEntry)
{
#if !defined(__NOT_SUPPORT_FAT32__)
   RTFCluster DirCluster = (Drive->FATType == RTFAT32) ? Drive->FirstDirSector : RTF_ROOT_DIR;
#else
   RTFCluster DirCluster = RTF_ROOT_DIR;
#endif /* __NOT_SUPPORT_FAT32__ */

   memset(DirEntry, 0, sizeof(*DirEntry));
   DirEntry->Dir.FileName[0] = '\\';
   memset((char *)DirEntry->Dir.FileName+1, ' ', 7+3);
   DirEntry->Dir.Attributes = RTF_ATTR_DIR;
   SET_FIRST_FILE_CLUSTER(DirEntry->Dir, DirCluster);
}

RTFDOSDirEntry *GetDirPrefetch(RTFDrive * Drive, const RTFDirLocation * Pos, kal_int32 PrefetchSectors)
{
   RTFSector Sector = CLUSTER_TO_SECTOR_DIR(Drive, Pos->Cluster) + (Pos->Index / DIRS_PER_SECTOR(Drive));
   fs_util_trace_info1(TRACE_GROUP_10, FS_TRC_RTF_GETDIR, Sector, NULL);

    // The prefetch sector length is always one cluster, because directory clusters are rarely continuous.
    if (PrefetchSectors == 0)   {
        PrefetchSectors = Drive->SectorsPerCluster;
    }

    return (RTFDOSDirEntry *) GetBufferDIR(Drive->Dev, Sector, PrefetchSectors) + (Pos->Index % DIRS_PER_SECTOR(Drive));
}
/*******************************************************************//**
 * Increase DSR->Index
 *
 * @par Category:
 * File System
 *
 * @return
 * 1: Sucessfully update the index for next directory entry
 * 0: No more directory entry
 **********************************************************************/
int IncDirPrefetch(RTFDrive * Drive, RTFDirLocation * DSR, kal_int32 PrefetchSectors)
{
   /* increase index */
   DSR->Index++;

   fs_util_trace_info2(TRACE_GROUP_10, FS_TRC_RTF_INCDIR, DSR->Cluster, DSR->Index, NULL);

   /* for root directory */
   if (DSR->Cluster == RTF_ROOT_DIR)
   {
      if (DSR->Index >= Drive->RootDirEntries)
         return 0;
   }
   /* for not root directory */
   else
   {
      /* get next cluster if new index is beyond this cluster */
      if (DSR->Index >= (Drive->ClusterSize/sizeof(RTFDOSDirEntry)))
      {
         RTFCluster NextCluster = GetClusterValue(Drive, DSR->Cluster, PrefetchSectors);
         DSR->Index = 0;

         /* meet the end of cluster chain, finish search */
         if (NextCluster >= RTF_CLUSTER_CHAIN_END)
            return 0;

         /* update cluster number */
         DSR->Cluster = NextCluster;
      }
   }

   return 1;
}

/*******************************************************************//**
 * Go to next directory entry
 *
 * @par Category:
 * File System
 *
 * @return
 * Next directry entry pointer. If no more directory entry, return NULL.
 **********************************************************************/
RTFDOSDirEntry * RTFAPI NextDirPrefetch(RTFDrive * Drive, RTFDirLocation * DSR, kal_int32 PrefetchSectors)
{
   fs_util_trace_info0(TRACE_GROUP_10, FS_TRC_RTF_NEXTDIR, NULL);

   if (IncDirPrefetch(Drive, DSR, 2))   {
      return GetDirPrefetch(Drive, DSR, PrefetchSectors);
   }
   else {
      return NULL;
   }
}

/*-----------------------------------*/
/* copy long file name from LFN entry, remain the Unicode format */
void RTFAPI CopyLFN(char * Name, const LFNDirEntry * LD)
{
   UINT i, index=0;
   WORD U;

   for (i=0; i<13; i++)
   {
      if(i < 5)
      {
         U = LD->Name1[i];
      }
      else if(i < 11)
      {
         U = LD->Name2[i-5];
      }
      else
      {
         U = LD->Name3[i-11];
      }

      if ((U == 0) || (U == 0xFFFF))
      {
         Name[index++] = 0;
         Name[index] = 0;
         break; // end of string
      }
      Name[index++] = U&0xff;
      Name[index++] = U>>8;
   }
}

/*-----------------------------------*/
/*In terms of WCHAR */
int RTFAPI LFNCharCount(const LFNDirEntry * LD)
{
   int i;

   for (i=0; i<13; i++)
   {
      if(i < 5)
      {
         if((UINT)(LD->Name1[i]) == 0)
            return i;
      }
      else if(i < 11)
      {
         if((UINT)(LD->Name2[i-5]) == 0)
            return i;
      }
      else
      {
         if((UINT)(LD->Name3[i-11]) == 0)
            return i;
      }
   }
   return 13;
}

BYTE RTFAPI ShortNameCheckSum(const BYTE * Name)
{
   int i;
   BYTE Sum = 0;
   for (i=0; i<11; i++)
      Sum = ((Sum & 1) ? 0x80 : 0) + (Sum >> 1) + Name[i];
   return Sum;
}

/*******************************************************************//**
 * Make a short file name string (native encoding) from a directory entry structure.
 *
 * @par Category:
 * File System
 *
 * @param[in] FileInfo        Directry entry structure, containing Native short name
 * @parma[in] MaxLength       The length of file name string buffer
 * @param[in, out] FileName   Buffer to store translated file name string
 **********************************************************************/
int RTFAPI MakeShortFileName(const RTFDOSDirEntry * FileInfo, char * FileName, UINT MaxLength)
{
    const char *LastName;
    const char *LastExt;
    int i, N, E;

    if (FileInfo->Attributes & RTF_ATTR_VOLUME)
    {
        // for volume label, copy all original FileName + ExtensionName to buffer
        if (12 > MaxLength)
        {
            return RTF_STRING_BUFFER_TOO_SMALL;
        }

        memcpy(FileName,(char*) FileInfo->FileName, 11);

        for (N = 10; N >= 0; N--)
        {
            if (FileName[N] != ' ')
            {
                FileName[N + 1] = '\0';

                break;
            }
        }

        if (N == -1)
        {
            FileName[0] = '\0';
        }

        return FS_NO_ERROR;
    }

    /* search the end of extension name */
    LastExt = FileInfo->Extension + 2;

    for (i=0; i<3; i++)
        if (LastExt[0] == ' ')
            LastExt--;

    if (LastExt == (const char*)((unsigned)FileInfo->Extension - 1))
    {
       LastExt = NULL;
    }

    /* search the end of file name */
    LastName = FileInfo->FileName + 7;

    for (i=0; i<8; i++)
        if (LastName[0] == ' ')
            LastName--;

    if (LastName == (const char*)((unsigned)FileInfo->FileName - 1))
    {
        // input file name contains nothing but all spaces, invalid file name
        fs_util_trace_err_noinfo(RTF_INVALID_FILENAME);

        return RTF_INVALID_FILENAME;
    }

    /* N: length of file name */
    N = LastName ? (LastName - FileInfo->FileName + 1) : 0;

    /* E: length of extension name */
    E = LastExt ? (LastExt - FileInfo->Extension + 1) : 0;

    /* check the length of full short name */
    if ((N+E+1+(E != 0)) > MaxLength)
        return RTF_STRING_BUFFER_TOO_SMALL;

    /* copy file name portion to FileName */
    memcpy(FileName,(char*) FileInfo->FileName, N);

    /* add '.' if extension name is existed */
    if (E)
    {
        FileName[N] = '.';
        N++;
    }

    /* copy extension name to FileName */
    memcpy(FileName + N, (char*) FileInfo->Extension, E);

    /* add tail mark */
    FileName[N+E] = '\0';

    return RTF_NO_ERROR;
}

/*-----------------------------------*/
RTFDOSDirEntry *StartDirSearchPrefetch(RTFDrive * Drive, RTFCluster Cluster, UINT Index, RTFDirLocation * DSR, kal_int32 PrefetchSectors)
{
   /* cluster number out of range */
   if ((Cluster != RTF_ROOT_DIR) && ((Cluster < 2L) || (Cluster >= Drive->Clusters)))
   {
      fs_util_trace_err_noinfo(FS_BAD_DIR_ENTRY);
      fs_util_trace_info4(TRACE_ERROR, FS_ERR_STARTDIRSEARCH_BEYOND_LAST_CLUSTER, Cluster, Index, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), NULL, NULL);
      XRAISE(FS_BAD_DIR_ENTRY);
   }

   DSR->Cluster = Cluster;
   DSR->Index   = Index;

   return GetDirPrefetch(Drive, DSR, PrefetchSectors);
}


void MTHintGen(RTFDirLocation *Hint, RTFDirLocation *DSR_SFN, RTFile *f)
{
#ifndef __FS_CARD_DOWNLOAD__
   if(f->DirEntry.LongPos.Cluster)
   {
      Hint->Cluster= f->DirEntry.LongPos.Cluster;
      Hint->Index= f->DirEntry.LongPos.Index;
   }
   else
   {
      Hint->Cluster= DSR_SFN->Cluster;
      Hint->Index  = DSR_SFN->Index;
   }

#ifdef __FS_OPEN_HINT__
   if (MTIsInternalHint(Hint) == 0)
#endif /* __FS_OPEN_HINT__ */
   {
      ((RTFFileOpenHint*)Hint)->Drive = (UINT)f->Drive;
      ((RTFFileOpenHint*)Hint)->SerialNumber = f->Drive->SerialNumber;
      ((RTFFileOpenHint*)Hint)->Stamp = OpenHintStamp;
   }
#endif
}

/*******************************************************************//**
 * Translate long file name (unicode) to short file name (native, DirEntry format)
 *
 * @par Category:
 * File System
 *
 * @param[in]  LongName  Long file name encoded by unicode
 * @param[out] ShortName Short file name encoded by native (DirEntry format)
 *
 * @par ChangeLog:
 * W09.48: Add INC_SHORT_NAME in case that extension name is beyond length 3. (Stanley Chu)
 * W09.07: Use SKIP_MATCH_SFN flag to decide if SFN should be skipped in SearchFile() more precisely. (Stanley Chu)
 *
 * @note:
 * 1. Validity of ASCII code must be checked, any invalid short file name is coded as '_'
 * 2. Both FileName and Extension is generated and filled in ShortName buffer.
 * 3. Lossyflag:
 *    1. Once lossyflag is set, LFN is required!
 *    2. If INC_SHORT_NAME is set, default SFN should be processed by IncShortName first before being created.
 *    3. If SKIP_MATCH_SFN is set, SearchFile can skip SFN matching to improve search time.
 **********************************************************************/
int GenerateShortName(const char * LongName, char * ShortName)
{
   const char * pN = LongName;
   char       * pF = ShortName;
   int          LossyFlag = 0;
   WCHAR        wide_c;
   char         c;
   char         encoding_length;
   const char * pSearch;

   encoding_length = fs_util_get_default_encoding_length();

   /* fill-in "spaces" to ShortName buffer in advance */
   memset(pF, ' ', 8 + 3);

   /* locate the last dot before NULL or backslash */
   for (pSearch  = pN; (pSearch[0] || pSearch[1]) && !(compASCII(pSearch, 0, '\\')) ; pSearch += 2);
   for (pSearch -=  2; (pSearch > pN) && !(compASCII(pSearch, 0, '.')) ; pSearch -= 2);

   /* set pSearch to NULL if dot-begin or dot-not-found (no extension name) */
   if (pSearch == pN)
   {
      pSearch = NULL;
   }

   /*---------------------------
    * Major file name portion
    *---------------------------*/

   while ((pN[0] || pN[1]) && !(compASCII(pN, 0, '\\')) && ((pF - ShortName) < 8))
   {
      if (compASCII(pN, 0, '.'))
      {
         /* break if last dot hit
          * otherwise, it's a multi-dot case, set LossyFlag and continue */
         if (pN == pSearch)
         {
            break;
         }

         /* ignore '.' */
         else
         {
            LossyFlag++;
            LossyFlag |= (INC_SHORT_NAME | SKIP_MATCH_SFN);
            pN += 2;
            continue;
         }
      }

      /*------ ASCII character ------*/
      if (isASCII(pN, 0))
      {
         /* ASCII character: not space */
         if (!(compASCII(pN, 0, ' ')))
         {
            c = fs_util_get_short_char(pN[0]);

            /* if this character is not supported by SFN, set lossy flag */
            if ((c == '_') && (!(compASCII(pN, 0, '_'))))
            {
               LossyFlag++;
               LossyFlag |= (INC_SHORT_NAME | SKIP_MATCH_SFN);
            }

            /* copy this ASCII character to native SFN buffer */
            *pF++ = c;
         }

         /* space */
         else
         {
            LossyFlag++;
            LossyFlag |= (INC_SHORT_NAME | SKIP_MATCH_SFN);

            /* !! space is ignored in native SFN !! */
         }
      }

      /*------ Non-ASCII character ------*/
      else
      {
         /* always set lossy flag to have a LFN if a non-ASCII character is encountered. Even though the length fits in SFN */
         LossyFlag++;

         /* need at least 2 bytes, so if the length of short name has reached 7, it is impossible to "preserve" this character */
         if ((encoding_length > 1) && (pF - ShortName) >= 7)
         {
            LossyFlag |= (INC_SHORT_NAME | SKIP_MATCH_SFN);
            break;
         }

         /* translate unicode to wide native character (need 2 bytes to store) */
         wide_c = fs_util_uni_to_native(*(kal_uint8 *)(pN) | (*(kal_uint8 *)(pN + 1) << 8));

         #ifndef __FS_NATIVE_ENCODING_TRANSPARENT__

         if (wide_c == 0xFFFF) // convert failed mark for both 8-bit and 16-bit encoding
         {
            wide_c = L'_';  // use '_' instead of invalid encoding
            LossyFlag |= (INC_SHORT_NAME | SKIP_MATCH_SFN);
            // Note: the conversion is failed, the output short name is wide_c & 0xFF = '_'
         }
         else if (encoding_length == 1) // convert successfully for 8-bit encoding
         {
            /*
             * If we try to convert UCS2 to a small encoding (e.g., 8-bit encoding),
             * the possibility of duplication is very high! (imagine convert Chinese
             * to ASCII). Therefore add flag SKIP_MATCH_SFN forcedly to skip SFN matching
             * match in SearchFile().
             */

            wide_c = (WCHAR)fs_util_gen_friendly_char((char)wide_c);
            LossyFlag |= (INC_SHORT_NAME | SKIP_MATCH_SFN);
         }
         else if (encoding_length > 1)  {  // copy 2-bytes native character to native SFN buffer
            *pF++ = wide_c >> 8;
         }

         /* Note: if unicode can be successfully translated to native code, SFN matching should
          * NOT be skipped in SearchFile! */

         #endif /* !__FS_NATIVE_ENCODING_TRANSPARENT__ */

         /*
          * If __FS_NATIVE_ENCODING_TRANSPARENT__ is defined, UnicodetoNative()
          * will return valid ASCII char, thus we only need to append one byte.
          */

         *pF++ = wide_c & 0xff;
      }

      /* goto next unicode character in source LFN */
      pN += 2;
   }

   /* if pN is NOT NULL, pN may be
    * 1. '\'
    * 2. '.'
    * 3. Other character (pN must be the 9th WCHAR), that is, the length of file name portion > 8 */

   if (pN[0] || pN[1])
   {
      /* if pN is "dot" */
      if (compASCII(pN, 0, '.'))
      {
         /* but NOT the LAST "dot", it's a multi-dot case, set lossy flag */
         if (pSearch != pN)
         {
            LossyFlag++;
            LossyFlag |= (INC_SHORT_NAME | SKIP_MATCH_SFN);
         }

         /*
          * Note if this is a multi-dot case, and if the first dot appears in any position of the
          * upfront 8 characters, INC_SHORT_NAME and SKIP_MATCH_SFN flags were set in above while-loop.
          *
          * However, in multi-dot case, if the first dot is located right after the 8th character, e.g.,
          * "MEDIATEK.IS.SO.STRONG", then INC_SHORT_NAME must be set as well to prevent following cases:
          *
          * 1. Create "MEDIATEK.1ST"
          * 2. Rename it to "MEDIATEK.1ST.1ST"
          * 3. FS_Open("MEDIATEK.1ST") will find it and confuse users.            (W10.11 Stanley Chu)
          */
      }
      /* if pN is '\' */
      else if (compASCII(pN, 0, '\\'))
      {
         // do nothing.
      }
      /* other wide characters, that is, the length of file name portion > 8. */
      else
      {
         LossyFlag++;
         LossyFlag |= (INC_SHORT_NAME | SKIP_MATCH_SFN);
      }
   }

   /* goto the last dot to handle extension name, if no extension name, pN = pSearch = NULL! */
   pN = pSearch;
   pF = ShortName + 8;

   /*---------------------------
    * Extension name portion
    *---------------------------*/

   if (pN)
   {
      /* skip '.' */
      pN += 2;

      while ((pN[0] || pN[1]) && !(compASCII(pN, 0, '\\')) && ((pF - ShortName) < 11))
      {
         /*------ ASCII character ------*/
         if (isASCII(pN, 0))
         {
            if (!compASCII(pN, 0, ' '))
            {
               c = fs_util_get_short_char(pN[0]);

               /* if this character is not supported by SFN, set lossy flag */
               if ((c == '_') && (!(compASCII(pN, 0, '_'))))
               {
                  LossyFlag++;
                  LossyFlag |= SKIP_MATCH_SFN;  // skip SFN matching in SearchFile()
               }

               *pF++ = c;
            }
            else  /* space */
            {
               LossyFlag++;
               LossyFlag |= SKIP_MATCH_SFN;  // skip SFN matching in SearchFile()
            }
         }
         /*------ Non-ASCII character ------*/
         else
         {
            LossyFlag++;

            /* there is no space to store WCHAR */
            if ((encoding_length > 1) && (pF - ShortName) >= 10)
           	{
               LossyFlag |= SKIP_MATCH_SFN;
               break;
            }

            wide_c = fs_util_uni_to_native(*(kal_uint8 *)(pN) | (*(kal_uint8 *)(pN + 1) << 8));

            #ifndef __FS_NATIVE_ENCODING_TRANSPARENT__

            /* if failed to translate UCS2 to Native, skip SFN matching in SearchFile()*/
            if (wide_c == 0xFFFF)
            {
               wide_c = L'_';
               LossyFlag |= SKIP_MATCH_SFN;  // skip SFN matching in SearchFile()
               // Note: the conversion is failed, the output short name is wide_c & 0xFF = '_'
            }
            else if (encoding_length == 1)
            {
               wide_c = (WCHAR)fs_util_gen_friendly_char((char)wide_c);
               LossyFlag |= (INC_SHORT_NAME | SKIP_MATCH_SFN);
            }
            else if (encoding_length > 1)  { // copy 2-bytes native character to native SFN buffer
               *pF++ = wide_c >> 8;
            }

            #endif /* !__FS_NATIVE_ENCODING_TRANSPARENT__ */

            /*
             * If __FS_NATIVE_ENCODING_TRANSPARENT__ is defined, UnicodetoNative()
             * will return valid ASCII char, thus we only need to append one byte.
             */

            *pF++ = wide_c & 0xff;
         }

         pN += 2;
      }

      /* if the length of extension name is longer than 3, set lossy flag. */
      if ((pN[0] || pN[1]) && !(compASCII(pN, 0, '\\')))
      {
         /*
          * Set INC_SHORT_NAME to enforce the default SFN is XXX~1.XXX when creating
          * a file.
          *
          * Otherwise, file creation will be failed if
          * Step 1. Create a.tiff (OK)
          * Step 2. Create a.tif  (Fail because SFN "A.TIF" is created in step 1,
          *         FS_FILE_EXISTS will be returned in SearchFile().
          *                                                    - W09.48 Stanley Chu -
          */

         LossyFlag++;
         LossyFlag |= (INC_SHORT_NAME | SKIP_MATCH_SFN);
      }
   }

   // check the 1st byte, convert it if it is a special mark for FAT
   if (ShortName[0] == 0xE5) ShortName[0] = 0x05; // use 0x05 instead of 0xE5

   return LossyFlag;
}
/*******************************************************************//**
 * Match two short file names (native/ASCII encoding) up to '\' or end-of-string.
 *
 * @par Category:
 * File System
 *
 * @par ChangeLog:
 * W09.04: Add one condition to exit matching loop: "When maximum length of SFN is reached". (Stanley Chu)
 *
 * @note
 * This function is only referenced by SearchFile()
 **********************************************************************/
int FNamesMatch(const char * N1, const char * N2)
{
   char c1 = 0, c2, c0;
   int  length = 11;  // maximum length of a short file name

   /*------------------------------------------------------
    * Condition for exiting matching loop:
    * 1. Two continuous NULL (current and previous characters) are encountered.
    * 2. Current character is not matched.
    * 3. Maximum length of a short file name is reached.
    *------------------------------------------------------*/

   do {
      c0 = c1;  // get previous character
      c1 = fs_util_toupper(*N1++);
      if (c1 == '\\') c1 = '\0';
      c2 = fs_util_toupper(*N2++);
      if (c2 == '\\') c2 = '\0';
   } while ((c1 || (c0 & 0x80)) && (c1 == c2) && (--length)); // for Thai encoding issues: 0xA8 0x00 0xA8 0x00 ...

   return c1 == c2;
}

/*-----------------------------------*/
int RTFAPI WFNamesMatch(const char * N1, const char * N2)
// match file name components in unicode, i.e. up to '\' or end-of-string
// operation on wide character string.
{
   WCHAR c1, c2;

   do {
      c1 = isASCII(N1,0) ? (WCHAR)fs_util_toupper(N1[0]) : *(WCHAR *)N1;
      N1+=2;
      if (c1 == 0x5c) c1 = 0;
      c2 = isASCII(N2,0) ? (WCHAR)fs_util_toupper(N2[0]) : *(WCHAR *)N2;
      N2+=2;
      if (c2 == 0x5c) c2 = 0;
   } while (c1 && (c1 == c2));

   return c1 == c2;
}

/*-----------------------------------*/
/* Note that FileName is expected to be a unicode stream */
int RTFAPI SearchFile(RTFile * f, UINT Flags, const char * FileName, RTFDirLocation * DSR_Hint)
// if path not found -> exception
// if file not found, returns 0, else 1
// if 0, the file's parent is opened
// update DirPos, DirEntry, and FullName in f->
// [X:][\][Path\][Path\]file (Unicode format)
{
   RTFDirLocation       DSR = { 0 };
   const RTFDOSDirEntry *dir_entry;
   const char           *inputName = FileName;
   char                 *pFull = f->FullName;
   BYTE                 CheckSum = 0;
   kal_bool             SkipMatchSFN;
   kal_bool             ApplyDSRHint;
   int                  LFNIndex;
   char                 nativeSFN[12], originSFN[12]; /* [Memo] 12 = 8 + . + 3 */
   int                  SearchCount = 0; // the number of directory entries traversed
   kal_uint32           start_time = 0, end_time = 0;
   const char           *ppN;
   const char           *pppN;
   #ifdef __FS_OPEN_HINT__
   kal_uint8            internal_hint = 0;
   kal_uint8            path_idx      = 0;
   kal_uint8            level         = 0;
   kal_uint8            new_hint      = 0;
   #endif

   #ifdef __FS_OPEN_HINT__
   if (DSR_Hint && MTIsInternalHint(DSR_Hint))
   {
      internal_hint = 1;
      path_idx = MTHintGetIndex(DSR_Hint);
      level    = MTHintGetLevel(DSR_Hint);
      new_hint = MTIsNewHint(DSR_Hint);
   }
   #endif

#ifndef __FS_CARD_DOWNLOAD__
    // abort check
    RTFileCheck_Aborted(f);
#endif

   /* in "?:\" case, move inputName to '\' */
   /* [Memo] inputName
    *
    *        [X][:][\][.][\][D][i][r][\][.][\][D][i][r][\][A][B][C][.][e][x][t]
    *         * --> *
    */
   if ( (inputName[0]||inputName[1]) && compASCII(inputName, 1, ':'))
      inputName += 4;

   /* copy drive's current dir to f->FullName */
   /* [Memo] f->FullName
    *
    *        [X][:][\][D][i][r]
    *         *
    */
   fs_util_dchar_strcpy(pFull, f->Drive->CurrDir);
/*
 * Step 1
 *      Setup starting path to search
 */

   /* absolute path => start from root directory */
   if (compASCII(inputName, 0, '\\'))
   {
       /* [Memo] inputName
        *
        *        [X][:][\][.][\][D][i][r][\][.][\][D][i][r][\][A][B][C][.][e][x][t]
        *               *
        */
      MakePseudoRootDirEntry(f->Drive, &f->DirEntry);

      /* skip '\' in FileName */
      inputName += 2;
      /* [Memo] inputName
       *
       *        [X][:][\][.][\][D][i][r][\][.][\][D][i][r][\][A][B][C][.][e][x][t]
       *                  *
       */

      /* let f->FullName be "X:\", and skip "X:\" */
      pFull += 6;
      pFull[0] = '\0';
      pFull[1] = '\0';

      /* [Memo] f->FullName
       *
       *        [X][:][\][D][i][r]
       *         *
       *                  -
       *   =>   [X][:][\][0][i][r]
       *                  *
       */

   }
   /* it's a relative path */
   else
   {
      /* start from CurrDirEntry */
      f->DirEntry = f->Drive->CurrDirEntry;// TODO: replace with memcpy
      pFull += fs_util_dchar_strlen(pFull);
      /* [Memo] f->FullName
       *
       *        [X][:][\][D][i][r]
       *         *   --------->    *
       *        &1
       */

   }

LABLE_NextDir:

/*
 * Step 2
 *      Check if complete criteria matched
 */

{
   /*
    * inputName now has following possibility,
    * 1. points to '\' after last matched component (like "\ABC[\XXX]")
    * 2. NULL if inputName is terminated. (the last component of FileName is matched, or FileName is "X:\")
    * 3. points to the first component if search is just beginning.
    *        [X][:][\][.][\][D][i][r][\][A][B][C][.][e][x][t]
    *                  *
    */

   /* if inputName is NULL, we're done! (note that if FileName = "X:\", we will return 1 here) */
   if (inputName == NULL)
   {
      if (DSR_Hint)
      {
         MTHintGen(DSR_Hint, &DSR, f); // fill hint info in DSR_Hint
      }

      fs_util_trace_info2(TRACE_GROUP_9 , FS_TRC_RTF_SEARCHFILE, RTF_SEARCH_RET_FILE, __LINE__, NULL);

      return 1;
   }

   /* inputName is not terminated */

   /* skip "." and multiple "\" from inputName. Case like "\.\" will be skipped here~ */
   while ( WFNamesMatch((char *)inputName, (char *)dchar_dot) || compASCII(inputName, 0, '\\') )// || compASCII(inputName, 0, ' '))
      inputName += 2;
   /* [Memo] inputName
    *  1st round:
    *        [X][:][\][.][\][D][i][r][\][.][\][D][i][r][\][A][B][C][.][e][x][t]
    *                  * --> *
    * _______________________________________
    *  2nd round:
    *        [X][:][\][.][\][D][i][r][\][.][\][D][i][r][\][A][B][C][.][e][x][t]
    *                                    * --> *
    */


   /* now inputName points to the first character of next component or NULL */

   /* then check inputName again. If inputName is terminated, we are done! */
   if ( compASCII(inputName, 0, '\0') )
   {
      if (DSR_Hint)
      {
         MTHintGen(DSR_Hint, &DSR, f); // fill hint info in DSR_Hint
      }

      fs_util_trace_info2(TRACE_GROUP_9, FS_TRC_RTF_SEARCHFILE, RTF_SEARCH_RET_FILE, __LINE__, NULL);

      return 1;
   }

   /* add '\' in f->FullName's tail, and let pFull skip '\' */
   if ( !compASCII(pFull, -1, '\\'))
   {
       /* [Memo] f->FullName
        *
        *  after &1                        +
        *               [X][:][\][D][i][r][\]
        *                                  *
        */
      setASCII(pFull, 0, '\\');
      pFull += 2;
   }


   /* if last matched name is NOT a DIR, search can't be continued, raise PATH_NOT_FOUND */

   /* [Memo]
    *
    *     1st round: it could be pseudo root or current dir
    */

   if ((f->DirEntry.Dir.Attributes & RTF_ATTR_DIR) == 0)
   {
//      fs_util_trace_err_noinfo(RTF_PATH_NOT_FOUND);
      XRAISE(RTF_PATH_NOT_FOUND);
   }

   /*
    * if there is only one component left (file name, without '\'), and we are searching the parent,
    * return 0 (not found, but parent found)
    */
       /* [Memo] inputName like the following, but might not in 1st round
        *
        *        [X][:][\]...[\][A][B][C][.][e][x][t]
        *                        *
        */

   if ((Flags & SEARCH_PARENT) && (fs_util_dchar_strchr(inputName, (int)'\\') == NULL))
   {
      fs_util_trace_info2(TRACE_GROUP_9, FS_TRC_RTF_SEARCHFILE, RTF_SEARCH_RET_PARENT, __LINE__, NULL);
      goto Return0; // TODO: RTF_SEARCH_RET_PARENT
   }
}

/*
 * Step 3
 *      Set-up start point of search
 */
{
   /* now we start to search in last matched directory */
   f->DirEntry.DirCluster = FIRST_FILE_CLUSTER(f->DirEntry.Dir);

    /*
     * check if directory entry is corrupted.
     *
     * normally FirstCluster should has a value
     */

    if (f->DirEntry.DirCluster == 0)
    {
        fs_util_trace_err_noinfo(FS_BAD_DIR_ENTRY);
        fs_util_trace_info0(TRACE_ERROR | MT_TRACE_INFO_WSTR, FS_INFO_DISK_ERROR, f->FullName);
        XRAISE(RTF_BAD_DIR_ENTRY);
    }

   ApplyDSRHint = KAL_FALSE;

   /* set start line for searching */
   if (DSR_Hint && DSR_Hint->Cluster)
   {
      #ifdef __FS_OPEN_HINT__
      if (internal_hint) // level should be > 0 here (DSR_Hint->Cluster > 0), or something wrong!
      {
         for (LFNIndex = 0; LFNIndex < level - 1; LFNIndex++)
         {
            // now inputName must on a WCHAR. Goto the nearest L'\\'
            while (*(WCHAR*)inputName && *((WCHAR*)inputName) != L'\\')/* [Memo] memory copy */
            {
               *(WCHAR*)pFull = *(WCHAR*)inputName;
               inputName += sizeof(WCHAR);
               pFull += sizeof(WCHAR);
               /* [Memo]
                *   inputName
                *   case 1:  [X][:][\][.][\][D][I][R][\][A][B][C][.][e][x][t]
                *                                        *->*
                *   case 2:  [A][B][C][.][e][x][t]
                *             *->*
                *   case 3:  [X][:][\][.][\][D][I][R][\][.][\][A][B][C][.][e][x][t]
                *                            *->*
                *   case 4:  [D][I][R][\][.][\][A][B][C][.][e][x][t]
                *             *->*
                *   f->FullName
                *                                    +
                *   case 1/2:  [X][:][\][D][I][R][\][A]
                *                                 *->*
                *                        +
                *   case 3/4:  [X][:][\][D]
                *                     *->*
                */

            }

            // add a L'\\' to the end of f->FullName
            /* [Memo]
             *   f->FullName
             *                                                            +
             *   case 1/2:     [X][:][\][D][I][R][\][A][B][C][.][e][x][t][\]
             *                                                         *->*
             *                                 +
             *   case 3/4:  [X][:][\][D][I][R][\]
             *                              *->*
             */
            *(WCHAR*)pFull = L'\\';
            pFull += sizeof(WCHAR);

            /*
             * Now inputName must on L'\\' or NULL.
             * Skip "\.\" and multiple L'\\'. Then go to the 1st WCHAR of
             * next level or don't move if it is already on NULL.
             */
                /* [Memo]
                 *   inputName
                 *   case 1:  [X][:][\][.][\]...[\][A][B][C][.][e][x][t]
                 *                                                       *
                 *   case 2:  [A][B][C][.][e][x][t]
                 *                                  *
                 *   case 3:  [X][:][\][.][\][D][I][R][\][D][I][R][\][.][\][A][B][C][.][e][x][t]
                 *                                                 *
                 *   case 4:  [D][I][R][\][.][\][A][B][C][.][e][x][t]
                 *                      *
                 */

            while ((*(WCHAR*)inputName == L'.' && *(WCHAR*)(inputName + sizeof(WCHAR)) == L'\\') ||
            	    *(WCHAR*)inputName == L'\\')
               inputName += sizeof(WCHAR);
         }

         // add NULL to the end of f->FullName
         *(WCHAR*)pFull = 0;
         /* [Memo]
          *   f->FullName
          *                                                            -
          *   case 1/2:     [X][:][\][D][I][R][\][A][B][C][.][e][x][t][0]
          *                                                            *
          *                                 -
          *   case 3/4:  [X][:][\][D][I][R][0]
          *                                 *
          */

         f->DirEntry.DirCluster = MTHintGetDirCluster(DSR_Hint);/* [Memo] apply hint's DirCluster, maybe there is value, or not */

         ApplyDSRHint = KAL_TRUE;
      }
      else
      #endif /* __FS_OPEN_HINT__ */
      {
         if (((RTFFileOpenHint*)DSR_Hint)->Stamp == OpenHintStamp &&
             ((RTFFileOpenHint*)DSR_Hint)->Drive == (UINT)f->Drive &&
             ((RTFFileOpenHint*)DSR_Hint)->SerialNumber == f->Drive->SerialNumber)
         {
            // move inputName to the last component of inputName
            ppN = inputName;
            pppN = NULL;
            end_time = (kal_uint32)pFull;  // preserve origianl pFull

            /* [Memo]
             *   inputName
             *                            *
             *   case 1:  [X][:][\][.][\][D][I][R][\][A][B][C][.][e][x][t]
             *                            3        2
             *             *
             *   case 2:  [A][B][C][.][e][x][t]
             *                                  2
             *                            *
             *   case 3:  [X][:][\][.][\][D][I][R][\][.][\][A][B][C][.][e][x][t]
             *                            3        2
             *             *
             *   case 4:  [D][I][R][\][.][\][A][B][C][.][e][x][t]
             *             3        2
             */

            while ((inputName = fs_util_dchar_strchr(inputName, '\\')) != 0)
            {
               // copy folder name in this level to f->FullName (use start_time, end_time temporarily)

               end_time = (kal_uint32)pFull;  // preserve origianl pFull

               for (start_time = (kal_uint32)ppN; start_time < (kal_uint32)inputName;)
               {
                   /* [Memo]
                    *   inputName
                    *                            *
                    *   case 1:  [X][:][\][.][\][D][I][R][\][A][B][C][.][e][x][t]
                    *                            3        2
                    *             *
                    *   case 2:  [A][B][C][.][e][x][t]
                    *                                  2
                    *                            *
                    *   case 3:  [X][:][\][.][\][D][I][R][\][.][\][A][B][C][.][e][x][t]
                    *                            3        2
                    *             *
                    *   case 4:  [D][I][R][\][.][\][A][B][C][.][e][x][t]
                    *             3        2
                    *
                    *   f->FullName
                    *                        +  +  +  <-- 3 to 2
                    *   case 1/3:  [X][:][\][D][I][R]
                    *                                 *
                    *                              +  +  +  +  +  +  +   <-- 3 to 2
                    *   case 2/4:  [X][:][\]...[\][A][B][C][.][e][x][t]
                    *                                                   *
                    */

                  *pFull++ = *(char*)start_time++;
                  *pFull++ = *(char*)start_time++;
               }

               // add '\' in f->FullName's tail
               if (!compASCII(pFull, -1, '\\'))
               {
                   /* [Memo]
                   *   f->FullName
                   *                                 +
                   *   case 1/3:  [X][:][\][D][I][R][\]
                   *                                    *
                   *                                                   +
                   *   case 2/4:  [X][:][\]...[\][A][B][C][.][e][x][t][\]
                   *                                                      *
                   */

                  setASCII(pFull, 0, '\\');
                  pFull += 2;
               }

               // skip any " ", ".", and multiple "\"
               /* [Memo]
                *   inputName
                *                            *
                *   case 1:  [X][:][\][.][\][D][I][R][\][.][\][A][B][C][.][e][x][t]
                *                            3                 2
                *             *
                *   case 2:  [D][I][R][\][.][\][A][B][C][.][e][x][t]
                *             3                 2
                */

               while ( WFNamesMatch((char *)inputName, (char *)dchar_dot) || compASCII(inputName, 0, '\\')) // || compASCII(inputName, 0, ' ') )
                  inputName += 2;

               pppN = ppN;
               ppN = inputName;
            }

            if(ppN && *ppN == 0) // case "\\(NULL)"
            {
               inputName = pppN;
               pFull = (char*)end_time; // restore pFull to last level
            }
            else // normal case
            {
               inputName = ppN; // pFull does not need change
            }

            ApplyDSRHint = KAL_TRUE;
         }
         else // stamp or drive or serial number is invalid, search from the top of a folder
         {
            ApplyDSRHint = KAL_FALSE;
         }
      }
   }
   else // DSR_Hint is invalid
   {
      ApplyDSRHint = KAL_FALSE;
   }

   if (ApplyDSRHint == KAL_TRUE)
   {
      dir_entry = StartDirSearch(f->Drive, DSR_Hint->Cluster, DSR_Hint->Index, &DSR);
   }
   else
   {
      dir_entry = StartDirSearch(f->Drive, f->DirEntry.DirCluster, 0, &DSR);
   }


   /* [Memo]
   *   f->FullName
   *                               -
   *   case 1:  [X][:][\][D][I][R][0]
   *                               *
   *                                                 -
   *   case 2:  [X][:][\]...[\][A][B][C][.][e][x][t][0]
   *                                                 *
   */
   setASCII(pFull, 0, '\0'); // add a tail to f->FullName
}

/*
 * Step 4
 *      Generate SFN for matching
 */
{
// TODO: should not do Step 4 unless dir_entry != NULL

   SkipMatchSFN = KAL_FALSE;

   // inputName[] Generate ShortFileName formats into nativeSFN[] (Native encoding) and originSFN[] (Leave it as-is)
   // nativeSFN[] and originSFN[] will be compared to the ShortFileName entry found from DIR search loop.
   // If the LFN => SFN convertion lossy, set SkipMatchSFN = KAL_TRUE
   {
      int idx = 0;
      int idx1 = 0, idx2 = 0;

      while(idx < 12)
      {
         nativeSFN[idx] = 0x20;
         originSFN[idx]= 0x20;
         idx++;
      }
      if ( fs_util_dchar_strcmp(inputName, (char *)dchar_dot_dot) == 0 )
      {
         //strcpy(nativeSFN, "..         ");
         nativeSFN[0] = 0x2e;
         nativeSFN[1] = 0x2e;
         nativeSFN[11] = 0x0;
         originSFN[0] = 0x0;
         goto StartRetrieveDIREntry;
      }
      else if ( fs_util_dchar_strcmp(inputName, (char *)dchar_dot) == 0 )
      {
         //strcpy(nativeSFN, ".          ");
         nativeSFN[0] = 0x2e;
         nativeSFN[11] = 0x0;
         originSFN[0] = 0x0;
         goto StartRetrieveDIREntry;
      }

      /*------------------------------------------------------------------------------
       * We don't make rules for the encoding of "FileName" except that every character
       * must occupy 2 bytes, thus we try every possible encoding here!
       *------------------------------------------------------------------------------*/

      /*------ TRY 1: Unicode encoding ------*/

      // formal short name algo (Special characters , convert and compare , eg.  1+1 )
      idx = GenerateShortName(inputName, nativeSFN);

      #ifdef __FS_NATIVE_ENCODING_TRANSPARENT__
      if (idx > 0)
      {
         /*
          * If __FS_NATIVE_ENCODING_TRANSPARENT__ is defined, FS will use formula to
          * generate valid ASCII char for any non-ascii unicode wchar.

          * Since the generated ASCII char is NOT unique to every non-ascii unicode,
          * we must skip SFN matching in SearchFile() to prevent incorrect matching result
          * due to duplicated SFN generated by GenerateShortName().
          *
          * For example.
          * Step 1. Create LFN: "XYZ" (XYZ are non-ASCII), SFN: "ABC~1" (OK)
          * Step 2. Create "ABC~1" (Failed because ABC~1 is existed).
          */
         SkipMatchSFN = KAL_TRUE;
         goto StartRetrieveDIREntry;
      }
      #endif /* __FS_NATIVE_ENCODING_TRANSPARENT__ */

      if (idx & SKIP_MATCH_SFN)
      {
         // lossy flag detected, raise SkipMatchSFN , But need validate in next bracket
         nativeSFN[0] = 0;
         SkipMatchSFN = KAL_TRUE;
      }

      /*------ TRY 2: Native encoding ------*/

      // Direct short name algo (API pass previous taken short name, bypass encoding and go through , eq. XYZ~1.TXT )
      {
         int non_ascii_flag = 0;
         int last_dot_pos = 0;
         idx1     = 0; // position to inputName[]     (input)
         idx2     = 0; // position to originSFN[] (output)

         while((idx2 < 11) && ((*(inputName + idx1) != 0) || (*(inputName + idx1 + 1) != 0)))
         {
            if((*(inputName + idx1) == 0x5C) && (*(inputName + idx1 + 1) == 0x0)) // ascii : back slash '\'
               break;
            if((*(inputName + idx1) == 0x2E) && (*(inputName + idx1 + 1) == 0x0)) // ascii : dot '.'
            {
               // fill-in space until filename portion reach 8 bytes
               while(idx2 < 8)
               {
                  originSFN[idx2] = 0x20;
                  idx2++;
               }

               if (last_dot_pos != 0) // dot hit again ,
               {
                  // don't need to compare SFN, originSFN[0] = 0x0; (let last_dot_pos > 8 to assign originSFN[0] = 0x0 later)
                  last_dot_pos += idx2;
                  break;
               }
               else               // dot hit once , last_dot_pos must be 8 to pass criteria
               {
                  last_dot_pos = idx2;
               }
            }
            // for non-ascii wide character. Note an example Thai encoding : 0xA8 0x00 0xA8 0x00 ... (ASCII code range: 0x00 ~ 0x7F)
            else if( (inputName[idx1] & 0x80) || (inputName[idx1 + 1] != 0x0))
            {
               // raise flag ! non-ascii character detected !
               non_ascii_flag ++;

               // copy this wchar to originSFN[]
               originSFN[idx2] = *(inputName + idx1);
               originSFN[idx2 + 1] = *(inputName + idx1 + 1);
               idx2 += 2;
            }
            // others , must be ascii
            else
            {
               // copy this char to originSFN[] (note only 1 byte is copied!)
               originSFN[idx2] = *(inputName + idx1);
               idx2++;
            }

            /* always increase idx1 by 2 because inputName(FileName) must be wide character string */
            idx1+=2;
         }

         // check if inputName[] (1) multi-dot  (2) dot at > 8th character (3) filename portion's length > 8 without any dot detected
         if ( (last_dot_pos > 8) || (last_dot_pos == 0 && idx2 > 8) )
         {
            // Don't need to compare originSFN[] string
            originSFN[0] = 0x0;
         }
         // if there are non-ascii characters...
         else if ( non_ascii_flag != 0 )
         {
            /* if inputName[] string ended, even though there are non-ascii characters, SFN matching is still required */
            if (  ((*(inputName + idx1) == 0) && (*(inputName + idx1 + 1) == 0))  // NULL
               || ((*(inputName + idx1) == 0x5C) && (*(inputName + idx1 + 1) == 0))   // '\'
               )
            {
               // invert SkipMatchSFN to compare originSFN[] string with SFN
               SkipMatchSFN = KAL_FALSE;

               /* 0xE5 special char will be treated as deleted */
               if (originSFN[0] == 0xE5)
                  originSFN[0] = 0x05;
            }
            else
            {
               // Don't need to compare originSFN[] string
               originSFN[0] = 0x0;
            }
         }
         else
         {
            // it's enough to just compare nativeSFN[] string with SFN , skip originSFN[] string
            originSFN[0] = 0x0;
         }
      }
      nativeSFN[11]  = 0x00;
      originSFN[11] = 0x00;
   }
}

StartRetrieveDIREntry:

/*
 * Step 5.
 *      Start search in current directory (last matched component)
 */
{
   LFNIndex = -1;

   /* retrieve directory entries to compare */
   while (dir_entry != NULL)
   {
      int Kind = EntryType(dir_entry);
#ifndef __FS_CARD_DOWNLOAD__
      if(start_time == 0)
      {
          kal_get_time(&start_time);
      }

      SearchCount++;

#endif /* __FS_CARD_DOWNLOAD__ */

      if ((SearchCount & 0x000003FF) == 0)  // print log every 1024 entries
      {
         fs_util_trace_info1(TRACE_ERROR, FS_INFO_DIR_ENTRY_WALKED, SearchCount, NULL);
      }

      if (Kind == NeverUsed)
         break;  // file not found
      else if (Kind == Lfn)
      {
         const LFNDirEntry * LD = (void*) dir_entry;

         if (LD->Ord & 0x40) // it's the start of an LFN /* [Memo] Nth Long entry = LAST_LONG_ENTRY(0x40) | N */
         {
            // see if it fits
            char * Limit;

            /* get LFN entries count */
            LFNIndex = LD->Ord & 0x3F; /* [Memo] ex: 0x42 & 0x3F --> 2, so it's the 2nd lfn entry of this dir */
            CheckSum = LD->CheckSum;

            /* temporarily set LongPos to this directory entry */
            f->DirEntry.LongPos = DSR;

            /* check if current length of path + LFN fits in spec */
            /* [Memo]
             *  1) 13 * 2-> there is 13 chars in one LFN entry
             *  2) LFNCharCount -> to determine total char numbers in Name1 & Name2 & Name3
             */

            // TODO: 2 --> sizeof(WCHAR)
            Limit = pFull + (LFNIndex-1)*13*2 + 2*LFNCharCount(LD);

            if (Limit > (f->FullName+RTF_MAX_PATH-1) || Limit < pFull)
            {
               LFNIndex = -1;
            }
            else
            {
               Limit[0] = '\0';  // terminate the long name
               Limit[1] = '\0';
            }
         }

         if ((LD->CheckSum != CheckSum) || (LFNIndex != (LD->Ord & 0x3F)) || (LFNIndex <= 0))
         {
            LFNIndex = -1;
         }
         else
         {
            CopyLFN(pFull + --LFNIndex * 26, LD);  /* copy LFN to f->fullName */
      }


      }
      else if ((Kind == InUse) &&
               (((dir_entry->Attributes & ~RTF_ATTR_ARCHIVE) == RTF_ATTR_VOLUME) ==
                ((Flags & SEARCH_LABEL) == SEARCH_LABEL)))
      {
         // check against LFN first
         /* [Memo] reuse "Match" */
         int Match = (LFNIndex == 0) && (CheckSum == ShortNameCheckSum((const BYTE*) dir_entry->FileName));
         int length;

         if (!Match)
         {
            /* LFN does NOT exist or LFN is not belong to this file */
            LFNIndex = -1;
         }
         else
         {
            /* compare LFN and FileName up to '\' or end-of-string */
            Match =  WFNamesMatch(pFull, inputName);
         }

         /* LFN is NOT matched or LFN does not exist, start to compare SFN here */
         if (!Match)
         {
            if(SkipMatchSFN) goto SearchContinue;

            /* Copy SFN in directory entry into pFull */
            memcpy(pFull, (const char *)dir_entry->FileName, 8);
            memcpy(pFull + 8, (const char *)dir_entry->Extension, 3);
            pFull[11]='\0';

            Match = FNamesMatch(pFull, nativeSFN);

            if(!Match)
               Match = FNamesMatch(pFull, originSFN);

            /* SFN matched! */
            if (Match)
            {
               /* get length of dir/file name */
               if ( fs_util_dchar_strchr(inputName, 0x5c) )
                  length = fs_util_dchar_strlen(inputName) - fs_util_dchar_strlen(fs_util_dchar_strchr(inputName, 0x5c));
               else
                  length = fs_util_dchar_strlen(inputName);

               pFull[length] = pFull[length + 1] = '\0';

               /* append dir/file name (given by argument, NOT SFN) to f->fileName (WITHOUT '\') */
               fs_util_dchar_strncpy(pFull, inputName, length);
            }
         }

         /*-------------------- LFN or SFN matched! ----------------------*/
         if (Match == 1)
         {
            if (WFNamesMatch((char *)inputName, (char *)dchar_dot_dot) && compASCII(inputName, 1, '.') && (FIRST_FILE_CLUSTER(*dir_entry) == 0))  // ".." to root
               MakePseudoRootDirEntry(f->Drive, &f->DirEntry);
            else
            {
               /* copy matched directory entry to file structure */
               f->DirEntry.Dir = *dir_entry;
               f->DirEntry.ShortPos = DSR;

               /* if LFN NOT matched or NOT found, set LongPos.Cluster to 0 */
               if (LFNIndex != 0)
                  f->DirEntry.LongPos.Cluster = 0;
            }

            /* decide to go upper or deeper layer to continue searching */

            /* if inputName starts with "..", goto upper layer */
            //if (compASCII(inputName, 0, '.') && compASCII(inputName, 1, '.'))
            if (fs_util_dchar_strcmp(inputName, (char *)dchar_dot_dot) == 0)
            {
               /* delete tail of pFull */
               setASCII(pFull, -1, '\0');

               /* locate last '\' in new pFull */
               pFull = fs_util_dchar_strrchr(f->FullName, '\\');
               if (pFull == NULL)
               {
                  fs_util_trace_err_noinfo(RTF_PATH_NOT_FOUND);

                  XRAISE(RTF_PATH_NOT_FOUND);
               }

               /* if case "X:\", let pFull point to "X" */
               if ((pFull - 3*2) < f->FullName)
                  pFull += 2;

               /* goto upper layer */
               setASCII(pFull, 0, '\0');
            }
            else
            {
               #ifdef __FS_OPEN_HINT__
               if (internal_hint)
               {
                  if (new_hint)
                  {
                     // generate a new location for this hint
                     MTHintGen(DSR_Hint, &DSR, f);
                     MTHintNew(path_idx, level, DSR_Hint, f, (WCHAR*)pFull);

                     // update new level to stamp
                     MTHintSetLevel(DSR_Hint, level + 1);
                  }

                  // clear DSR_Hint to prevent being used in next level
                  DSR_Hint->Cluster = 0;
               }
               #endif

               /* goto deeper layer */
               pFull += fs_util_dchar_strlen(pFull);
            }

            /* move inputName (FileName) to the closest '\' */
            inputName = fs_util_dchar_strchr(inputName, '\\');

            /* goto next string to continue searching */

            #ifdef __FS_OPEN_HINT__
            level++;
            #endif

            goto LABLE_NextDir; /* CYLNE: [Memo] Step 2: Check if complete criteria */
         }
      }
SearchContinue: /* Optimize algo, Karen Hsu, 2004/04/28, ADD */
      if (Kind != Lfn)
         LFNIndex = -1;

      dir_entry = NextDirPrefetch(f->Drive, &DSR, 0);

      if ((SearchCount & 0x1FF) == 0)       // check once every 512 directory entry
      {
         #ifdef __FS_CARD_DOWNLOAD__
         WacthDogRestart(); // REVIEW: need to check with Carlos
         #else /* __FS_CARD_DOWNLOAD__ */

         register RTFDevice * Dev;

         //-- 1. abort check
         RTFileCheck_Aborted(f);

         //-- 2. device lock release check
         kal_get_time(&end_time);

         if ((end_time-start_time) > 400)  // 2 sec
         {
             Dev = f->Drive->Dev;

             if (Flags & SEARCH_RELEASE_LOCK)
             {
                 f->Task = kal_get_current_thread_ID();

                 UnlockDevice(Dev);
             }

             kal_sleep_task(20);        // wait for 100 ms.

             if (Flags & SEARCH_RELEASE_LOCK)
             {
                 LockDevice(Dev, 0);

                 if (f->Task != kal_get_current_thread_ID() || f->Lock == 0 || f->Valid > FS_FH_VALID)  //  > FS_FH_VALID(1) includes FS_FH_MEDIACHANGED(2), FS_FH_ABORTED(3), FS_FH_EXPORTED(4).
                 {
                     fs_util_trace_err_noinfo(RTF_INVALID_FILE_HANDLE);

                     XRAISE(RTF_INVALID_FILE_HANDLE);
                 }
             }

             start_time = 0;
         }
         #endif /* __FS_CARD_DOWNLOAD__ */
      }
   }

   /* nothing matched in this directory, searching is failed.. */

   {
      /* locate closest '\' in FileName */
      char *p1stSlash = fs_util_dchar_strchr(inputName, (int)'\\');

      /* if another '\' is found in FileName, which means we want to search a "directory" in current directory */
      if (p1stSlash != NULL)
      {
         /* if the last matched directory entry is a DIR, and only one 'directory name' is left in FileName, return 0! */
         if ( (f->DirEntry.Dir.Attributes & RTF_ATTR_DIR) && compASCII(p1stSlash, 1, 0x0) )
         {
            if ((pFull + fs_util_dchar_strlen(inputName) + 2) > (f->FullName + RTF_MAX_PATH))
            {
               fs_util_trace_err_noinfo(MT_PATH_OVER_LEN_ERROR);

               XRAISE(MT_PATH_OVER_LEN_ERROR);
            }

            /* append this name to f->fullName (even though it is not existed actually) */
            fs_util_dchar_strcpy(pFull, inputName);

            /* remove tail backslash in f->fullName */
            *(pFull + (int) ((int)p1stSlash - (int)inputName) ) = 0x0;

            fs_util_trace_info2(TRACE_GROUP_9, FS_TRC_RTF_SEARCHFILE, RTF_SEARCH_RET_PATH, __LINE__, NULL);
            return 0;
         }

         fs_util_trace_err_noinfo(RTF_PATH_NOT_FOUND);

         XRAISE(RTF_PATH_NOT_FOUND);
      }
   }

   /* if this is the last component (without tail '\'), and nothing matched in current directory, return 0! (SEARCH_FILES) */

Return0:

   // path is found, but not the file
   // complete full path name
   if ((pFull + fs_util_dchar_strlen(inputName) + 2) > (f->FullName + RTF_MAX_PATH))
   {
      // "*" or "*.*" should not be counted as part of path.
      if (!fs_util_dchar_strcmp(inputName, (char*)dchar_star) || !fs_util_dchar_strcmp(inputName, (char*)dchar_start_dot_star))
      {
         // append "*" or "*.*" for recursive engine and sort engine (replace *.* by *)
         fs_util_dchar_strcpy(pFull, (char*)dchar_star);

         return 0;
      }
      else
      {
         fs_util_trace_err_noinfo(MT_PATH_OVER_LEN_ERROR);

         XRAISE(MT_PATH_OVER_LEN_ERROR);
      }
   }

   /* append remaining FileName to f->FullName */
   fs_util_dchar_strcpy(pFull, inputName);

   return 0;
}
}



/*-----------------------------------*/
void RTFAPI FreeFTSlot(RTFile * f)
{
   memset(f, 0, sizeof(RTFile));
}

/*-----------------------------------*/
RTFHANDLE RTFAPI MakeNewFileHandle(RTFile * f)
{
   static UINT  Unique = 0;

   Unique = (Unique + 1) & UMAX;
   if (Unique == 0)
      Unique++;
   f->Unique = Unique;
   f->Valid = MT_ENUM_FH_VALID;
#ifndef __FS_CARD_DOWNLOAD__
   f->Task = kal_get_current_thread_ID();
#endif
   return (RTFHANDLE) ((f->Unique << (4*sizeof(int))) | (f - gFS_Data.FileTable));
}

/*-----------------------------------*/
extern kal_int32 GetFileHandle(RTFile *f)
{
   return (RTFHANDLE) ((f->Unique << (4*sizeof(int))) | (f - gFS_Data.FileTable));
}

/*-----------------------------------*/
void RTFAPI InitFilePointer(RTFile * f)
// set file pointer and cluster/sector/offset to 0
// to move back, you must call InitFilePointer first
// note that cluster 0 indicates unallocated space (except for the root)
{
   f->FilePointer = 0;
   f->Offset = 0;
   f->LastCluster = 0;

   /*
    * For non-FAT32 drive, only use low-word Cluster to make compatible with non-standard FirstClusterHi.
    * If a file is copied from a certain procedure (NTFS => FAT16), Windows may set FirstClusterHi as 1 for files on FAT16 drive.
    *                                                                                          - W10.41 -
    */
   if (RTFAT32 == f->Drive->FATType || RTF_ROOT_DIR == FIRST_FILE_CLUSTER(f->DirEntry.Dir))
      f->Cluster = FIRST_FILE_CLUSTER(f->DirEntry.Dir);
   else
      f->Cluster = FIRST_FILE_CLUSTER_LOW_WORD_ONLY(f->DirEntry.Dir);
}


/*******************************************************************//**
 * Commit SFN diretory entry of a specified file
 *
 * @par Category:
 * File System
 *
 * @note
 * 1. Move the file pointer and cluster/offset forward
 * 2. To move back, you must call InitFilePointer first.
 * 3. this function cannot move the file pointer beyond the allocated file size
 **********************************************************************/
void MoveFilePointer(RTFile * f, UINT Offset)
{
   kal_uint32 Ofs = f->Offset + Offset;
   #ifdef __FS_SMART_FILE_SEEKER__
   kal_uint32        next_milestone;
   kal_uint32        file_pos = f->FilePointer;
   RTFDirLocation    seek_hint = {0, 0};
   #endif

   kal_int32         fat_prefetch_size;

   if ((f->FilePointer + Offset) < f->FilePointer)
   {
      fs_util_trace_err_noinfo(RTF_FILE_TOO_LARGE);
      fs_util_trace_info2(TRACE_ERROR, FS_ERR_MOVEFILEPTR_WRAP_AROUND, f->FilePointer, Offset, NULL);

      XRAISE(RTF_FILE_TOO_LARGE);
   }

   #ifdef __FS_SMART_FILE_SEEKER__
   if (f->usr_ptr_type == FS_TBL_USR_PTR_MILESTONE && f->usr_ptr)
   {
      next_milestone = MTSH_GetNextStaticMilestone(f, file_pos);
   }
   else
   {
      next_milestone = 0;
   }
   #endif

   f->FilePointer += Offset;

   // root dir is a special case
   if (f->Cluster == RTF_ROOT_DIR)
   {
      f->Offset = Ofs;
      return;
   }

   while (Ofs >= f->Drive->ClusterSize)
   {
      // Exception! attempt to move beyond the last cluster
      if ((f->Cluster == 0) || (f->Cluster >= RTF_CLUSTER_CHAIN_END))
      {
         fs_util_trace_err_noinfo(RTF_FAT_ALLOC_ERROR);
         fs_util_trace_info1(TRACE_ERROR, FS_ERR_MOVEFILEPTR_BEYOND_LAST_CLUSTER, f->Cluster, NULL);

         XRAISE(RTF_FAT_ALLOC_ERROR);  // Attempt to move beyond last cluster
      }

      #ifdef __FS_SMART_FILE_SEEKER__
      if (next_milestone)
      {
         if ((file_pos >> f->Drive->ClusterShift) == (next_milestone >> f->Drive->ClusterShift))
         {
            if (f->Cluster >= RTF_CLUSTER_CHAIN_END)
               seek_hint.Cluster = f->LastCluster;
            else
               seek_hint.Cluster = f->Cluster;

            seek_hint.Index   = (file_pos >> f->Drive->ClusterShift) << f->Drive->ClusterShift;
            MTSH_AddSeekHint(f, &seek_hint, FS_SEEKHINT_TYPE_STATIC);

            next_milestone = MTSH_GetNextStaticMilestone(f, next_milestone);
         }

         file_pos += f->Drive->ClusterSize; // step to next cluster first (f->Cluster will be updated below)
      }
      #endif

      Ofs -= f->Drive->ClusterSize;

      /* f->Cluster stores current cluster number */
      f->LastCluster = f->Cluster;

      /* get cluster number of "the next" cluster, and store it to f->Cluster */
      fat_prefetch_size = GetFATPrefetchSectorsByOffset(f->Drive, Ofs);
      f->Cluster = GetClusterValue(f->Drive, f->LastCluster, fat_prefetch_size);
   }

   /*
    * Set f->Cluster to 0 to indicate current cluster is the last cluster of a file.
    * Therefore we need f->LastCluster to keep the cluster number of the last cluster!
    */
   if (f->Cluster >= RTF_CLUSTER_CHAIN_END)
      f->Cluster = 0;

   /* record byte offset within a cluster in f->Offset */
   f->Offset = Ofs;

   #ifdef __FS_SMART_FILE_SEEKER__
   if (f->usr_ptr_type == FS_TBL_USR_PTR_MILESTONE && f->usr_ptr)
   {
      // check if static hint is required
      if (next_milestone && f->FilePointer >> f->Drive->ClusterShift == next_milestone >> f->Drive->ClusterShift)
      {
         if (f->Cluster)
            seek_hint.Cluster = f->Cluster;
         else
            seek_hint.Cluster = f->LastCluster;

         seek_hint.Index   = (f->FilePointer >> f->Drive->ClusterShift) << f->Drive->ClusterShift;
         MTSH_AddSeekHint(f, &seek_hint, FS_SEEKHINT_TYPE_STATIC);
      }
   }
   #endif
}

/*-----------------------------------*/
UINT MoveFilePointerSegment(RTFile * f, UINT Offset)
// move the sector aligned file pointer and cluster/offset forward within
// one segment of contiguous clusters.
// return value is length of segment in bytes.
// the file pointer is advanced by the same value.
// this function can move less bytes then requested
{
   kal_uint32 Ofs = f->Offset + Offset;
   #ifdef __FS_SMART_FILE_SEEKER__
   kal_uint32        next_milestone = 0;
   kal_uint32        file_pos = f->FilePointer;
   RTFDirLocation    seek_hint = {0, 0};
   #endif

   kal_int32         fat_prefetch_size;

   /* [EXCEPTION] attempt to move backward */
   if ((f->FilePointer + Offset) < f->FilePointer)
   {
      fs_util_trace_err_noinfo(RTF_FILE_TOO_LARGE);
      fs_util_trace_info2(TRACE_ERROR, FS_ERR_MOVEFILEPTR_WRAP_AROUND, f->FilePointer, Offset, NULL);

      XRAISE(RTF_FILE_TOO_LARGE);
   }

   // root dir is a special case
   if (f->Cluster == RTF_ROOT_DIR)
   {
      f->FilePointer += Offset;
      f->Offset = 0;
      return Offset;
   }

   #ifdef __FS_SMART_FILE_SEEKER__
   if (f->usr_ptr_type == FS_TBL_USR_PTR_MILESTONE && f->usr_ptr)
   {
      next_milestone = MTSH_GetNextStaticMilestone(f, file_pos);
   }
   else
   {
      next_milestone = 0;
   }
   #endif
   while (Ofs >= f->Drive->ClusterSize)
   {
      #ifdef __FS_SMART_FILE_SEEKER__
      if (next_milestone)
      {
         if ((file_pos >> f->Drive->ClusterShift) == (next_milestone >> f->Drive->ClusterShift))
         {
            if (f->Cluster >= RTF_CLUSTER_CHAIN_END)
               seek_hint.Cluster = f->LastCluster;
            else
               seek_hint.Cluster = f->Cluster;

            seek_hint.Index   = (file_pos >> f->Drive->ClusterShift) << f->Drive->ClusterShift;
            MTSH_AddSeekHint(f, &seek_hint, FS_SEEKHINT_TYPE_STATIC);

            next_milestone = MTSH_GetNextStaticMilestone(f, next_milestone);
         }

         file_pos += f->Drive->ClusterSize; // step to next cluster first (f->Cluster will be updated below)
      }
      #endif

      Ofs -= f->Drive->ClusterSize;

      f->LastCluster = f->Cluster;

      // When Moving the File Pointer, the prefetch FAT buffer size should not exceed corrspond remaining file size
      fat_prefetch_size = GetFATPrefetchSectorsByOffset(f->Drive, Ofs);
      f->Cluster = GetClusterValue(f->Drive, f->LastCluster, fat_prefetch_size);

      /*
       * Case 1. If f->Cluster is the last cluster of file, which means f->Offset is located in this cluster,
       * not the end. Then this condition will be true and MoveFilePointerSegment() will
       * move file pointer to the end of this cluster only!
       *
       * This imply that in RTFWrite()'s l2 part, it will write data to cluster-aligned offset first,
       * then write other data starting from the next cluster. 2 writes may happen!
       *
       * Case 2. It is the end of this segment!
       */
      if (f->Cluster != (f->LastCluster + 1))
      {
         /* in this segment, we have walked (Offset - Ofs) bytes (the return value) */
         Offset -= Ofs;
         Ofs = 0;
      }
   }

   /* mark f->Cluster to 0 to indicate this is the last cluster of a file */
   if (f->Cluster >= RTF_CLUSTER_CHAIN_END)
      f->Cluster = 0;

   f->FilePointer += Offset;
   f->Offset = Ofs;

   #ifdef __FS_SMART_FILE_SEEKER__
   if (f->usr_ptr_type == FS_TBL_USR_PTR_MILESTONE && f->usr_ptr)
   {
      // check if static hint is required
      if (next_milestone && f->FilePointer >> f->Drive->ClusterShift == next_milestone >> f->Drive->ClusterShift)
      {
         if (f->Cluster)
            seek_hint.Cluster = f->Cluster;
         else
            seek_hint.Cluster = f->LastCluster;

         seek_hint.Index   = (f->FilePointer >> f->Drive->ClusterShift) << f->Drive->ClusterShift;
         MTSH_AddSeekHint(f, &seek_hint, FS_SEEKHINT_TYPE_STATIC);
      }
   }
   #endif

   return Offset;
}

#if defined(__FS_CACHE_SUPPORT__) && !defined(__FS_CARD_DOWNLOAD__)
#define fs_srv_get_cluster() GetBufferFAT(Drive, Sector, PrefetchSectorLength)
RTFCluster fs_srv_get_cluster_value(RTFDrive * Drive, RTFCluster Cluster, kal_uint32 Option, kal_int32 PrefetchSectorLength)
#else  // defined(__FS_CACHE_SUPPORT__) && !defined(__FS_CARD_DOWNLOAD__)
RTFCluster GetClusterValue(RTFDrive * Drive, RTFCluster Cluster, kal_int32 PrefetchSectorLength)
{
    return fs_srv_get_cluster_value(Drive, Cluster, FS_GET_CLUSTER_DEFAULT, GetBuffer);
}

#define fs_srv_get_cluster() GetBufferFunc(Drive->Dev, Sector, 0)
RTFCluster fs_srv_get_cluster_value(RTFDrive * Drive, RTFCluster Cluster, kal_uint32 Option, fs_func_get_buffer GetBufferFunc)
#endif // defined(__FS_CACHE_SUPPORT__) && !defined(__FS_CARD_DOWNLOAD__)
{
    RTFCluster Result = 0;
    kal_uint32 Sector = 0;
    kal_uint8 *FAT = NULL;
    kal_uint32 SectorShift, SectorSize;

    if ((Option == FS_GET_CLUSTER_DEFAULT) &&
        ((Cluster != 1) || (gMT_Sanity != KAL_TRUE)) &&
        ((Cluster < 2l) || (Cluster >= Drive->Clusters)))
    {
        fs_util_trace_err_noinfo(RTF_FAT_ALLOC_ERROR);
        fs_util_trace_info1(TRACE_ERROR, FS_ERR_GETCLUSTERVALUE_INVALID_IN_CLUSTER, Cluster, NULL);

        XRAISE(RTF_FAT_ALLOC_ERROR);
    }

   SectorShift=Drive->Dev->DevData.SectorShift;
   SectorSize=Drive->Dev->DevData.SectorSize;

   switch (Drive->FATType)
   {
      case RTFAT12:
      {
         kal_uint32 Pos;
         UINT       B1, B2;
         BYTE      *FATPtr;

         Pos    = Cluster + Cluster / 2;     // 0 1 3 4 6 7 9 10 12 13
         Sector = Drive->FirstFATSector + (Pos >> SectorShift);
         FATPtr = fs_srv_get_cluster();
         B1     = FATPtr[Pos & (SectorSize-1)];

         Pos++;
         Sector = Drive->FirstFATSector + (Pos >> SectorShift);
         FATPtr = fs_srv_get_cluster();
         B2     = FATPtr[Pos & (SectorSize-1)];

         Result = (Cluster & 1) ? ((B2 << 4) | (B1 >> 4)) : (((B2 & 0x0F) << 8) | B1);
         if (Result >= 0xFF7)
            Result |= 0x0FFFF000;
         FAT=(kal_uint8*)FATPtr;
         break;
      }
      case RTFAT16:
      {
         WORD * FATPtr;
         Sector = Drive->FirstFATSector + (Cluster >> (SectorShift-1));
         FATPtr = fs_srv_get_cluster();
         Result = FATPtr[Cluster & ((SectorSize >> 1)-1)];
         if (Result >= 0xFFF7)
            Result |= 0x0FFF0000;
         FAT=(kal_uint8*)FATPtr;
         break;
      }
#if !defined(__NOT_SUPPORT_FAT32__)
      case RTFAT32:
      {
         kal_uint32 * FATPtr;
         Sector = Drive->FirstFATSector + (Cluster >> (SectorShift-2));
         FATPtr = fs_srv_get_cluster();
         Result = FATPtr[Cluster & ((SectorSize >> 2)-1)] & 0x0FFFFFFF;
         FAT=(kal_uint8*)FATPtr;
         break;
      }
#endif /* __NOT_SUPPORT_FAT32__ */
      default:
         fs_err_internal_fatal(FS_ERR_CLUSTER_01, (void*)(Drive->FATType));
   }

   /* check cluster value validity, if not valid, raise FAT_ALLOC_ERROR */
   if ((Option == FS_GET_CLUSTER_DEFAULT) &&
       (Result != 0) &&
       (Result < 0x0FFFFFF7) &&
       (gMT_Sanity != KAL_TRUE) &&
       ((Result < 2) || (Result >= Drive->Clusters)))
   {
      fs_util_trace_err_noinfo(RTF_FAT_ALLOC_ERROR);
      fs_util_trace_info4(TRACE_ERROR, FS_ERR_GETCLUSTERVALUE_INVALID_OUT_CLUSTER, Cluster, Result, Result, Sector, NULL);
      fs_util_trace_info1(TRACE_ERROR, FS_INFO_DISK_ERROR2, (MT_BASE_DRIVE_LETTER + (Drive - gFS_Data.DriveTable)), NULL);
      kal_buffer_trace(TRACE_ERROR, FS_INFO_FAT_SECTOR, FS_BUFFER_SIZE, FAT);
      fs_util_native_to_uni(*FAT); // Used to Remove Build Warnings
      XRAISE(RTF_FAT_ALLOC_ERROR);
   }

   return Result;
}

#define RTF_CORE_MOUNT
/*******************************************************************//**
 * Allocate a drive
 *
 * @par Category:
 * File System
 *
 * @note
 * 1. Search drive table starting from DriveLetter, find the frist slot with NULL device ptr,
 * then allocate this slot to the specified device.
 * 2. No device access
 * 3. Device's FirstDrive is the LAST drive to be allocated!!
 *
 * @Return
 * NULL : Too many drives, this drive can't be mounted.
 * Drive: Allocated drive
 **********************************************************************/
RTFDrive * AllocateDrive(char DriveLetter, RTFDevice * Dev)
{
   RTFDrive * Drive;

   if ((DriveLetter < 'C') && (Dev->DeviceType == FS_DEVICE_FDISK))
      DriveLetter = 'C';

   while (1)
   {
      if ((DriveLetter - MT_BASE_DRIVE_LETTER) >= FS_MAX_DRIVES)
         return NULL;

      Drive = gFS_Data.DriveTable + DriveLetter - MT_BASE_DRIVE_LETTER;
      if (Drive->Dev == Dev)
         break;

      /*
       * Find the frist slot with NULL device ptr in drive table.
       * The last found drive will be FisrtDrive, and the first found drive's NextDrive will be NULL.
       */
      if (Drive->Dev == NULL)
      {
         Drive->Dev = Dev;
         Drive->NextDrive = Dev->DevData.FirstDrive;
         Dev->DevData.FirstDrive = Drive;
         break;
      }
      DriveLetter++;
   }

   Drive->MountState = NotMounted;

   return Drive;
}


/*-----------------------------------*/
static char InitLogicalDrive(char DriveLetter,
                                    RTFDevice * Dev,
                                    RTFPartitionRecord * Geometry,
                                    RTFSector PartitionSector)
// sets up a drive with informationm from a partition entry
// no device access, but the caller must have read a partition
// table or guess at the format of a floppy
{
   RTFDrive * Drive;

   Drive = AllocateDrive(DriveLetter, Dev);
   if (Drive == NULL) // can't mount, too many drives
      return DriveLetter;

   Drive->MountState = Mounted;
   Drive->Geometry = *Geometry;
   Drive->FirstSector = PartitionSector + Geometry->RelativeSector;
   return MT_BASE_DRIVE_LETTER + (Drive - gFS_Data.DriveTable) + 1; // return next drive letter
}



/*-----------------------------------*/
void CheckMedia(RTFDevice * Dev)
{
   if ((Dev->DevData.MediaRemovedReported == 0) ||
       (Dev->DevData.MediaPresent == 0))
   {
      Dev->DevData.MediaRemovedReported = 1;

      fs_util_trace_err_noinfo(RTF_MEDIA_CHANGED);
      fs_util_trace_info1(TRACE_ERROR, FS_ERR_MEDIA_NOT_PRESENT, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

      XRAISE(RTF_MEDIA_CHANGED);
   }
}

void CheckDirEntry(RTFile *f)
{
    kal_uint32 C;

    if (f->SpecialKind!=NormalFile) return;

    C=FIRST_FILE_CLUSTER(f->DirEntry.Dir);

    if ( (C == 1L) ||    // Note: The Rule Must Sync with CheckDir() at FS_SanityCheck()
         ((C < RTF_CLUSTER_CHAIN_END) && (C >= f->Drive->Clusters)) ||
         ((C != RTF_ROOT_DIR) && (C>RTF_CLUSTER_CHAIN_END+7)))   {
         fs_util_trace_err_noinfo(FS_BAD_DIR_ENTRY);
         fs_util_trace_info4(TRACE_ERROR, FS_ERR_DIRENTRY_INVALID_START_CLUSTER, C, C, f->Drive->Clusters, f->Drive->Clusters, NULL);
         fs_util_trace_info0(TRACE_ERROR | MT_TRACE_INFO_WSTR, FS_INFO_DISK_ERROR, f->FullName);
         XRAISE(RTF_BAD_DIR_ENTRY);
    }
}

void RTFAPI UnmountDevice(RTFDevice * Dev, int CloseFiles)
{
   UINT i;
   RTFile * f = gFS_Data.FileTable;
   RTFDrive * D = Dev->DevData.FirstDrive;

   /* clean ALL file table slots */
   if (CloseFiles)
      for (i=0; i<FS_MAX_FILES; i++, f++)
         if (f->Dev == Dev)
            FreeFTSlot(f);

   /* Drive: set all drives in Dev to NotMounted */
   while (D)
   {
      D->MountState = NotMounted;

   #ifndef __FS_CARD_DOWNLOAD__
      MTExpireDirCacheByDrive(D);   // expire dir cache
   #endif

      #ifdef __FS_OPEN_HINT__
      MTHintExpireByDrive(D);       // expire internal open hint
      #endif

      D = D->NextDrive;
   }

   /* discard all device's buffers */
   DiscardAllBuffers(Dev);

   // reset write protection flag because in MountDevice, write protection flag will NOT be clear.
   Dev->DeviceFlags &= ~MT_DEVICE_WRITE_PROTECT;

   /* Device: set device to NotMounted */
   Dev->DevData.MountState = NotMounted;
}

/*-----------------------------------*/
static int GetDiskGeometry(RTFDevice * Dev, RTFPartitionRecord * DiskGeometry, BYTE * MediaDescriptor)
{
   int volatile Result;
   RTFSYSFreeMutex(RTFLock);
   XTRY
      case XCODE:
         CheckMedia(Dev);
         if (Dev->DevData.MountState < Initialized)
            Result = RTF_DRIVE_NOT_READY;
         else
            if (Dev->Driver->GetDiskGeometry)
               Result = Dev->Driver->GetDiskGeometry(Dev->DriverData, DiskGeometry, MediaDescriptor);
            else
               Result = RTF_UNSUPPORTED_DRIVER_FUNCTION;
         break;
      default:
         Result = XVALUE;
         XHANDLED;
         break;
      case XFINALLY:
         RTFSYSLockMutex(RTFLock, RTF_INFINITE);
         break;
   XEND
   return Result;
}

/*-----------------------------------*/
int rtf_core_mount_device(RTFDevice * Dev, DWORD Flags)
{
   int volatile Result;
   int Status;
   RTFSYSFreeMutex((RTFMutex *)RTFLock);
   XTRY
      case XCODE:
         Dev->DevData.MediaRemovedReported = 1;
         CheckMedia(Dev);
         Dev->DevData.ErrorCondition = RTF_NO_ERROR;
         Dev->DevData.MediaDescriptor = 0;

         kal_mem_set((void *)&Dev->DevData.Geometry, 0, sizeof(Dev->DevData.Geometry));
         Dev->DevData.MountState = Initialized;

         Result = Dev->Driver->MountDevice(Dev->DriverData, Dev->DeviceNumber, Dev->DeviceType, Dev->DeviceFlags);

         if (Result < RTF_NO_ERROR)
         {
            Dev->DevData.ErrorCondition = Result;

            fs_util_trace_err_noinfo(Result);
            fs_util_trace_info1(TRACE_ERROR, FS_ERR_MOUNTDEVICE_DRIVER_MOUNT_FAIL, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

            XRAISE(Result);
         }

         Dev->DevData.ErrorCondition = RTF_NO_ERROR;

/*  SLIM
         if (Result > RTF_MIN_BUFFER_SIZE)
         {
            fs_util_trace_err_noinfo(RTF_INVALID_SECTOR_SIZE);
            fs_util_trace_info1(TRACE_ERROR, FS_ERR_MOUNTDEVICE_INVALID_SECTOR_SIZE, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

            XRAISE(RTF_INVALID_SECTOR_SIZE);
         }

         if (!fs_util_is_power_two(Result))
         {
            fs_util_trace_err_noinfo(RTF_INVALID_SECTOR_SIZE);
            fs_util_trace_info1(TRACE_ERROR, FS_ERR_MOUNTDEVICE_INVALID_SECTOR_SIZE, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

            XRAISE(RTF_INVALID_SECTOR_SIZE);
         }
*/

         /* set device's sector size to the return value of driver (MountDevice) */
         Dev->DevData.SectorSize = Result;
         Dev->DevData.SectorShift = 0;
         while ((1 << Dev->DevData.SectorShift) < Dev->DevData.SectorSize)
            Dev->DevData.SectorShift++;

         break;
      default:
         if (Flags & NO_RAISE)
         {
            Result = XVALUE;
            XHANDLED;
         }
         break;
      case XFINALLY:
         RTFSYSLockMutex(RTFLock, RTF_INFINITE);
         break;
   XEND
   if (Result >= RTF_NO_ERROR)
   {
      /*
       * NOTE: If FS_DEVICE_WRITE_PROTECTION flag is set already in gFS_DeviceList,
       * we keep it even if this device is not write protected by driver's report.
       */
      if((Status = GetDiskGeometry(Dev, &Dev->DevData.Geometry, &Dev->DevData.MediaDescriptor)) == RTF_WRITE_PROTECTION)
         Dev->DeviceFlags |= MT_DEVICE_WRITE_PROTECT;

      Dev->DevData.MountState = Mounted;
   }
   /* Reserve drive name for mount error device, Karen Hsu, 2004/03/04, ADD START */
   else
   {
      if((Status = GetDiskGeometry(Dev, &Dev->DevData.Geometry, &Dev->DevData.MediaDescriptor)) != 0)
      {
         if(Dev->DeviceFlags & MT_DEVICE_NOR_FLASH)
            NorPartition = KAL_TRUE;
         else if(Dev->DeviceFlags & MT_DEVICE_NAND_FLASH)
            NandPartition = KAL_TRUE;
      }
   }

   if (Status == MT_MSDC_NOT_PRESENT)
   {
      fs_util_trace_err_noinfo(Status);
      fs_util_trace_info0(TRACE_ERROR, FS_ERR_MOUNTDEVICE_MSDC_NOT_PRESENT, NULL);

      Dev->DevData.MountState = NotMounted;
      Result = Status;
   }
   /* Reserve drive name for mount error device, Karen Hsu, 2004/03/04, ADD END */
   return Result;
}

/*-----------------------------------*/
#define FS_MAX_AUTO_FORMAT_RETRY (1)

static char INTERN ScanPartitionTable(char volatile DriveLetter,
                                      RTFDevice * Dev,
                                      int PartitionKind)
// raises no exceptions
{
#if !defined(__FS_SLIM_EXTENDED_PARTITION__)
   kal_uint32 ExOffset = 0; /* Remove RVCT warning, Karen Hsu, 2004/11/02, MOD */
   int ExPartition = -1;   // see if we have an extended partition
#endif
   int i;
   int PrimPartitions = 0; // count primary partitions
   int DriveOffset = 0;
   RTFMasterBootRecord * MBR;
   int retry = 0;

    do
    {
        MBR = GetBuffer(Dev, 0, FS_BTYPE_SYS);

        Dev->DevData.MountState = Accessible;

        if (MBR->Signature != 0xAA55)
        {
            fs_util_trace_err_noinfo(RTF_CORRUPTED_PARTITION_TABLE);
            fs_util_trace_info2(TRACE_ERROR, FS_ERR_SCANPTABLE_MBR_SIG, MBR->Signature, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

#ifndef __FS_CARD_DOWNLOAD__

            // try to auto format device (low + high) for device with flag FS_DEVICE_AUTO_FORMAT
            if ((Dev->DeviceFlags & FS_DEVICE_AUTO_FORMAT) && (retry < FS_MAX_AUTO_FORMAT_RETRY))
            {
                // auto format will directly r/w sectors via driver. Flush and discard all buffers first.
                FlushAllBuffers(Dev);
                DiscardAllBuffers(Dev);

                DriveOffset = fs_fmt_self_format((FS_Device*)Dev, FS_DEVICE_FDISK);

                if (DriveOffset != RTF_NO_ERROR)
                {
                    XRAISE(DriveOffset);
                }

                retry++;

                continue;   // try again
            }

#endif // !__FS_CARD_DOWNLOAD__

            XRAISE(RTF_CORRUPTED_PARTITION_TABLE);
        }

        break;

    } while (1);

   Dev->DevData.MountState = HasFileSystem;

   // process primary partions first
   for (i=0; i<4; i++)
   {
      switch (MBR->PTable[i].OSType)
      {
         // primary partions with FAT12/FA16
         case 0x01:
         case 0x04: // max 32MB, 1024 cylinder
         case 0x06: // max  2GB, 1024 cylinder
         case 0x0B: // FAT-32 CHS
         case 0x0C: // FAT-32 LBA
         case 0x0E: // max 2GB, more than 1024 cylinder
               PrimPartitions++;

               if ((PrimPartitions == 1) && (PartitionKind & RTF_PARTITION_FIRST_PRIMARY) &&
                  (Dev->DeviceFlags & MT_DEVICE_CHECK_PART) && (MBR->PTable[i].BootIndicator != 0x80))
               {
                  Dev->DevData.MountState = Accessible;

                  fs_util_trace_err_noinfo(RTF_CORRUPTED_PARTITION_TABLE);
                  fs_util_trace_info2(TRACE_ERROR, FS_ERR_SCANPTABLE_BOOT_INDICATOR, MBR->PTable[i].BootIndicator, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

                  XRAISE(RTF_CORRUPTED_PARTITION_TABLE);
               }

               if (((PrimPartitions == 1) && (PartitionKind & RTF_PARTITION_FIRST_PRIMARY)) ||
                   ((PrimPartitions > 1) && (PartitionKind & RTF_PARTITION_OTHER_PRIMARY)))
                  DriveLetter = InitLogicalDrive(DriveLetter,
                                              Dev,
                                              MBR->PTable + i,
                                              0);
            break;
#if !defined(__FS_SLIM_EXTENDED_PARTITION__)
         case 0x05: // extended DOS partition max 2GB, max 1024 cylinder
         case 0x0F: // ditto, more than 1024 cylinder
            ExOffset = MBR->PTable[i].RelativeSector;
            ExPartition = i;
#endif
         default:   // ignore anything else
            break;
      }
   }

#if !defined(__FS_SLIM_EXTENDED_PARTITION__)
   if (PartitionKind & RTF_PARTITION_EXTENDED)
   {
      // Process extended partions.
      // Note that we support only one extended partition on a drive,
      // but this partition can contain any number of logical drives
      while (ExPartition != -1)
      {
         ExPartition = -1;

         MBR = GetBuffer(Dev, ExOffset + DriveOffset, FS_BTYPE_SYS);

         if (MBR->Signature != 0xAA55)
         {
            fs_util_trace_err_noinfo(RTF_CORRUPTED_PARTITION_TABLE);
            fs_util_trace_info2(TRACE_ERROR, FS_ERR_SCANPTABLE_EXT_MBR_SIG, MBR->Signature, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

            XRAISE(RTF_CORRUPTED_PARTITION_TABLE);
         }

         for (i=0; i<4; i++)
         {
            switch (MBR->PTable[i].OSType)
            {
               // primary partions with FAT12/FAT16
               case 0x01:
               case 0x04: // max 32MB, 1024 cylinder
               case 0x06: // max 2GB, 1024 cylinder
               case 0x0B: // FAT-32 CHS
               case 0x0C: // FAT-32 LBA
               case 0x0E: // max 2GB, more than 1024 cylinder
                  DriveLetter = InitLogicalDrive(DriveLetter,
                                                 Dev,
                                                 MBR->PTable + i,
                                                 ExOffset + DriveOffset);
                  break;
               case 0x05: // extended DOS partition max 2GB, max 1024 cylinder
               case 0x0F: // ditto, more than 1024 cylinder
                  if (MBR->PTable[i].RelativeSector <= DriveOffset)
                  {
                     fs_util_trace_err_noinfo(RTF_CORRUPTED_PARTITION_TABLE);
                     fs_util_trace_info2(TRACE_ERROR, FS_ERR_SCANPTABLE_RELATIVE_SECTOR, MBR->PTable[i].RelativeSector, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

                     XRAISE(RTF_CORRUPTED_PARTITION_TABLE);
                  }

                  DriveOffset = MBR->PTable[i].RelativeSector;
                  ExPartition = i;
               default:   // ignore anything else
                  break;
            }
         }
      }
   }
#endif   // !__FS_SLIM_EXTENDED_PARTITION__

   return DriveLetter;
}

/*-----------------------------------*/
static char INTERN ReserveLogicalDrive(char DriveLetter, RTFDevice * Dev)
// this is called for removable devices at startup
// it does not access the device and creates exactly one
// logical drive
{
   RTFDrive * Drive = AllocateDrive(DriveLetter, Dev);

   if (Drive == NULL)        // can't mount, too many drives
      return DriveLetter;
   else
      return MT_BASE_DRIVE_LETTER + (Drive - gFS_Data.DriveTable) + 1; // return next drive letter
}


void MountPartitions(RTFDevice * Dev)
// mount all partitions
{
   switch (Dev->DeviceType)
   {
      case RTF_DEVICE_FDISK:
         ScanPartitionTable('C', Dev, RTF_PARTITION_ALL);
         break;
      case RTF_DEVICE_FLOPPY:
         Dev->DevData.Geometry.OSType = 1;
         InitLogicalDrive(MT_BASE_DRIVE_LETTER + (Dev->DevData.FirstDrive - gFS_Data.DriveTable), Dev, &Dev->DevData.Geometry, 0);
         break;
      #ifdef DEBUG
      default:
         fs_err_internal_fatal(FS_ERR_MOUNT_01, NULL);
      #endif
   }
}

#ifndef __FS_CARD_DOWNLOAD__
static kal_int32 FS_GetBootMode(void)
{
    PW_CTRL_GET_POWERON_REASON CtrlVal;
    DCL_HANDLE pmu_handle;
    pmu_handle = DclPW_Open(DCL_PW, FLAGS_NONE);
    DclPW_Control(pmu_handle, PW_CMD_GET_POWERON_REASON, (DCL_CTRL_DATA_T *)&CtrlVal);
    DclPW_Close(pmu_handle);

    return (kal_int32)CtrlVal.powerOnReason;
}
#endif

/*-----------------------------------*/
void RTFAPI MountLogicalDrive(RTFDrive * Drive, MountStates State)
// prepares drive or device for a file open operation
// all required mounting is done, if required
// devices are identified by State == Initialized
{
   WCHAR driver_X[]={0x58, 0x3a, 0x5c, 0};  /*X:\\*/

   if (Drive->Dev == NULL)
   {
      XRAISE(RTF_DRIVE_NOT_FOUND);
   }

   XTRY
      case XCODE:
         if (Drive->Dev->DevData.MountState < Mounted)
         {
            int Result;

            if((Drive->Dev->DevData.MountState == NotMounted) &&
               (Drive->Dev->DeviceFlags & RTF_DEVICE_REMOVABLE))
            {
               Drive->MountState = NotMounted;
            }

            Result = rtf_core_mount_device(Drive->Dev, 0);

            if (Drive->Dev->DevData.MountState < Mounted)
            {
               fs_util_trace_info2(TRACE_ERROR, FS_ERR_MOUNTDRIVE_DEV_MOUNT_FAIL, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), Drive->Dev->DevData.MountState, NULL);

               XRAISE(Result);
            }
         }

         // don't get here if the device is not mounted

         if (Drive->MountState < Mounted)
         {
            MountPartitions(Drive->Dev);

            if (Drive->MountState < Mounted)
            {
               fs_util_trace_info2(TRACE_ERROR, FS_ERR_MOUNTDRIVE_DRV_MOUNT_FAIL, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), Drive->MountState, NULL);

               XRAISE(RTF_DRIVE_NOT_FOUND);
            }
         }

         /* get PBR to check if it is reasonable and fill drive structure */
         {
            RTFBootRecord * BR = GetBuffer(Drive->Dev, Drive->FirstSector, FS_BTYPE_SYS);
            RTFSector RootDirSectors;
            kal_uint32 FATSectors;
            kal_int32  FATType;

            Drive->MountState = Accessible;

            /* NearJump[0]: Both 0xEB and 0xE9 are acceptable */
            if ((BR->Signature != 0xAA55) ||
               ((Drive->Dev->DeviceFlags & MT_DEVICE_CHECK_PART) &&
               (BR->NearJump[0] != 0xE9) && (BR->NearJump[0] != 0xEB)))
            {
               fs_util_trace_info4(TRACE_ERROR, FS_ERR_MOUNTDRIVE_INVALID_FS_SIG, BR->Signature, BR->NearJump[0], fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), NULL, NULL);

               XRAISE(RTF_INVALID_FILE_SYSTEM);
            }

            if (BR->BP.BytesPerSector != Drive->Dev->DevData.SectorSize)
            {
               fs_util_trace_info2(TRACE_ERROR, FS_ERR_MOUNTDRIVE_INVALID_FS_SEC, BR->BP.BytesPerSector, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), NULL);

               XRAISE(RTF_INVALID_SECTOR_SIZE);
            }

            if (fs_util_is_power_two(BR->BP.SectorsPerCluster))
               Drive->SectorsPerCluster = BR->BP.SectorsPerCluster;
            else
               if ((BR->BP.SectorsPerCluster & 0x80) &&
                   ((BR->BP.SectorsPerCluster & 0x7F) >= 8) &&
                   ((BR->BP.SectorsPerCluster & 0x7F) <= 15))
                  Drive->SectorsPerCluster = 1 << (BR->BP.SectorsPerCluster & 0x7F);
               else
               {
                  fs_util_trace_info2(TRACE_ERROR, FS_ERR_MOUNTDRIVE_INVALID_FS_SPC, BR->BP.SectorsPerCluster, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), NULL);

                  XRAISE(RTF_INVALID_FILE_SYSTEM);
               }

            Drive->ClusterShift = 1;
            while ((1l << Drive->ClusterShift) < (1l * Drive->Dev->DevData.SectorSize * Drive->SectorsPerCluster))
               Drive->ClusterShift++;

            Drive->SPerCShift = 0;
            while ((1 << Drive->SPerCShift) < Drive->SectorsPerCluster)
               Drive->SPerCShift++;

            /* if BPB_TotalSector16 != 0, let BPB_TotalSector32 = BPB_TotalSector16 */
            if (BR->BP.SectorsOnDisk != 0)
               BR->BP.TotalSectors = BR->BP.SectorsOnDisk;

            Drive->FirstFATSector = Drive->FirstSector + BR->BP.ReservedSectors;
            Drive->FATCount = BR->BP.NumberOfFATs;
            FATType = RTFFormatGetFatType(BR, &RootDirSectors, &FATSectors, &Drive->Clusters);

            if (FATType == RTF_ERROR_RESERVED)
            {
               fs_util_trace_info2(TRACE_ERROR, FS_ERR_MOUNTDRIVE_INVALID_FS_FAT_TYPE, Drive->Clusters, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), NULL);

               XRAISE(RTF_INVALID_FILE_SYSTEM);
            }

            Drive->FATType = FATType;

            Drive->Clusters += 2;  // make that logical clusters

#if !defined(__NOT_SUPPORT_FAT32__)
            if (Drive->FATType == RTFAT32)
            {
               /* BPB_FSVer should be 0.0 */
               if (BR->BP.E._32.Version != 0)
               {
                  fs_util_trace_info2(TRACE_ERROR, FS_ERR_MOUNTDRIVE_INVALID_FS_FAT32_VER, BR->BP.E._32.Version, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), NULL);

                  XRAISE(RTF_INVALID_FILE_SYSTEM);
               }

               Drive->SectorsPerFAT = BR->BP.E._32.SectorsPerFAT;
               Drive->FirstDataSector = Drive->FirstFATSector + Drive->FATCount * Drive->SectorsPerFAT;
               Drive->FirstDirSector = BR->BP.E._32.RootDirCluster; // not a sector
               Drive->RootDirEntries = 0;
               Drive->SerialNumber = BR->BP.E._32.BPB.SerialNumber;
               Drive->InfoSector = (BR->BP.E._32.FSInfoSector != 0xFFFF) ? (Drive->FirstSector + BR->BP.E._32.FSInfoSector) : 0;
               // if FAT mirroring is disabled, pretend we only have one FAT
               if (BR->BP.E._32.Flags & 0x80)
               {
                  Drive->FATCount = 1;
                  Drive->FirstFATSector = Drive->FirstSector
                                        + BR->BP.ReservedSectors
                                        + (BR->BP.E._32.Flags & 0x0F)
                                          * BR->BP.E._32.SectorsPerFAT;
               }
            }
            else
#endif /* __NOT_SUPPORT_FAT32__ */
            {
               Drive->SectorsPerFAT = BR->BP.SectorsPerFAT;
               Drive->FirstDirSector = Drive->FirstFATSector + Drive->FATCount * Drive->SectorsPerFAT;
               Drive->FirstDataSector = Drive->FirstDirSector + RootDirSectors;
               Drive->RootDirEntries = BR->BP.DirEntries;
               Drive->SerialNumber = BR->BP.E._16.BPB.SerialNumber;
               Drive->InfoSector = 0;
            }

            // Calculate Cluster Size
            Drive->ClusterSize = 1l << Drive->ClusterShift;

            // Calculate the Data Ranges in one FAT sector (used for FAT prefetching)
            Drive->DataRangePerFATSector = 8 * SECTOR_SIZE / (Drive->FATType) * Drive->ClusterSize;

            /* make current directory as root directory */
            fs_util_dchar_strcpy(Drive->CurrDir, (char *)driver_X);
            Drive->CurrDir[0] = MT_BASE_DRIVE_LETTER + (Drive - gFS_Data.DriveTable);
            MakePseudoRootDirEntry(Drive, &Drive->CurrDirEntry);

            // do some plausibility checks

            if (BR->BP.ReservedSectors == 0)
            {
               fs_util_trace_info1(TRACE_ERROR, FS_ERR_MOUNTDRIVE_INVALID_FS_RESERVED_SEC, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), NULL);

               XRAISE(RTF_INVALID_FILE_SYSTEM);
            }

            if ((Drive->FATCount < 1) || (Drive->FATCount > 2))
            {
               fs_util_trace_info2(TRACE_ERROR, FS_ERR_MOUNTDRIVE_INVALID_FS_FAT_CNT, Drive->FATCount, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), NULL);

               XRAISE(RTF_INVALID_FILE_SYSTEM);
            }

            if (Drive->SectorsPerFAT == 0)
            {
               fs_util_trace_info1(TRACE_ERROR, FS_ERR_MOUNTDRIVE_INVALID_FS_FAT_SIZE, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), NULL);

               XRAISE(RTF_INVALID_FILE_SYSTEM);
            }

            if (Drive->SectorsPerCluster == 0)
            {
               fs_util_trace_info1(TRACE_ERROR, FS_ERR_MOUNTDRIVE_INVALID_FS_ZERO_SPC, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), NULL);

               XRAISE(RTF_INVALID_FILE_SYSTEM);
            }
         /* Check Sectors Range of Drive-onto-Device , WCP_SW , 2005/09/13, ADD START */
            /* Check If Logical Sectors Larger than Physical Sectors
             * -----------------------------------------------------
             *  This modification is a trade-off solution come from a special case.
             *  Which a cluster-overflow-formatted card will stop response once
             *  out-of-valid sector written.
             *  On spec, card must response error when try to write wrong sector.
             *  Another approach on driver is to check range every sector write.
             *  But it degrad the performance.
             *  Yet another proposal is reject mount for this case.
             *  But Windows can mount this card and make user confused.
             *  So the trade-off solution is try to limit drive cluster value at initialize.
             * */
            while ( (Drive->FirstDataSector + (Drive->Clusters - 2) * Drive->SectorsPerCluster)
                 /* Max Logical Sector */ > (Drive->Dev->DevData.Geometry.Sectors) /* Max Physical Sector */ )
            {
               Drive->Clusters--;

               fs_util_trace_info1(TRACE_ERROR, FS_ERR_MOUNTDRIVE_TOO_MANY_LOGI_SEC, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), NULL);

               if (Drive->Dev->DevData.Geometry.Sectors == 0)
               {
                  Drive->Dev->DevData.MountState = NotMounted;

                  fs_util_trace_info1(TRACE_ERROR, FS_ERR_MOUNTDRIVE_MEDIA_CHANGED, fs_conf_get_devtype_by_devflag(Drive->Dev->DeviceFlags), NULL);

                  XRAISE(RTF_MEDIA_CHANGED);
               }
               if (((Drive->Clusters - 2) * Drive->SectorsPerCluster) <= Drive->FirstDataSector)
               {
                  break;
               }
            }
         /* Check Sectors Range of Drive-onto-Device , WCP_SW , 2005/09/13, ADD END */

         }

         Drive->MountState = HasFileSystem;

         #ifdef __FS_LIMITED_DISK_SIZE__
         if (((Drive->Clusters - 2) * Drive->SectorsPerCluster)
//             > (FS_MAX_DISK_SIZE * (1024 * 1024 / Drive->Dev->DevData.SectorSize))) // DIV SLIM
             > (FS_MAX_DISK_SIZE * (1024 * 1024 >> Drive->Dev->DevData.SectorShift)))

         {
               Drive->MountState = SizeExceeded;
               XRAISE(MT_DISK_SIZE_TOO_LARGE);
         }
         #endif // __FS_LIMITED_DISK_SIZE__

         #ifndef __FS_CARD_DOWNLOAD__
         // mark all clusters who cross sector boundary as Bad Cluster to avoid using it in the future! (powerloss issue, FAT12 only)
         {
             kal_uint32 cluster_group, cluster_crossed, cluster_value;

             XTRY
                 case XCODE:
                     if (Drive->FATType == RTFAT12)
                      {
                         for (cluster_group = 0; cluster_group < Drive->Clusters; cluster_group += FS_FAT12_CLUSTER_CROSSING_SECTOR_GROUP)
                         {
                             for (cluster_crossed = cluster_group + FS_FAT12_CLUSTER_CROSSING_SECTOR_OFFSET;
                                  cluster_crossed < (cluster_group + FS_FAT12_CLUSTER_CROSSING_SECTOR_GROUP - 1) && cluster_crossed < Drive->Clusters;
                                  cluster_crossed += FS_FAT12_CLUSTER_CROSSING_SECTOR_OFFSET)
                             {
                                 cluster_value = GetClusterValue(Drive, cluster_crossed, 0);

                                 if (cluster_value == 0)
                                 {
                                     SetClusterValue(Drive, cluster_crossed, RTF_BAD_CLUSTER);
                                 }
                             }

                             FlushAllBuffersInGeometryOrder(Drive->Dev);
                         }
                      }

                     break;
                 default:
                     XHANDLED;
                     break;
                 case XFINALLY:
                     break;
             XENDX
         }
         #endif

         // system drive
         if (Drive->Dev->DeviceNumber == gFS_DeviceNumOfSYSDRV)
         {
            Drive->FreeClusterCount = 0;
            Drive->ClusterWatermark = RTF_INVALID_CLUSTER;
         }
         // other drives
         else {
            Drive->FreeClusterCount = RTF_INVALID_CLUSTER;  // FS_GetDiskInfo will ident this value
            Drive->ClusterWatermark = 2;
         }

#ifndef __FS_CARD_DOWNLOAD__
         // Always ount free clusters right away
         // 1. at system init
         // 2. at FS_LockFAT(FS_REMOUNT_ENUM) or FS_TestMSDC, FS_DEVICE_COUNT_FREE_CLUSTER will be set before call MountRemovableDevice().
         if ((kal_query_systemInit() == KAL_TRUE) ||
             (Drive->Dev->DeviceNumber == gFS_DeviceNumOfSYSDRV) ||
             (Drive->Dev->DevData.Reserved & FS_DEVICE_COUNT_FREE_CLUSTER))  {
            BatchCountFreeClusters(Drive);
         }
         // Add Alarm Mode boot check for memory cards (Font Support)
         else if (Drive->Dev->DeviceFlags & RTF_DEVICE_REMOVABLE)    {
            kal_int32 bootmode;
            bootmode=FS_GetBootMode();
            if (bootmode==RTCPWRON) {
                BatchCountFreeClusters(Drive);
            }
         }
#endif

#if 0 /* Fix FAT32 display wrong free size, Karen Hsu, 2005/06/06, REM */
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
#endif

#if (defined(__FS_SHADOW_NAND__) || defined(__FS_SHADOW_CARD__))
         if (stack_query_boot_mode() != USBMS_BOOT)
         {
            InitShadowFAT(Drive);
         }
#endif
         break;
      default:
         fs_util_trace_err_noinfo(XVALUE);

         if (((State <= Initialized) && (Drive->Dev->DevData.MountState >= State)) || (Drive->MountState >= State))
            XHANDLED;

         break;
      case XFINALLY:
#ifndef __FS_CARD_DOWNLOAD__
         MTExpireDirCacheByDrive(Drive);  // reset dir cache in mount stage (W10.28)
#endif
         #ifdef __FS_OPEN_HINT__
         MTHintExpireByDrive(Drive);      // reset internal open hint in mount stage (W10.28)
         #endif

         break;
   XENDX
}

int MountRemovableDevice(RTFDevice *Dev)
{
   volatile int Result = RTF_NO_ERROR;

   fs_assert_local(Dev != NULL);

   XTRY
      case XCODE:
         SafeLock(MT_LOCK_RTF | MT_LOCK_DEV, Dev, RTF_INFINITE);
         DiscardAllBuffers(Dev);
         /* Here we assume only one drive on the dev */
         MountLogicalDrive(Dev->DevData.FirstDrive, HasFileSystem);
         break;
      default:
         if (MT_MSDC_MOUNT_ERROR == XVALUE || MT_DISK_SIZE_TOO_LARGE == XVALUE)
         {
            Result = XVALUE;

            fs_util_trace_err_noinfo(Result);
         }
         else
         {
            XTRY
               case XCODE:
                  SafeLock(MT_LOCK_RTF | MT_LOCK_DEV, Dev, RTF_INFINITE);
                  Dev->DeviceType = RTF_DEVICE_FLOPPY;
                  MountLogicalDrive(Dev->DevData.FirstDrive, HasFileSystem);
                  break;
               default:
                  Result = XVALUE;
                  XHANDLED;
                  Dev->DevData.MountState = NotMounted;
                  break;
               case XFINALLY:
                  Dev->DeviceType = FS_DEVICE_FDISK;
                  break;
            XENDX
            /* XTRY ~ XENDX Block don't return directly */
            if (Result == RTF_NO_ERROR)
               XVALUE = RTF_NO_ERROR;
            else
            {
               XVALUE = MT_MSDC_MOUNT_ERROR;

               fs_util_trace_err_noinfo(Result);
            }
         }
         break;
      case XFINALLY:
         SafeUnlock(MT_LOCK_RTF | MT_LOCK_DEV);
         break;
   XEND_API

   return Result;
}

#ifndef __FS_CARD_DOWNLOAD__
/*************************************************************************
* FUNCTION
*  RTFSYSErrorExit
*
* DESCRIPTION
*  This function implements to filesystem fatal error handler
*
* PARAMETERS
*
* RETURNS
*
* GLOBALS AFFECTED
*
*************************************************************************/
void RTFAPI
RTFSYSErrorExit(const char * Message, UINT ExitCode)
{
	kal_fatal_error_handler(KAL_ERROR_FILESYS_INTERNAL_FAILED, ExitCode);
}

void fs_lock_init()
{
    if (NULL == _gfs_lock_common)
    {
        _gfs_lock_common = fs_lock_alloc_mutex("FSComLock", FS_LOCK_TYPE_DEFAULT);
    }
}

FS_Mutex* fs_lock_alloc_mutex(const char *name, fs_lock_type_enum type)
{
    if (FS_LOCK_TYPE_DEFAULT == type)
    {
        return (FS_Mutex*)RTFSYSAllocMutex(name);
    }

    return NULL;
}

void fs_lock_free_mutex(FS_Mutex *mutex)
{
    //--- RTFiles implementation

    RTFSYSFreeMutex((RTFMutex*)mutex);
}

int fs_lock_get_mutex(FS_Mutex *mutex, kal_uint32 timeout)
{
    //--- RTFiles implementation
    kal_uint32 lr;
    kal_int32 result;
    FS_GET_RETURN_ADDRESS(lr);
    result = RTFSYSLockMutex((RTFMutex*)mutex, (kal_uint32)timeout);
    mutex->mt_sem_owner_lr=lr;
    return result;
}


/*************************************************************************
* FUNCTION
*  _rtfLock
*
* DESCRIPTION
*  This function implements to set and lock
*
* PARAMETERS
*
* RETURNS
*
* GLOBALS AFFECTED
*
*************************************************************************/
#if defined(WIN32)
CRITICAL_SECTION CS;    // CRITICAL_SECTION is defined in "windows.h"

BYTE
_rtfLock(BYTE * Lock)
{
	kal_uint8 tmp;
	static kal_uint8 first = 0;

   if(!first)
   {
      InitializeCriticalSection(&CS);
      first = 1;
   }

   EnterCriticalSection(&CS);

	tmp = *Lock;
	*Lock = 1;

	LeaveCriticalSection(&CS);

	return tmp;
}
#else
BYTE
_rtfLock(BYTE * Lock)
{
	kal_uint8 tmp;
	kal_uint32 savedmask;

	/* Critical Section */
	savedmask = SaveAndSetIRQMask();

	tmp = *Lock;
	*Lock = 1;

	RestoreIRQMask(savedmask);

	return tmp;
}
#endif

/*******************************************************************//**
 * Promise task only takes one lock
 *
 * @par Category:
 * File System (MTK Internal Enhancement)
 *
 * @note
 * Free mutex until rtf_lock_count equals to 1
 **********************************************************************/

int SafeLockEntry(RTFMutex *Lock, DWORD Timeout)
{
    int Result;

    Result = RTFSYSLockMutex(Lock, Timeout);
    if(Result < RTF_NO_ERROR) return Result;
    while(Lock->rtf_lock_count > 1) RTFSYSFreeMutex(Lock);
    return Result;
}

int RTFAPI SafeLock(DWORD Lock, RTFDevice * Dev, DWORD Timeout)
{
   int Result = RTF_NO_ERROR;

   if(kal_query_systemInit() == KAL_TRUE) //for sanity check
      return Result;

   do {
        if(Lock & MT_LOCK_FMT)  { Result=SafeLockEntry(MTFMLock, Timeout); if (Result<0) break; }
        if(Lock & MT_LOCK_EXT)  { Result=SafeLockEntry(MTXLock, Timeout);  if (Result<0) break; }
        if(Lock & MT_LOCK_MOVE) { Result=SafeLockEntry(MTMoveLock, Timeout);  if (Result<0) break; }
        if(Lock & MT_LOCK_XDEL) { Result=SafeLockEntry(MTXdelLock, Timeout);  if (Result<0) break; }
#ifdef __FS_SORT_SUPPORT__
        if(Lock & MT_LOCK_SORT) { Result=SafeLockEntry(MTSortLock, Timeout);  if (Result<0) break; }
#endif
        if(Lock & MT_LOCK_DISKIF) { Result=SafeLockEntry(MTDiskInfoLock, Timeout);  if (Result<0) break; }
        if(Lock & MT_LOCK_DEV)   {
          if((Dev) && (Dev->DeviceType & (RTF_DEVICE_FDISK | RTF_DEVICE_REMOVABLE)))      {
             Result=SafeLockEntry(Dev->DevData.Lock, Timeout);  if (Result<0) break;
          }
        }
        if(Lock & MT_LOCK_RTF)  { Result=SafeLockEntry(RTFLock, Timeout);  if (Result<0) break; }
   } while (0);

   return Result;
}

void SafeUnlockEntry(RTFMutex *Lock)
{
    while(RTFSYSOwnMutex(Lock) == KAL_TRUE) RTFSYSFreeMutex(Lock);
}

/* Promise task exits without holding lock */
int RTFAPI SafeUnlock(DWORD Lock)
{
   RTFDevice * Dev;

   if(kal_query_systemInit() == KAL_TRUE) //for sanity check
      return RTF_NO_ERROR;

   if (Lock & MT_LOCK_RTF) SafeUnlockEntry(RTFLock);
   if (Lock & MT_LOCK_DEV)   {
      for (Dev = gFS_DeviceList; Dev->DeviceType; Dev++)      {
         while(RTFSYSOwnMutex(Dev->DevData.Lock) == KAL_TRUE)         {
            if (Dev->DevData.B) FreeBuffer(Dev);
            RTFSYSFreeMutex(Dev->DevData.Lock);
         }
      }
   }

   if (Lock & MT_LOCK_DISKIF) SafeUnlockEntry(MTDiskInfoLock);

#ifdef __FS_SORT_SUPPORT__
   if (Lock & MT_LOCK_SORT) SafeUnlockEntry(MTSortLock);
#endif

   if (Lock & MT_LOCK_XDEL) SafeUnlockEntry(MTXdelLock);
   if (Lock & MT_LOCK_MOVE) SafeUnlockEntry(MTMoveLock);
   if (Lock & MT_LOCK_EXT)  SafeUnlockEntry(MTXLock);
   if (Lock & MT_LOCK_FMT)  SafeUnlockEntry(MTFMLock);

   return RTF_NO_ERROR;
}

/*-----------------------------------*/
void RTFAPI UnlockDevice(RTFDevice * Dev)
{
   /* free inuse buffer */
   if (Dev->DevData.B)
      FreeBuffer(Dev);
   if (Dev->DevData.ErrorCondition < RTF_NO_ERROR)
      UnmountDevice(Dev, 1);

#ifdef DEBUG
   EntryExitCheck(Dev, XHANDLER);
#endif
   /* free system lock */
   RTFSYSFreeMutex(RTFLock);

   /* free device lock */
   RTFSYSFreeMutex(Dev->DevData.Lock);
#ifdef DEBUG
   CheckReleased(XHANDLER);
#endif
}

/*******************************************************************//**
 * Lock both device and system lock (non-blocking mode)
 *
 * @par Category:
 * File System
 *
 * @note
 * Increase device's access count whenever device is locked.
 **********************************************************************/
void RTFAPI LockDevice(RTFDevice * Dev, UINT Flags)
{
   int status;
   kal_uint32 timeout;

   /*--------------------------------------------------------------------------
    * SysLockFAT is only set in FS_LockFAT(FS_LOCK_USB_ENUM) and used by USB boot-up mode.
    * Since 09A, USB boot-up mode uses FS_LockFAT(FS_EXPORT_ENUM) instead to allow system
    * drive access by NVRAM.
    *--------------------------------------------------------------------------*/
   if(INT_QueryExceptionStatus() == KAL_FALSE) //allow to write exception record
      fs_assert_local(SysLockFAT == 0);

   if (CardBusyCheck && (Dev->DeviceFlags & RTF_DEVICE_REMOVABLE) && !(Flags & FS_NOBUSY_CHECK_MODE))
   {
      if (Dev->DevData.FirstDrive) // e.g., for dual T-card platform, drive letter is required to distinguish different memory card devices.
      {
         status = FS_GetDevStatus(MT_BASE_DRIVE_LETTER + (Dev->DevData.FirstDrive - gFS_Data.DriveTable), FS_FEATURE_STATE_ENUM);
      }
      else
      {
         status = FS_GetDevStatus(FS_DEVICE_TYPE_CARD, FS_FEATURE_STATE_ENUM);
      }

      if (status == MT_DEVICE_BUSY)
      {
         fs_util_trace_err_noinfo(status);
         fs_util_trace_info1(TRACE_ERROR, FS_ERR_NONBLOCKLOCKDEVICE_DEVICE_BUSY, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

         XRAISE(status);
      }
   }

   if (Flags & FS_NONBLOCK_MODE)
   {
      timeout = RTF_NO_WAIT;
   }
   else
   {
      timeout = RTF_INFINITE;
   }

   status = RTFSYSLockMutex(Dev->DevData.Lock, timeout);

   if(status != RTF_NO_ERROR)
   {
      fs_util_trace_err_noinfo(status);
      fs_util_trace_info1(TRACE_ERROR, FS_ERR_NONBLOCKLOCKDEVICE_LOCK_DEV_FAIL, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

      XRAISE(status);
   }

   status = RTFSYSLockMutex(RTFLock, timeout);

   if(status != RTF_NO_ERROR)
   {
      fs_util_trace_err_noinfo(status);
      fs_util_trace_info1(TRACE_ERROR, FS_ERR_NONBLOCKLOCKDEVICE_LOCK_RTF_FAIL, fs_conf_get_devtype_by_devflag(Dev->DeviceFlags), NULL);

      RTFSYSFreeMutex(Dev->DevData.Lock); /* Fix always occupy device lock bug, Karen Hsu, 2005/01/30, ADD */
      XRAISE(status);
   }

   Dev->DevData.AccessCount++;
}

/*******************************************************************//**
 * Find device lock
 *
 * @par Category:
 * File System
 *
 * @note
 * Return existed device's lock with the same driver. If not found, allocate one
 * using device's friendly name as the semaphore name.
 **********************************************************************/
RTFMutex * FindDeviceLock(RTFDevice * Dev, RTFDriver * Driver, const char * Name)
{
   for (; Dev >= gFS_DeviceList; Dev--)
      if (Dev->Driver == Driver)
         return Dev->DevData.Lock;
   return RTFSYSAllocMutex(Name);
}


#endif /* !__FS_CARD_DOWNLOAD__ */

/*-----------------------------------*/
static void INTERN InitDevices(void)
{
   RTFDevice * Dev;

   for (Dev = gFS_DeviceList; Dev->DeviceType; Dev++)
   {
      //if ((Dev->Driver->Version < 200) || (Dev->Driver->Version > RTFILE_VER))
         //RTFSYSErrorExit("Dev driver version mismatch", 1);

      if (Dev->DeviceType == FS_DEVICE_FLOPPY)
      {
         Dev->DeviceFlags |= RTF_DEVICE_REMOVABLE;
      }

      Dev->DevData.MediaPresent = (Dev->DeviceFlags & RTF_DEVICE_NO_MEDIA) == 0;
      Dev->DevData.MediaRemovedReported = 1;
      Dev->DevData.PhysicalDiskIndex = -1;

      kal_sprintf(Dev->DevData.FriendlyName, "Disk %d",  (Dev - gFS_DeviceList));

    #ifndef __FS_CARD_DOWNLOAD__
      /* set device's lock */
      if (Dev->DevData.Lock == NULL)
      {
         /* allocate another lock for this device */
         if (Dev->DeviceFlags & RTF_DEVICE_NEW_LOCK)
            Dev->DevData.Lock = RTFSYSAllocMutex(Dev->DevData.FriendlyName);
         /* share one lock for the same device driver */
         else
            Dev->DevData.Lock = FindDeviceLock(Dev-1, Dev->Driver, Dev->DevData.FriendlyName);
      }
   #endif /* __FS_CARD_DOWNLOAD__ */
   }
}
/*-----------------------------------*/
static char INTERN LockedScanPartitionTable(char volatile DriveLetter,
                                            RTFDevice * Dev,
                                            int PartitionKind)
{
   XTRY // just to keep CheckReleased happy
      case XCODE:
         XTRY
            case XCODE:
               LockDevice(Dev, 0);
               DriveLetter = ScanPartitionTable(DriveLetter, Dev, PartitionKind);
               break;
            default:
               XHANDLED;
               break;
            case XFINALLY:
               UnlockDevice(Dev);
               break;
         XENDX
         break;
      default:
         break;
      case XFINALLY:
         break;
   XENDX
   return DriveLetter;
}

/*-----------------------------------*/
void ScanDevices(void)
{
   RTFDevice *Dev;
   char      DriveLetter = MT_BASE_DRIVE_LETTER;
   int       DiskIndex = 0;
   /* Dynamic assign device number, Karen Hsu, 2005/06/08, MOD START */
   int i = 1;

   // distribute disk indexes
   for (Dev = gFS_DeviceList; Dev->DeviceType; Dev++)
   {
      Dev->DeviceNumber = i;
      i++;
      if (Dev->DeviceType == FS_DEVICE_FDISK)
         Dev->DevData.PhysicalDiskIndex = DiskIndex++;
      else
         Dev->DevData.PhysicalDiskIndex = -1;
   }
   /* Dynamic assign device number, Karen Hsu, 2005/06/08, MOD END */

   // mount devices if they are not removeable
   for (Dev = gFS_DeviceList; Dev->DeviceType; Dev++)
      if ((Dev->DeviceFlags & RTF_DEVICE_REMOVABLE) == 0)
         rtf_core_mount_device(Dev, NO_RAISE);

   // mount first primary partitions in every device
   // ignore RTF_MOUNT_CONTIGUOUS devices
   for (Dev = gFS_DeviceList; Dev->DeviceType; Dev++)
   {
      if (Dev->DeviceFlags & RTF_DEVICE_MOUNT_CONTIGUOUS)
         continue;
      if (Dev->DeviceType == FS_DEVICE_FLOPPY)
      {
         DriveLetter = ReserveLogicalDrive(DriveLetter, Dev);
      }
      else
      {
         if (Dev->DevData.MountState >= Mounted)
            DriveLetter = LockedScanPartitionTable(DriveLetter, Dev, RTF_PARTITION_FIRST_PRIMARY);
         /* Reserve drive name for mount error device, Karen Hsu, 2004/03/04, ADD START */
         else if((Dev->DeviceFlags & RTF_DEVICE_REMOVABLE) == 0)
         {
            UINT idx;
            for(idx = MT_BASE_DRIVE_INDEX; idx < FS_MAX_DRIVES; idx++)
               if(gFS_Data.DriveTable[idx].Dev == NULL)
                  break;
            AllocateDrive(MT_BASE_DRIVE_LETTER + idx, Dev);
         }
         /* Reserve drive name for mount error device, Karen Hsu, 2004/03/04, ADD END */
      }
   }

   #if !defined(__FS_SLIM_EXTENDED_PARTITION__)
   // mount extended partitions in every device
   for (Dev = gFS_DeviceList; Dev->DeviceType; Dev++)
      if (((Dev->DeviceFlags & (RTF_DEVICE_REMOVABLE | RTF_DEVICE_MOUNT_CONTIGUOUS)) == 0) &&
          (Dev->DevData.MountState >= Mounted))
      {
         DriveLetter = LockedScanPartitionTable(DriveLetter, Dev, RTF_PARTITION_EXTENDED);
      }
   #endif   // !__FS_SLIM_EXTENDED_PARTITION__

   // mount other primary partitions in every device
   for (Dev = gFS_DeviceList; Dev->DeviceType; Dev++)
      if (((Dev->DeviceFlags & (RTF_DEVICE_REMOVABLE | RTF_DEVICE_MOUNT_CONTIGUOUS)) == 0) &&
          (Dev->DevData.MountState >= Mounted))
      {
         DriveLetter = LockedScanPartitionTable(DriveLetter, Dev, RTF_PARTITION_OTHER_PRIMARY);
      }
      /* Reserve drive name for mount error device, Karen Hsu, 2004/03/04, ADD START */
      else if((Dev->DeviceType & RTF_DEVICE_REMOVABLE) == 0)
      {
         if(((Dev->DeviceFlags & MT_DEVICE_NOR_FLASH) && NorPartition) ||
            ((Dev->DeviceFlags & MT_DEVICE_NAND_FLASH) && NandPartition))
         {
            UINT idx;
            for(idx = MT_BASE_DRIVE_INDEX; idx < FS_MAX_DRIVES; idx++)
               if(gFS_Data.DriveTable[idx].Dev == NULL)
                  break;
            AllocateDrive(MT_BASE_DRIVE_LETTER + idx, Dev);
         }
      }
      /* Reserve drive name for mount error device, Karen Hsu, 2004/03/04, ADD END */


   // mount RTF_MOUNT_CONTIGUOUS devices
   for (Dev = gFS_DeviceList; Dev->DeviceType; Dev++)
      if (((Dev->DeviceFlags & (RTF_DEVICE_REMOVABLE | RTF_DEVICE_MOUNT_CONTIGUOUS)) == RTF_DEVICE_MOUNT_CONTIGUOUS) &&
          (Dev->DevData.MountState >= Mounted))
      {
         DriveLetter = LockedScanPartitionTable(DriveLetter, Dev, RTF_PARTITION_ALL);
      }

   // reserve a drive letters for removable devices (assuming only one drive in each removable device!)
   for (Dev = gFS_DeviceList; Dev->DeviceType; Dev++)
      if ((Dev->DeviceType == FS_DEVICE_FDISK) &&
          ((Dev->DeviceFlags & (RTF_DEVICE_MOUNT_CONTIGUOUS | RTF_DEVICE_REMOVABLE)) == RTF_DEVICE_REMOVABLE))
      {
         DriveLetter = ReserveLogicalDrive(DriveLetter, Dev);
      }

   #if (defined(__NANDFDM_MULTI_INSTANCE__) && defined(__NAND_FDM_50__))
   {
      /*
       * In custom_MemoryDevice.h, customer could configure each
       * device as VISIBLE or INVISIBLE. Visible device will be un-mounted and
       * exported when USB cable is inserted.
       *
       * Here we dynamically add MT_DEVICE_NO_EXPORT flag to device which was set
       * to INVISIBLE to prevent them being un-mounted in FS_LockFAT()
       *                                                     - W09.45 Stanley Chu
       */
      RTFDeviceInfo info;

      for (Dev = gFS_DeviceList; Dev->DeviceType; Dev++)
      {
         /*
          * Only NAND flash device requires dynamic configuration now.
          * Note: Device with system drive will remain its default setting, and will be
          *       taken care specifically in FS_LockFAT(). Such device does not need
          *       dynamic configuraiton.
          */
         if (Dev->DeviceFlags & MT_DEVICE_NAND_FLASH && Dev->DeviceNumber != gFS_DeviceNumOfSYSDRV)
         {
            // query NAND FDM driver and mark (clean) MT_DEVICE_NO_EXPORT flag
            if (Dev->Driver->IOCtrl)
            {
               info.DeviceInfo.NAND.Flag = 0; // reset flag first

               Dev->Driver->IOCtrl(Dev->DriverData, FS_IOCTRL_QUERY_NAND_INFO, &info);

               if (info.DeviceInfo.NAND.Flag & MT_DEVICE_FLAG_VISIBLE)
                  Dev->DeviceFlags &= ~MT_DEVICE_NO_EXPORT;
               else // invisible
                  Dev->DeviceFlags |= MT_DEVICE_NO_EXPORT;
            }
         }
      }
   }
   #endif /* __NANDFDM_MULTI_INSTANCE__ && __NAND_FDM_50__ */
}


void RTFAPI RTFInit(void)
{
    RTFINIT_BEGIN();

    if(TLSBlockIndex == -1)
        TLSBlockIndex = RTFSYSAllocTLS();

    MTCacheInit();
#ifdef __FS_OPEN_HINT__
    MTHintAlloc();
#endif

    fs_lock_init();      // initialize FS internal locks

#if defined(__FS_XDATA_MEMORY_NOT_IN_STACK__)
    fs_mem_init();
#endif

    InitDevices();
    ScanDevices();

   RTFINIT_END();
}