bbcfat.c 66.2 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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#ifndef WIN32
#include <unistd.h>
#include <netinet/in.h>
#endif

#include <PR/bbfs.h>
#include "bbclocal.h"
#include "ecc256.h"

#define MAX_FSFILES	64

#ifndef WIN32
#define DCACHE_ALIGN __attribute__ ((aligned(16))) 
#else
#define DCACHE_ALIGN 
#endif

/* Global Statistics */
volatile int __bbc_bytes_written = 0;
volatile int __bbc_bytes_read = 0;

static int __bbc_write_fat(bbc_hand *hp);
static int __bbc_check_fat(bbc_hand *hp);
int __osBbFsSync(bbc_hand *hp);

/* 
 * Return number of bytes read by FRead
 */
int BBCGetBytesRead() 
{
    return __bbc_bytes_read;
}

/* 
 * Return number of bytes written by FWrite
 */
int BBCGetBytesWritten()
{
    return __bbc_bytes_written;
}
    
#ifdef BBC_DIAG
/*
 * Diagnostic version of __BBC_ScanBadBlocks_real
 * Doesn't change FAT table unless DBE fixed for block marked bad in FAT
 */
int
__BBC_ScanBadBlocks_diag(bbc_hand *hp, int rewrite_dbe)
{
    TIME_T t1, t2;
    int readt = 0, writet = 0;
    int readb = 0, writeb = 0;
    BbFat16* fat = hp->bh_fat;
    int blocks = hp->bh_cardsize;
    flashif_t *fif = hp->bh_flashif;
    u8 spare[BB_FL_SPARE_SIZE] DCACHE_ALIGN;
    int i, status, rv, fatmarked;
    char *junk;
    typedef struct badblkstat {
        char* name;
        int mfg;
        int dbe;
        int fixeddbe;
        int fatmfg;
        int fatdbe;
        int fatonly;
    } badblkstat_t;

    badblkstat_t badtotal = { "TOTAL", 0, 0, 0, 0, 0, 0 };
    badblkstat_t badbyarea[3] = { { "SKSA", 0, 0, 0, 0, 0, 0 },
                                  { "FAT",  0, 0, 0, 0, 0, 0 },
                                  { "FS",   0, 0, 0, 0, 0, 0 } };
    badblkstat_t* area;

    BBC_LOG(MSG_DEBUG, "__BBC_ScanBadBlocks_diag %d\n", rewrite_dbe);
    if ((junk = malloc(BB_FL_BLOCK_SIZE)) == NULL) {
	BBC_LOG_SYSERROR("__BBC_ScanBadBlocks_diag: malloc failed");
	return BBC_NOMEM;
    }
    BBC_LOG(MSG_DIAG, "Basic media check: scanning card for bad blocks (DBE rewrite = %d)\n", rewrite_dbe);
    for(i = 0; i < blocks; i++) {
        status = BB_FAT16_NEXT(fat, i);

	if (status == BB_FAT_BAD) {           
            fatmarked = 1;
        } 
        else {
            fatmarked = 0;
        }

        if (i < SYS_BLOCKS) {
            /* In SKSA area */
            area = &badbyarea[0];
        }
        else if (i >=  blocks-BB_FAT16_BLOCKS) {
            /* part of FAT */
            area = &badbyarea[1];
        }
        else {
            /* In file system area */
            area = &badbyarea[2];
        }
        
        if (bbc_diag_mode) TIME(&t1);
        rv = (*fif->read_blocks)(fif->f, i, 1, junk, spare);
        if (bbc_diag_mode) { TIME(&t2); readt += __bbcdiag_deltat(t1, t2); readb++; }
        if (rv < 0) {
            if (rv == BBC_BADBLK) {
                /* Block was marked bad by manufacturer */
                BBC_LOG(MSG_WARNING, "__BBC_ScanBadBlocks_diag: blk %d in %s marked bad by MFG %s\n",
                        i, area->name, fatmarked? "- FAT already marked":"");
                area->mfg++;
                if (fatmarked) area->fatmfg++;
            }
	    else if (rv == BBC_DATAERR) {
		/*
		 * Got DBE on read.  That is ok, since the block may still be good.
		 * Only by rewriting it can that be determined, so we mark it as
		 * available and wait until it gets written.
		 */
	        BBC_LOG(MSG_WARNING, "__BBC_ScanBadBlocks_diag: blk %d in %s read DBE (ok) %s\n",
                        i, area->name, fatmarked? "- FAT already marked":"");
                area->dbe++;
                if (fatmarked) area->fatdbe++;
                if (rewrite_dbe) {
                    if (bbc_diag_mode) TIME(&t1);
                    rv = (*fif->write_blocks)(fif->f, i, 1, junk, spare);
                    if (bbc_diag_mode) { TIME(&t2); writet += __bbcdiag_deltat(t1, t2); writeb++; }
                    if (rv < 0) {
                        BBC_LOG(MSG_ERR, "__BBC_ScanBadBlocks_diag: rewrite of DBE blk %d returned with %d\n",
                                i, rv);
                    }
                    else {
                        /* Try reading block again */
                        if (bbc_diag_mode) TIME(&t1);
                        rv = (*fif->read_blocks)(fif->f, i, 1, junk, spare);
                        if (bbc_diag_mode) { TIME(&t2); readt += __bbcdiag_deltat(t1, t2); readb++; }
                        if (rv >= 0) {
                            BBC_LOG(MSG_DIAG, "__BBC_ScanBadBlocks_diag: rewrite of DBE blk %d succeeded\n", i);
                            area->fixeddbe++;
                            if (fatmarked)
                                status = BB_FAT_AVAIL;
                        }
                        else {
                            BBC_LOG(MSG_DIAG, "__BBC_ScanBadBlocks_diag: blk %d still has DBE\n", i);
                        }
                    }
                }
	    } else {
                /* Other error while reading - can't rely on data returned, abort */
	        BBC_LOG(MSG_ERR, "__BBC_ScanBadBlocks_diag: blk %d err %d abort bad block scan\n", i, rv);
                free(junk);
		return rv;
	    }
	}
        else {
            if (fatmarked) {
                BBC_LOG(MSG_ERR, "__BBC_ScanBadBlocks_diag: blk %d in %s "
                        "marked bad by FAT but is okay (no MFG/DBE)\n", 
                        i, area->name);
                area->fatonly++;
            }
        }

	BB_FAT16_NEXT(fat,i) = status;
    }
    /* non-existent blocks are bad */
    for(; i < BB_FAT16_ENTRIES; i++)
	BB_FAT16_NEXT(fat,i) = BB_FAT_BAD;
    free(junk);
        
    BBC_LOG(MSG_DIAG, "__BBC_ScanBadBlocks_diag: Bad blocks summary\n");
    for (i=0; i<3; i++) {
        badtotal.mfg += badbyarea[i].mfg;
        badtotal.dbe += badbyarea[i].dbe;
        badtotal.fatmfg += badbyarea[i].fatmfg;
        badtotal.fatdbe += badbyarea[i].fatdbe;
        badtotal.fixeddbe += badbyarea[i].fixeddbe;
        badtotal.fatonly += badbyarea[i].fatonly;
        
        BBC_LOG(MSG_DIAG, "%s: MFG=%d (%d marked in FAT), DBE=%d "
                "(%d marked in FAT), FIXED DBE=%d, FAT only = %d\n",
                badbyarea[i].name, badbyarea[i].mfg, badbyarea[i].fatmfg,
                badbyarea[i].dbe, badbyarea[i].fatdbe, badbyarea[i].fixeddbe,
                badbyarea[i].fatonly);                
    }
    BBC_LOG(MSG_DIAG, "%s: MFG=%d (%d marked in FAT), DBE=%d "
            "(%d marked in FAT), FIXED DBE=%d, FAT only = %d\n",
            badtotal.name, badtotal.mfg, badtotal.fatmfg,
            badtotal.dbe, badtotal.fatdbe, badtotal.fixeddbe,
            badtotal.fatonly);
    if (bbc_diag_mode) {
        BBC_LOG(MSG_DIAG, "Read %d blocks (%d bytes) in %d ms (%.1f KB/s)\n",
                readb, readb*BB_FL_BLOCK_SIZE, readt,
                __bbcdiag_getKBs(readb*BB_FL_BLOCK_SIZE, readt));
        if (writeb) {
            BBC_LOG(MSG_DIAG, "Wrote %d bad blocks (%d bytes) in %d ms (%.1f KB/s)\n",
                    writeb, writeb*BB_FL_BLOCK_SIZE, writet,
                    __bbcdiag_getKBs(writeb*BB_FL_BLOCK_SIZE, writet));
        }
    }

    BBC_LOG(MSG_DEBUG, "__BBC_ScanBadBlocks_diag SUCCESS\n");
    return BBC_OK;
}
#endif /* BBC_DIAG */

/*
 * read all of the blocks on the flash, checking the disposition of
 * the block by examining the spare area.
 */
static int
__BBC_ScanBadBlocks_real(bbc_hand *hp)
{
    BbFat16* fat = hp->bh_fat;
    int blocks = hp->bh_cardsize;
    flashif_t *fif = hp->bh_flashif;
    u8 spare[BB_FL_SPARE_SIZE] DCACHE_ALIGN;
    int i, status, rv;
    char *junk;

    BBC_LOG(MSG_DEBUG, "__BBC_ScanBadBlocks_real\n");
    if ((junk = malloc(BB_FL_BLOCK_SIZE)) == NULL) {
	BBC_LOG_SYSERROR("__BBC_ScanBadBlocks_real: malloc failed");
	return BBC_NOMEM;
    }
    for(i = 0; i < blocks; i++) {
	if (BB_FAT16_NEXT(fat,i) == BB_FAT_BAD) {
	    BBC_LOG(MSG_WARNING, "__BBC_ScanBadBlocks_real: blk %d already marked bad in FAT\n", i);
            continue;
        } 
        if ((rv = (*fif->read_blocks)(fif->f, i, 1, junk, spare)) < 0) {
            if (rv == BBC_BADBLK) {
                /* Block was marked bad by manufacturer */
                BBC_LOG(MSG_WARNING, "__BBC_ScanBadBlocks_real: blk %d err %d marked bad\n", i, rv);
                status = BB_FAT_BAD;
            }
	    else if (rv == BBC_DATAERR) {
		/*
		 * Got DBE on read.  That is ok, since the block may still be good.
		 * Only by rewriting it can that be determined, so we mark it as
		 * available and wait until it gets written.
		 */
	        BBC_LOG(MSG_WARNING, "__BBC_ScanBadBlocks_real: blk %d read DBE (ok)\n", i, rv);
	        status = BB_FAT_AVAIL;
	    } else {
                /* Other error while reading - can't rely on data returned, abort */
	        BBC_LOG(MSG_ERR, "__BBC_ScanBadBlocks_real: blk %d err %d abort bad block scan\n", i, rv);
                free(junk);
		return rv;
	    }
	} else
	    status = BB_FAT_AVAIL;
	BB_FAT16_NEXT(fat,i) = status;
    }
    /* non-existent blocks are bad */
    for(; i < BB_FAT16_ENTRIES; i++)
	BB_FAT16_NEXT(fat,i) = BB_FAT_BAD;
    free(junk);
    BBC_LOG(MSG_DEBUG, "__BBC_ScanBadBlocks_real SUCCESS\n");
    return BBC_OK;
}

/*
 * XXX This is a hack to speed up format in the direct case.
 * XXX Once the -h protocol is implemented on USB read, we can
 * XXX dispense with this.
 */
static int
__BBC_ScanBadBlocks_direct(bbc_hand *hp)
{
    unsigned int hbuf[2];
    unsigned char *blist;
    BbFat16* fat = hp->bh_fat;
    int blocks = hp->bh_cardsize;
    int i;
    int rv = BBC_OK;

    BBC_LOG(MSG_DEBUG, "__BBC_ScanBadBlocks_direct\n");
    if ((blist = malloc(blocks)) == NULL) {
	BBC_LOG_SYSERROR("__BBC_ScanBadBlocks_direct: malloc failed");
	return BBC_NOMEM;
    }

    hbuf[0] = REQ_SCAN_BLOCKS;
    hbuf[1] = hp->bh_seqno;
    if ((rv = __bbc_send_cmd(hp->bh_pofd, hbuf, 8)) < 0) goto out;
    if ((rv = __bbc_read_rsp(hp->bh_pifd, hbuf, 8)) < 0) goto out;
    if (hbuf[0] != 255-REQ_SCAN_BLOCKS) {
        BBC_LOG(MSG_ERR, "__BBC_ScanBadBlocks_direct: sync lost\n");
        rv = BBC_SYNCLOST;
        goto out;
    } 
    else if (hbuf[1]&0x80000000) {
        BBC_LOG(MSG_ERR, "__BBC_ScanBadBlocks_direct: scan blocks failed %d\n", hbuf[1]);
        rv = BBC_ERROR;
        goto out;
    }
    rv = __bbc_read_data(hp->bh_pifd, blist, blocks);
    if (rv < 0) {
        BBC_LOG_BBCERROR("__BBC_ScanBadBlocks_direct: read bad block list failed", rv);
	goto out;
    }
    for(i = 0; i < blocks; i++) {
	if (BB_FAT16_NEXT(fat,i) == BB_FAT_BAD) {
	    BBC_LOG(MSG_WARNING, "__BBC_ScanBadBlocks_direct: blk %d already marked bad in FAT\n", i);
            continue;
        }
	BB_FAT16_NEXT(fat,i) = (blist[i]) ? BB_FAT_BAD : BB_FAT_AVAIL;
	if (BB_FAT16_NEXT(fat,i) == BB_FAT_BAD) {
	    BBC_LOG(MSG_WARNING, "__BBC_ScanBadBlocks_direct: blk %d marked bad\n", i);
	}
    }
    /* non-existent blocks are bad */
    for(; i < BB_FAT16_ENTRIES; i++)
	BB_FAT16_NEXT(fat,i) = BB_FAT_BAD;

out:
    free(blist);
    BBC_LOG(MSG_DEBUG, "__BBC_ScanBadBlocks_direct return %d\n", rv);
    return rv;
}

static int
__BBC_ScanBadBlocks(bbc_hand *hp)
{
    return (hp->bh_type == BBC_HT_DIRECT) ?
        __BBC_ScanBadBlocks_direct(hp) : __BBC_ScanBadBlocks_real(hp);
}

int
__BBC_Format(bbc_hand *hp, int clear_bad_blocks)
{
    BbFat16* fat = hp->bh_fat;
    int blocks = hp->bh_cardsize;
    int i, rv;

    BBC_LOG(MSG_DEBUG, "__BBC_Format\n");
    /*
     * For blocks in the file system area that go bad during
     * operation, the bad block status in the FAT is the only
     * record of that.  This means that a reformat operation
     * of a previously formatted card must preserve this
     * information.
     */
    if (hp->bh_fat_valid) {
        if (clear_bad_blocks) {
            memset(fat, 0, BB_FL_MAX_FATS*sizeof(BbFat16));
        }
        else {
            /*
             * Clear inode table but leave block table alone.
             * The next pointers for good blocks will be set to
             * AVAIL by the bad block scan.
             */
            memset(fat->inode, 0, sizeof(fat->inode));
        }
    }
    if ((rv = __BBC_ScanBadBlocks(hp)) < 0) {
        BBC_LOG_BBCERROR("__BBC_Format: __BBC_ScanBadBlocks failed", rv);
        return rv;
    }
    /* reserve blocks for copies of the FAT at the high end */
    for (i = 0; i < BB_FAT16_BLOCKS; i++) {
	if (BB_FAT16_NEXT(fat, blocks-i-1) != BB_FAT_BAD)
	    BB_FAT16_NEXT(fat, blocks-i-1) = BB_FAT_RESERVED;
    }
    /* reserve blocks for system area */
    for (i = 0; i < BB_SYSTEM_AREA_SIZE/BB_FL_BLOCK_SIZE; i++) {
	if (BB_FAT16_NEXT(fat,i) != BB_FAT_BAD)
	    BB_FAT16_NEXT(fat,i) = BB_FAT_RESERVED;
    }
    hp->bh_fat_valid = 1;
    if ((rv = __bbc_write_fat(hp)) == BBC_OK) {
	rv = __bbc_check_fat(hp);
        if (rv < 0) {
            BBC_LOG_BBCERROR("__BBC_Format: __bbc_check_fat failed", rv);
        }
    }
    else BBC_LOG_BBCERROR("__BBC_Format: __bbc_write_fat failed", rv);

    BBC_LOG(MSG_DEBUG, "__BBC_Format return %d\n", rv);
    return rv;
}

/*
 * File system consistency checker
 *
 * Deletes files containing the following errors:
 * 	blocks marked bad
 * 	invalid block pointers
 *	blocks allocated to more than one file
 * Reclaims blocks not allocated to any file
 */
static int
__osBbFCheck(bbc_hand *hp)
{
    BbFat16 *fat = hp->bh_fat;
    int blocks = hp->bh_cardsize;
    int fixed = 0;
    BbInode* in;
    u16 i, j, files = 0;
    static u32 map[8192/32];	/*XXXblythe move to superblock structure*/
    u16 b;
    u32 size;
    int rv = BBC_OK;

    BBC_LOG(MSG_DEBUG, "__osBbFCheck\n");
restart:
    BBC_LOG(MSG_DIAG, "__osBbFCheck blks %d\n", blocks);
    memset(map, 0, sizeof map);
    for(i = 0; i < BB_INODE16_ENTRIES; i++) {
#ifdef BBC_DEBUG
        char nm[16];
        char line[60];
        char blockstring[16];
        int nblks = 0;
#endif

	in = fat->inode+i;
	if (!in->type) continue;
	size = 0;
        files++;
	/* check blocks */
#ifdef BBC_DEBUG
        if (bbc_diag_mode) {
            memset(nm, 0, 16);
            strncpy(nm, in->name, 8); 
            if (in->name[8]) { 
                strcat(nm, ".");  
                strncat(nm, &in->name[8], 3); 
            }
            
            BBC_LOG(MSG_INFO, "inode %d name %s size %ld, blks: \n", 
                    i, nm, in->size);
            line[0] = '\0';
        }
#endif
	for(b = in->block; b != BB_FAT_LAST; b = BB_FAT16_NEXT(fat,b)) {
#ifdef BBC_DEBUG
            if (bbc_diag_mode) { 
                sprintf(blockstring, "%d", b);
                if (nblks)
                    strcat(line, ", ");
                /* leave room for ", \0" */
                if (strlen(line) + strlen(blockstring) < sizeof(line) - 3) {
                    strcat(line, blockstring);
                }
                else {
                    BBC_LOG(MSG_INFO, "%s\n", line);
                    line[0] = '\0';
                    strcat(line, blockstring);
                }
            }
            nblks++;
#endif
	    if (b <  BB_FL_BYTE_TO_BLOCK(BB_SYSTEM_AREA_SIZE)) goto delete;
	    if (b >= blocks-BB_FAT16_BLOCKS) goto delete;
	    if (map[b>>5] & (1<<(b&31))) goto delete;
	    map[b>>5] |= 1<<(b&31);
	    size += BB_FL_BLOCK_SIZE;
	}
#ifdef BBC_DEBUG
        if (bbc_diag_mode) {
            BBC_LOG(MSG_INFO, "%s\n", line);
            BBC_LOG(MSG_INFO, "computed size %ld, %d blocks\n\n", size, nblks);
        }
#endif
	if (size != in->size) goto delete;
	if (!in->name[0]) goto delete;
	for(j = 1; j < BB_INODE16_NAMELEN; j++)
	    if (in->name[j] && (in->name[j] < ' ' || in->name[j] > '~')) goto delete;
	continue;
delete:
        BBC_LOG(MSG_WARNING, "__osBbFCheck: deleting bad file inode %d %d %.11s %ld %ld %d\n",
	        in-fat->inode, b, in->name, in->size, size, in->block);
	memset(in->name, 0, BB_INODE16_NAMELEN);
	in->size = 0;
	in->type = 0;
	in->block = 0;
	fixed++;
	goto restart;
    }
    /* reclaim unaccounted for blocks */
    for(b = BB_FL_BYTE_TO_BLOCK(BB_SYSTEM_AREA_SIZE);
	    b < blocks-BB_FAT16_BLOCKS; b++) {
	if (map[b>>5] & (1<<(b&31))) continue;
        if (BB_FAT16_NEXT(fat,b) == BB_FAT_BAD) continue;
        if (BB_FAT16_NEXT(fat,b) == BB_FAT_AVAIL) continue;
        BBC_LOG(MSG_INFO, "__osBbFCheck: reclaim block %d\n", b);
	BB_FAT16_NEXT(fat,b) = BB_FAT_AVAIL;
	fixed++;
    }
    /* XXX the following is redundant but does no harm */
    for(i = 0; i < BB_FAT16_BLOCKS; i++) {
	if (BB_FAT16_NEXT(fat, blocks-1-i) != BB_FAT_BAD)
	    BB_FAT16_NEXT(fat, blocks-1-i) = BB_FAT_RESERVED;
    }
    for(i = 0; i < BB_FL_BYTE_TO_BLOCK(BB_SYSTEM_AREA_SIZE); i++) {
	if (BB_FAT16_NEXT(fat, i) != BB_FAT_BAD)
	    BB_FAT16_NEXT(fat, i) = BB_FAT_RESERVED;
    }
    if (fixed)
        rv =__osBbFsSync(hp);
    BBC_LOG(MSG_DIAG, "__osBbFCheck done: %d files\n", files);
    return rv;
}

#ifdef BBC_DIAG
/*
 * File system dump
 *
 * Non-invasive version of Fcheck that takes a block number as
 * an argument
 */
int
__osBbFDump(bbc_hand *hp, int blkno)
{
    BbFat16 *fat;
    int blocks = hp->bh_cardsize;
    flashif_t *fif = hp->bh_flashif;
    BbInode* in;
    u16 i, j, k, m;
    static u32 map[8192/32];	/*XXXblythe move to superblock structure*/
    u8 spare[BB_FL_SPARE_SIZE] DCACHE_ALIGN;
    u16 b;
    u32 size;
    u8 *magic;
    u16 csum, *p;
    int rv = BBC_OK;

    if (blocks <= 0) {
        BBC_LOG(MSG_ERR, "__osBbFDump: invalid block count %d\n", blocks);
	return BBC_BADARG;
    }

    if (blkno >= blocks || blkno < 0) {
        BBC_LOG(MSG_ERR, "__osBbFDump: invalid block number %d\n", blkno);
	return BBC_BADARG;
    }

    if ((fat = malloc((blocks/BB_FAT16_ENTRIES)*sizeof(BbFat16))) == NULL) {
        BBC_LOG_SYSERROR("__osBbFDump: malloc failed");
	return BBC_NOMEM;
    }

    /*
     * Read the supplied block as the first block of a FAT set and follow
     * the links to get the complete FAT
     */
    for (k = 0; k < (blocks/BB_FAT16_ENTRIES); k++) {
        BBC_LOG(MSG_INFO, "fdump read blk %d\n", blkno);
	if (blkno >= blocks || blkno < blocks - BB_FAT16_BLOCKS) {
            BBC_LOG(MSG_ERR, "fdump blk %d out of range\n", blkno);
	    rv = BBC_ERROR;
	    goto err;
	}
        if ((rv = (*fif->read_blocks)(fif->f, blkno, 1, fat+k, spare)) < 0) {
	    BBC_LOG(MSG_ERR, "fat read blk %d fails with %d\n", blkno, rv);
	    goto err;
	}
	/* compute checksum on this fat block */
        p = (u16 *)(fat+k);
        for (csum = m = 0; m < BB_FL_BLOCK_SIZE/sizeof(u16)-1; m++)
	    csum += ntohs(p[m]);
        fat[k].seq = ntohl(fat[k].seq);
        fat[k].link = ntohs(fat[k].link);
        fat[k].cksum = ntohs(fat[k].cksum);
        if ((u16)(fat[k].cksum + csum) != BB_FAT16_CKSUM) {
	    BBC_LOG(MSG_ERR, "bad checksum on block %d = 0x%x\n", blkno, (u16)(fat[k].cksum + csum));
	    rv = BBC_ERROR;
	    goto err;
        }
	magic = (k == 0) ? BB_FAT16_MAGIC : BB_FAT16_LINK_MAGIC;
	if (memcmp(fat[k].magic, magic, sizeof fat[k].magic)) {
            BBC_LOG(MSG_ERR, "bad magic on block %d: %s\n", blkno, fat[k].magic);
	    rv = BBC_ERROR;
            goto err;
	}
        if (fat[k].seq != fat[0].seq) {
	    BBC_LOG(MSG_ERR, "block %d, bad seq on linked fat: %ld != %ld\n", 
                    blkno, fat[k].seq, fat[0].seq);
	    rv = BBC_ERROR;
	    goto err;
	}
	BBC_LOG(MSG_INFO, "block %d, seqno %ld link %d\n",
                blkno, fat[k].seq, fat[k].link);
	blkno = fat[k].link;
    }

    /* have complete FAT, fix endianness */
    for (m = 0; m < blocks; m++)
        BB_FAT16_NEXT(fat,m) = ntohs(BB_FAT16_NEXT(fat,m));
    for (m = 0; m < BB_INODE16_ENTRIES; m++) {
	fat->inode[m].block = ntohs(fat->inode[m].block);
	fat->inode[m].size = ntohl(fat->inode[m].size);
    }

    BBC_LOG(MSG_INFO, "osBbFDump blks %d\n", blocks);
    memset(map, 0, sizeof map);
    for(i = 0; i < BB_INODE16_ENTRIES; i++) {
        char nm[16]; 
        char line[60];
        char blockstring[16];
        int nblks = 0;

	in = fat->inode+i;
	if (!in->type) continue;
	size = 0;
	/* check blocks */
        memset(nm, 0, 16);
        strncpy(nm, in->name, 8); 
        if (in->name[8]) { 
            strcat(nm, ".");
            strncat(nm, &in->name[8], 3); 
        }

        BBC_LOG(MSG_INFO, "inode %d name %s size %ld, blks: \n", i, nm, in->size);
        line[0] = '\0';
	for(b = in->block; b != BB_FAT_LAST; b = BB_FAT16_NEXT(fat,b)) {
            sprintf(blockstring, "%d", b);
            if (nblks)
                strcat(line, ", ");
            /* leave room for ", \0" */
            if (strlen(line) + strlen(blockstring) < sizeof(line) - 3) {
                strcat(line, blockstring);
            }
            else {
                BBC_LOG(MSG_INFO, "%s\n", line);
                line[0] = '\0';
                strcat(line, blockstring);
            }
            nblks++;

	    if (b <  BB_FL_BYTE_TO_BLOCK(BB_SYSTEM_AREA_SIZE))
	        BBC_LOG(MSG_ERR, "block %d in system area\n", b);
	    if (b >= blocks-BB_FAT16_BLOCKS)
	        BBC_LOG(MSG_ERR, "block %d in FAT area\n", b);
	    if (map[b>>5] & (1<<(b&31)))
	        BBC_LOG(MSG_ERR, "block %d duplicate allocation\n", b);
	    map[b>>5] |= 1<<(b&31);
	    size += BB_FL_BLOCK_SIZE;
	}
        BBC_LOG(MSG_INFO, "%s\n", line);
	BBC_LOG(MSG_INFO, "computed size %ld, %d blks\n", size, nblks);
	if (size != in->size)
            BBC_LOG(MSG_ERR, "bad size: inode size %ld\n", in->size);
	if (!in->name[0])
            BBC_LOG(MSG_ERR, "name is null\n");
	for(j = 1; j < BB_INODE16_NAMELEN; j++)
	    if (in->name[j] && (in->name[j] < ' ' || in->name[j] > '~')) {
                BBC_LOG(MSG_ERR, "inode with bad name %d %d %.11s %ld %ld %d\n",
                        in-fat->inode, b, in->name, in->size, size, in->block);
	    }
        BBC_LOG(MSG_INFO, "\n");
    }
    /* reclaim unaccounted for blocks */
    for(b = BB_FL_BYTE_TO_BLOCK(BB_SYSTEM_AREA_SIZE);
	    b < blocks-BB_FAT16_BLOCKS; b++) {
	if (map[b>>5] & (1<<(b&31))) continue;
        if (BB_FAT16_NEXT(fat,b) == BB_FAT_BAD) continue;
        if (BB_FAT16_NEXT(fat,b) == BB_FAT_AVAIL) continue;
        BBC_LOG(MSG_ERR, "unclaimed block %d\n", b);
	BB_FAT16_NEXT(fat,b) = BB_FAT_AVAIL;
    }
err:
    free(fat);
    return rv;
}
#endif /* BBC_DIAG */

/*
 * Check that the card meets the bad block constraints
 *
 * Called after the FAT is initialized.  Blocks marked bad
 * by the manufacturer are marked bad in the FAT by this point.
 */
static int
__bbc_check_fat(bbc_hand *hp)
{
    BbFat16* fat = hp->bh_fat;
    int blocks = hp->bh_cardsize;
    int j;
    int badsys = 0;
    int badblks = 0;
    int bad_fat_blk = 0;

    for (j = 0; j < blocks; j++) {
	if (BB_FAT16_NEXT(fat,j) == BB_FAT_BAD) {
	    badblks++;
	    if (j < SYS_BLOCKS)
		badsys++;
	    if (j >= (blocks - BB_FAT16_BLOCKS))
		bad_fat_blk++;
        }
    }

    /* 
     * There are two reasons that a card will be considered
     * too bad to use:
     *
     * More than 2 bad blocks in the system area
     * More than 1/64th of the total blocks are bad
     */
    if (badsys > BB_MAX_BAD_SYSBLOCKS) {
	BBC_LOG(MSG_ERR, "__bbc_check_fat: too many bad sysblocks: %d\n", badsys);
	return BBC_CARDFAILED;
    }

    if (bad_fat_blk >= BB_MAX_BAD_FATBLOCKS) {
	BBC_LOG(MSG_ERR, "__bbc_check_fat: all fat blocks are bad\n");
	return BBC_CARDFAILED;
    }

    if (badblks > BB_MAX_BAD_BLOCKS) {
	BBC_LOG(MSG_ERR, "__bbc_check_fat: too many bad blocks: %d (max %d of %d)\n",
            badblks, BB_MAX_BAD_BLOCKS, blocks);
	return BBC_CARDFAILED;
    }

    BBC_LOG(MSG_INFO, "__bbc_check_fat ok: badsys %d, total bad %d\n", badsys, badblks);
    return BBC_OK;
}

static u16
chksum(BbFat16 *fat)
{
    u16 *p, csum;
    int m;

    p = (u16 *)fat;
    for (csum = m = 0; m < BB_FL_BLOCK_SIZE/sizeof(u16); m++)
        csum += ntohs(p[m]);
    return csum;
}

/*
 * Read the given block as a FAT
 */
static int
read_fat_blk(bbc_hand *hp, int blkno, BbFat16 *fat, u8 *magic)
{
    flashif_t *fif = hp->bh_flashif;
    u8 spare[BB_FL_SPARE_SIZE] DCACHE_ALIGN;
    int rv;

    /*BBC_LOG(MSG_DEBUG, "read_fat_blk\n"); */
    if ((rv = (*fif->read_blocks)(fif->f, blkno, 1, fat, spare)) < 0) {
        BBC_LOG_BBCERROR("read_fat_blk: read_blocks failed", rv);
        BBC_LOG(MSG_ERR, "fat read blk %d fails\n", blkno);
        return rv;
    }
    BBC_LOG(MSG_DIAG, "read_fat_blk %d: seqno %d link %d\n", 
            blkno, ntohl(fat->seq), ntohs(fat->link));
    /* compute checksum */
    if ((rv = chksum(fat)) != BB_FAT16_CKSUM) {
        BBC_LOG(MSG_ERR, "read_fat_blk %d: bad checksum = 0x%x\n", blkno, (u16)rv);
        return BBC_ERROR;
    }
    if (memcmp(fat->magic, magic, sizeof fat->magic)) {
	BBC_LOG(MSG_ERR, "read_fat_blk %d: bad magic: %s (expecting %s)\n",
                blkno, fat->magic, magic);
	return BBC_ERROR;
    }
    /* fix endianness, but leave block and inode data backwards for now */
    fat->seq = ntohl(fat->seq);
    fat->link = ntohs(fat->link);
    fat->cksum = ntohs(fat->cksum);
    return BBC_OK;
}

/*
 * Follow the links and read the rest of the set of FAT blocks
 * Does nothing on 64MB cards, since they require only one FAT block
 */
static int
read_linked_fats(bbc_hand *hp, BbFat16 *fat)
{
    int blocks = hp->bh_cardsize;
    int k, rv;

    /* check whether linked FATs are valid */
    for (k = 1; k < blocks/BB_FAT16_ENTRIES; k++) {
	if (!fat[k-1].link) {
	    BBC_LOG(MSG_ERR, "read_linked_fats: bad link %d on fat[%d]\n", fat[k-1].link, k-1);
	    return BBC_ERROR;
	}
	if ((rv = read_fat_blk(hp, fat[k-1].link, fat+k, BB_FAT16_LINK_MAGIC)) != BBC_OK) return rv;
	if (fat[k-1].seq != fat[k].seq) {
	    BBC_LOG(MSG_ERR, "bad seq on linked fat: %ld != %ld\n", fat[k].seq, fat[k-1].seq);
	    return BBC_ERROR;
	}
    }
    return BBC_OK;
}

int
__bbc_find_best_fat(bbc_hand *hp)
{
    BbFat16 *fat;
    int blocks = hp->bh_cardsize;
    int j, m;
    u32 seq = 0;
    s32 best = -1;

    if (blocks <= 0) {
        BBC_LOG(MSG_ERR, "__bbc_read_fat: card has invalid block count %d\n", blocks);
        return BBC_ERROR;
    }

    if ((fat = malloc((blocks/BB_FAT16_ENTRIES)*sizeof(BbFat16))) == NULL) {
        BBC_LOG_SYSERROR("__bbc_read_fat: malloc failed");
        return BBC_NOMEM;
    }

    /*
     * Look through all the copies and find the one with valid checksum
     * that has the highest sequence number
     */
    for (j = 0; j < BB_FAT16_BLOCKS; j++) {
	if (read_fat_blk(hp, blocks-1-j, fat, BB_FAT16_MAGIC) == BBC_OK) {
	    if (read_linked_fats(hp, fat) == BBC_OK) {
	        /* valid FAT: if sequence number is bigger, save it */
	        if (fat[0].seq >= seq) {
	            seq = fat[0].seq;
	            best = j;
                    hp->bh_fat_rotor = best;
                    /* fix endianness */
                    for (m = 0; m < blocks; m++)
                        BB_FAT16_NEXT(fat,m) = ntohs(BB_FAT16_NEXT(fat,m));
                    for(m = 0; m < BB_INODE16_ENTRIES; m++) {
	                fat->inode[m].block = ntohs(fat->inode[m].block);
	                fat->inode[m].size = ntohl(fat->inode[m].size);
                    }
	            memcpy(hp->bh_fat, fat, (blocks/BB_FAT16_ENTRIES)*sizeof(BbFat16));
	        }
	    }
	}
    }
    BBC_LOG(MSG_DIAG, "read_fat: best seq = %ld\n", seq);
    free(fat);
    if (best < 0) {
        hp->bh_fat_valid = 0;
        return BBC_NOFORMAT;
    }
    hp->bh_fat_valid = 1;
    return blocks-1-best;
}

int
__bbc_read_fat(bbc_hand *hp)
{
    int rv;
    rv = __bbc_find_best_fat(hp);
    if (rv < 0) return rv;

    /* check file system consistency */
    return __osBbFCheck(hp);
}

int
__bbc_read_system_area(bbc_hand *hp, char *buf, int len)
{
    TIME_T t1, t2;
    BbFat16* fat = hp->bh_fat;
    flashif_t *fif = hp->bh_flashif;
    u8 spare[BB_FL_SPARE_SIZE] DCACHE_ALIGN;
    int i, j;
    int off = 0;
    int badblks = 0;
    int rv = 0;

    if (bbc_diag_mode) TIME(&t1);
    /*
     * Read the system area from the flash using the bad block map
     * in the FAT and special knowledge of the structure of the
     * system area
     */
    i = 0;	/* offset into the logical SKSA image */
    j = 0;	/* actual block number in the flash */
    while (i < len) {
	if (j >= SYS_BLOCKS)
	    break;
	if (badblks > BB_MAX_BAD_SYSBLOCKS)
	    break;
	if (BB_FAT16_NEXT(fat,j) == BB_FAT_BAD) {
	    /*
	     * If this happens in the system app, it means the FAT
	     * bad blocks are out of sync with the links in the
	     * system app.  Just return and force a rewrite of
	     * the whole thing.
	     */
	    badblks++;
	    goto nextbad;
        }
        if ((rv = (*fif->read_blocks)(fif->f, j, 1, buf+i, spare)) < 0) {
            /* Error reading a block that is supposed to be good */
            BBC_LOG_BBCERROR("__bbc_read_system_area: read_blocks failed", rv);
            BBC_LOG(MSG_ERR, "Error reading physical block %d, byte %d\n", j, i);
            if (rv == BBC_BADBLK) {
                /* Block marked bad by manufacturer, mark bad in FAT as well */
                BB_FAT16_NEXT(fat,j) = BB_FAT_BAD;
                badblks++;

                /* Sync change */
                if (__osBbFsSync(hp) != BBC_OK)
                    break;

                /* if this happens in the system app, give up */
                goto nextbad;
            }
            else {
                /* 
                 * Block not readable for some other reason.
                 * Do not need to mark the block bad since it may be recoverable.
                 * Just give up and return.
                 */
                break;
            }            
        }

        i += BB_FL_BLOCK_SIZE;
	off = BB_FL_BYTE_TO_BLOCK(i);
	/* below the system app, blocks are sequential */
        if (off < SA0_OFF)
	    goto next;
	/*
	 * link on the license block points to the first block of the sysapp.
	 * for the rest of the  system app, follow the links
	 * assuming just one sysapp for now.
	 *
	 * the spare area is not protected by ecc, so we store three
	 * copies of the link in successive bytes.  if there is only
	 * a single bit error, then at most one of them is wrong.
	 * if more than one bit is wrong, we lose.
	 */
	if (spare[BB_FL_BLOCK_LINK_OFF] == spare[BB_FL_BLOCK_LINK_OFF+1])
	    j = spare[BB_FL_BLOCK_LINK_OFF];
	else
	    /*
	     * if the first two don't agree, then one of them has the
	     * bad bit and the third one is the one to choose.
	     */
	    j = spare[BB_FL_BLOCK_LINK_OFF+2];
	BBC_LOG(MSG_DEBUG, "rsa: link -> %d\n", j);
	if (j == 0xff || j < SA0_OFF)
	    break;
	continue;
nextbad:
	if (off >= SA0_OFF)
            break;
next:
	j++;
    }

    if (bbc_diag_mode) {
        TIME(&t2);
        BBC_LOG(MSG_DIAG, "__bbc_read_system_area: read %d bytes in %d ms (%.1f KB/s)\n",
                i, __bbcdiag_deltat(t1, t2), 
                __bbcdiag_getKBs(i, __bbcdiag_deltat(t1,t2)));
    }
    /*
     * No need to return error, just return the number of bytes read.
     * There may be blocks that have never been written before and which
     * have bad ECC on read.  In that case, the higher level BBCVerifySKSA 
     * logic will see it as a short read and the images will mismatch.
     * Let it rewrite SKSA and find out if the blocks are really bad or not. 
     */
    return i;
}

/*
 * Writes the system app into system area on the flash, starting at currblk
 * Layout of the SA on the flash will be:
 *         currblk
 *   ... | Ticket | SA blk N | SA blk N-1 | ... | SA blk 1 | ...
 *
 * The first block in buf is the ticket, and the remaining blocks are the system app
 *     buf = ticket | SA
 *     len = length of buf (ticket + SA)
 *
 * Upon the function completion,
 *  currblk will be updated to point to the next available block
 *  badblks will be incremented by the number of bad blocks encountered
 *  firstblk will point to license block for the SA
 *  lastblk  will point to the last block of the SA
 *
 * Return values:
 *   > 0 => the length of data that was written (error if != "len")
 *   < 0 => error occurred
 */
int
__bbc_write_system_app(bbc_hand *hp, int* currblk, int* badblks,
                       int* firstblk, int* lastblk,
                       const char *buf, int len, int skipblks)
{
    BbFat16* fat = hp->bh_fat;
    flashif_t *fif = hp->bh_flashif;
    u8 spare[BB_FL_SPARE_SIZE] DCACHE_ALIGN;
    int licblk = 0;
    int i, j, rv = 0;
    int off = 0, prev = 0;

    if (firstblk) *firstblk = 0;
    if (lastblk)  *lastblk = 0;

    BBC_LOG(MSG_DEBUG, "Write SA: currblk=%d, badblks=%d, buf=0x%08x, len=%u, skipblks=%d\n",
            *currblk, *badblks, buf, len, skipblks);

    if (len <= 0)
	/* nothing to do */
	return rv;

    memset(spare, 0xff, sizeof spare);

    /*
     * First write the license block 
     */
    for (i = 0, j = *currblk; i < BB_FL_BLOCK_TO_BYTE(SL_BLOCKS); j++) {
	if (j >= SYS_BLOCKS)
	    break;
	if (*badblks > BB_MAX_BAD_SYSBLOCKS)
	    break;

	if (BB_FAT16_NEXT(fat,j) == BB_FAT_BAD) {
	    if (firstblk == NULL) {
		/*
		 * We are writing the ticket for SA1 and a bad block can not
		 * be papered over with links in that case, so fail the card.
		 */
	        BBC_LOG(MSG_DEBUG, "__bbc_write_system_app: t1 blk %d already marked bad\n", j);
		return BBC_SKWRITEFAIL;
	    }
	    BBC_LOG(MSG_DEBUG, "__bbc_write_system_app: %d already marked bad\n", j);
	    (*badblks)++;
            continue;
	}
	if (off >= skipblks) {
            if ((rv = (*fif->write_blocks)(fif->f, j, 1, buf+BB_FL_BLOCK_TO_BYTE(off), spare)) < 0) {
                BBC_LOG(MSG_WARNING, "__bbc_write_system_app: write %4d failed with %d\n", j, rv);
                if (rv == BBC_DATAERR) {
		    if (firstblk == NULL) {
		        /*
		         * We are writing the ticket for SA1 and a bad block can not
		         * be papered over with links in that case, so fail the card.
		         */
	                BBC_LOG(MSG_DEBUG, "__bbc_write_system_app: t1 blk %d write failed\n", j);
		        return BBC_SKWRITEFAIL;
		    }
                    BB_FAT16_NEXT(fat,j) = BB_FAT_BAD;
                    (*badblks)++;
                    continue;
                }
                else {
                    /* Other error writing block - abort */
                    goto out;
                }
            }
        }
        else BBC_LOG(MSG_DEBUG, "__bbc_write_system_app: skipping SA ticket block %d\n", j);

	BB_FAT16_NEXT(fat,j) = BB_FAT_RESERVED;
        i += BB_FL_BLOCK_SIZE;
    }

    /* Remember position of license block */
    licblk = j-1;
    if (firstblk) *firstblk = licblk;

    /*
     * The system app "file" uses the link fields in the spare
     * area to chain together the blocks.  The link of the license
     * block points to the first block of the system app.
     *
     * To simplify the handling of the link fields, write the
     * blocks in reverse order
     */
    off = BB_FL_BYTE_TO_BLOCK(len)-1;
    for (; i < len; j++) {
	if (j >= SYS_BLOCKS)
	    break;
	if (*badblks > BB_MAX_BAD_SYSBLOCKS)
	    break;
	if (BB_FAT16_NEXT(fat,j) == BB_FAT_BAD) {
	    BBC_LOG(MSG_DEBUG, "__bbc_write_system_app: %d already marked bad\n", j);
	    (*badblks)++;
            continue;
	}
        /*
	 * There are only 64 blocks in the system area, so the block
	 * number can be represented as a byte.  Store it in three
	 * successive bytes to be robust against single bit errors.
	 * Note that error correction does not happen on the spare area.
	 */
	if (prev) {
	    spare[BB_FL_BLOCK_LINK_OFF] = prev;
	    spare[BB_FL_BLOCK_LINK_OFF+1] = prev;
	    spare[BB_FL_BLOCK_LINK_OFF+2] = prev;
	}
	if (off >= skipblks) {
            if ((rv = (*fif->write_blocks)(fif->f, j, 1,
                                          buf+BB_FL_BLOCK_TO_BYTE(off), spare)) < 0) {
                BBC_LOG(MSG_WARNING, "__bbc_write_system_app: write %4d failed with %d\n", j, rv);
                if (rv == BBC_DATAERR) {
                    BB_FAT16_NEXT(fat,j) = BB_FAT_BAD;
                    (*badblks)++;
                    continue;
                }
                else {
                    /* Other error writing block - abort */
                    goto out;
                }
            }
        }
        else BBC_LOG(MSG_DEBUG, "__bbc_write_system_app: skipping block %d in SA\n", j);
        
        if (lastblk && *lastblk == 0) {
            *lastblk = j;
        }

	BBC_LOG(MSG_DEBUG, "__bbc_write_system_app: link %4d->%4d\n", j, prev ? prev : 0xff);
	BB_FAT16_NEXT(fat,j) = BB_FAT_RESERVED;
	prev = j;
	off--;
        i += BB_FL_BLOCK_SIZE;
    }

    *currblk = j;

    /*
     * If the system app was written successfully, go back and
     * update the link of the license block to point to the first 
     * block of the SA.
     */
    if (rv == 0 && i == len && 0 >= skipblks) {
        /*
	 * See comment above about the handling of the link fields
	 */
	j--;
	spare[BB_FL_BLOCK_LINK_OFF] = j;
	spare[BB_FL_BLOCK_LINK_OFF+1] = j;
	spare[BB_FL_BLOCK_LINK_OFF+2] = j;
	BBC_LOG(MSG_DEBUG, "license blk %d -> %d (off %d)\n", licblk, j, 0);
	if ((rv = (*fif->write_blocks)(fif->f, licblk, 1, buf, spare)) < 0) {
	    BBC_LOG(MSG_ERR, "rewrite %d failed with %d!\n", licblk, rv);
            if (rv == BBC_DATAERR) {
                BB_FAT16_NEXT(fat, licblk) = BB_FAT_BAD;
                (*badblks)++;
            }
	}
    }

out:
    /*
     * Update the fat, since we have marked blocks as RESERVED or BAD.
     */
    if (!BBC_IO_ERR(rv)) {
        int res = __osBbFsSync(hp);
        if (rv == BBC_OK) rv = res;
    }
    if (*badblks > BB_MAX_BAD_SYSBLOCKS)
	rv = BBC_CARDFAILED;

    // If error, returns error code, otherwise the number of bytes written
    return (rv < 0)? rv: i;
}


/*
 * Write the system area to the flash using the bad block map
 * in the FAT and special knowledge of the structure of the
 * system area.  Only starts writing blocks after skipblks.
 *
 * NOTE: It is possible if a first block that we actually write 
 * develops into a bad block, then the last skipped block, will
 * not be pointing correctly to the next block.
 */
int
__bbc_write_system_area(bbc_hand *hp, const char *buf, int len, int skipblks)
{
    BbFat16* fat = hp->bh_fat;
    flashif_t *fif = hp->bh_flashif;
    u8 spare[BB_FL_SPARE_SIZE] DCACHE_ALIGN;
    int badblks = 0;
    int i, j;
    int off = 0, rv = 0;
    int sa1len, sa1blocks;
    int sa1last, sa2first;

    if (BB_FL_BLOCK_TO_BYTE(skipblks) > len) {
        /* nothing to do */
        return 0; 
    }

    /* Verify the buffer is large enough to contain SK + Ticket */
    if (len < BB_FL_BLOCK_TO_BYTE(SL0_OFF + SL_BLOCKS)) {
        BBC_LOG(MSG_ERR, "Buffer too small for T1, len=%d\n", len);
        return BBC_BADLENGTH;
    }

    /* Figure out the size of SA1 */ 
    sa1len = BBC_GET_SA_SIZE(buf+BB_FL_BLOCK_TO_BYTE(SL0_OFF));
    sa1blocks = BB_FL_BYTE_TO_BLOCK(sa1len);
    BBC_LOG(MSG_DEBUG, "SA1Len=%d, SA1Blocks=%d\n", sa1len, sa1blocks);

    /* Verify sa1len */
    if (sa1len <= 0) {
        BBC_LOG(MSG_ERR, "SA1Len %d should be greater than 0\n", sa1len);
        return BBC_BADLENGTH;
    }

    /* Verify the buffer is large enough to contain SA1 */
    if (len < BB_FL_BLOCK_TO_BYTE(SA0_OFF) + sa1len) {
        BBC_LOG(MSG_ERR, "Buffer too small for SA1, sa1len=%d, len=%d\n",
                sa1len, len);
        return BBC_BADLENGTH;
    }

    /* 
     * REVIEW: Because of the layout of the SKSA as
     * SK[1] | ... | SK[4] | T1 | SA1[n1] | ... | SA1[1] | T2 | SA2[n2] | ... | SA2[1]
     * with links from T1 to SA1[1], SA1[i] to SA1[i+1], SA1[n1] to T2
     *                 T2 to SA2[1], SA2[i] to SA2[i+1]
     * It is impossible to start from an arbitrary block and start writing from there
     * unless the sizes of SA1 and SA2 remains fixed.  For instance, if SA2 were to
     * grow, the layout of all the blocks after T2 will be shifted.
     *
     * This means that this function only works for skip blocks with the following
     * values: within the SK, at T1 or T2.
     *
     * Note that with this structure it is impossible for SA1 and SA2's size
     * (or content for that matter) to change without T1 and T2 changing as well.
     * But we cannot enforce these restrictions for the following reason:  it is
     * possible to get cases in which the new image matches the old one at least
     * up to the end of T2.  One way this can happen is if a BBCVerifySKSA gets
     * interrupted by loss of power or the user pulling the card.  If we enforce
     * the skip boundary restriction, then the card can not be updated by a subsequent
     * BBCVerifySKSA2 with force == 1.  The solution to this problem is to modify the
     * skip boundary to extend it backwards to the previous ticket.
     */

    /* If the skipblks value is within SA1, then reset it to T1 */
    if ((skipblks > SL0_OFF) && (skipblks < SA0_OFF + sa1blocks)) {
        skipblks = SL0_OFF;
        BBC_LOG(MSG_DEBUG, "Skip value within SA1, reset to %d\n", skipblks);
    } else
        /* If skipblks is past T2, then reset it to T2 */
        if (skipblks > SA0_OFF + sa1blocks) {
            skipblks = SA0_OFF + sa1blocks;
            BBC_LOG(MSG_DEBUG, "Skip value within SA2, reset to %d\n", skipblks);
        }

    BBC_LOG(MSG_INFO, "Rewrite SKSA skipping first %d blocks (%d bytes)\n",
        skipblks, BB_FL_BLOCK_TO_BYTE(skipblks));

    /* Write the SK */
    memset(spare, 0xff, sizeof spare);
    for (i = j = 0; i < len; j++) {
	if (j >= SYS_BLOCKS)
	    break;
	if (BB_FAT16_NEXT(fat,j) == BB_FAT_BAD) {
	    BBC_LOG(MSG_ERR, "wsa: sk block %d already marked bad\n", j);
            rv = BBC_SKWRITEFAIL;
            goto out;
	}
        if (i >= BB_FL_BLOCK_TO_BYTE(skipblks)) {
            if ((rv = (*fif->write_blocks)(fif->f, j, 1, buf+i, spare)) < 0) {
                BBC_LOG(MSG_ERR, "wsa: write sk blk %4d failed with %d\n", j, rv);
                BBC_LOG(MSG_CRIT, "Error writing SK %d\n", rv);
		if (rv == BBC_DATAERR)
		    rv = BBC_SKWRITEFAIL;
                goto out;
            }
        }
        else BBC_LOG(MSG_DEBUG, "skipping block %d\n", j);

	BB_FAT16_NEXT(fat,j) = BB_FAT_RESERVED;
        i += BB_FL_BLOCK_SIZE;
	off = BB_FL_BYTE_TO_BLOCK(i);
	/* below the system app, blocks are sequential */
	if (off >= SL0_OFF)
        {
            j++;
	    break;
        }
    }

    /*
     * Update the fat, since we have marked blocks as RESERVED or BAD.
     */
    if (!BBC_IO_ERR(rv)) {
        int res = __osBbFsSync(hp);
        if (rv == BBC_OK) rv = res;
    }
    if (badblks > BB_MAX_BAD_SYSBLOCKS) {
	return BBC_CARDFAILED;
    }

    /* Write SA1 */
    rv = __bbc_write_system_app(hp, &j, &badblks, NULL, &sa1last,
                                buf+BB_FL_BLOCK_TO_BYTE(SL0_OFF),
                                BB_FL_BLOCK_SIZE + sa1len, skipblks - SL0_OFF);
    if (rv < 0) {
        BBC_LOG(MSG_CRIT, "Error writing SA1 %d\n", rv);
        return rv;
    }
    i += rv;

    /*
     * This code is still used on the EMS depot to write SKSA bundles that
     * have the original SK + T1 + SA1 format with no SA2.  In that case,
     * we will already be done at this point.
     */
    if (i >= len)
	goto out;

    /* Write SA2 */
    rv = __bbc_write_system_app(hp, &j, &badblks, &sa2first, NULL,
                                buf+BB_FL_BLOCK_TO_BYTE(SA0_OFF + sa1blocks),
                                len - BB_FL_BLOCK_TO_BYTE(SA0_OFF + sa1blocks),
                                skipblks - SA0_OFF - sa1blocks);

    if (rv < 0) {
        BBC_LOG(MSG_CRIT, "Error writing SA2 %d\n", rv);
        return rv;
    }
    i += rv;

    /* 
     * If both SA1 and SA2 were written successfully, go back and
     * create link from the last block of SA1 to the ticket of SA2
     * Only do this if we don't want to skip the writing of the last
     * block of SA1 (block link should be good - pointing to T2 as long
     * as that block remains good)
     */
    off = SA0_OFF + sa1blocks - 1;
    if (i == len && off >= skipblks) {
	spare[BB_FL_BLOCK_LINK_OFF] = sa2first;
	spare[BB_FL_BLOCK_LINK_OFF+1] = sa2first;
	spare[BB_FL_BLOCK_LINK_OFF+2] = sa2first;
	BBC_LOG(MSG_DEBUG, "SA1 last blk %d -> %d (off %d)\n", sa1last, sa2first, off);
	if ((rv = (*fif->write_blocks)(fif->f, sa1last, 1, 
                                       buf + BB_FL_BLOCK_TO_BYTE(off), spare)) < 0) {
	    BBC_LOG(MSG_ERR, "rewrite %d failed with %d!\n", sa1last, rv);
            if (rv == BBC_DATAERR) {
                BB_FAT16_NEXT(fat, sa1last) = BB_FAT_BAD;
                badblks++;
            }
	}
    }

out:
    /*
     * Update the fat, since we have marked blocks as RESERVED or BAD.
     */
    if (!BBC_IO_ERR(rv)) {
        int res = __osBbFsSync(hp);
        if (rv == BBC_OK) rv = res;
    }
    if (badblks > BB_MAX_BAD_SYSBLOCKS)
	rv = BBC_CARDFAILED;

    return (rv < 0)? rv:i;
}

static void
__osBbFsFormatName(char fname[BB_INODE16_NAMELEN], const char* name)
{
    int i, j;
    /* reformat name to XXXXXXXXYYY filling with 0s */
    for(i = 0; name[i] && name[i] != '.' && i < BB_INODE16_NAMELEN-3; i++)
	fname[i] = name[i];
    for(j = i; j < BB_INODE16_NAMELEN-3; j++) fname[j] = '\0';
    if (name[i] == '.') {
	i++;
	while(name[i] && j < BB_INODE16_NAMELEN)
	    fname[j++] = name[i++];
    }
    while(j < BB_INODE16_NAMELEN)
	fname[j++] = '\0';
}

void
__bbc_format_name(char fname[BB_INODE16_NAMELEN], const char* name)
{
    __osBbFsFormatName(fname, name);
}

/*
 * Fix endianness for a complete FAT (may be multiple blocks)
 */
static void
swab_fat(bbc_hand *hp, BbFat16 *fat)
{
    int i, k;
    int blocks = hp->bh_cardsize;
    u16 *p;
    u16 csum;

    /* fix all blocks and inodes */
    for(i = 0; i < blocks; i++)
        BB_FAT16_NEXT(fat,i) = htons(BB_FAT16_NEXT(fat,i));
    for(i = 0; i < BB_INODE16_ENTRIES; i++) {
	fat->inode[i].block = htons(fat->inode[i].block);
	fat->inode[i].size = htonl(fat->inode[i].size);
    }

    /* fix the rest including the checksum */
    p = (u16*)fat;
    for (k = 0; k < blocks/BB_FAT16_ENTRIES; k++) {
        fat[k].seq = htonl(fat[k].seq);
        fat[k].link = htons(fat[k].link);
        /* update checksum */
        for(csum = i = 0; i < BB_FL_BLOCK_SIZE/sizeof(u16)-1; i++)
	    csum += ntohs(p[k*BB_FL_BLOCK_SIZE/sizeof(u16)+i]);
        fat[k].cksum = htons( (u16) (BB_FAT16_CKSUM - csum) );
    }
}

int
__osBbFsSync(bbc_hand *hp)
{
    BbFat16* fat = hp->bh_fat;
    BbFat16* wfat;
    int blocks = hp->bh_cardsize;
    int target;
    flashif_t *fif = hp->bh_flashif;
    u16 sum, *p, link;
    u8 spare[BB_FL_SPARE_SIZE] DCACHE_ALIGN;
    int tries, k, rv;

    /*
     * recompute the checksum/version number and write out the
     * FAT blocks to the 'next' FAT block using a simple rotor
     */
    BBC_LOG(MSG_ALL, "FsSync\n");
    memset(spare, 0xff, sizeof(spare));
    if ((wfat = malloc(BB_FL_MAX_FATS*sizeof(BbFat16))) == NULL) {
	BBC_LOG_SYSERROR("__osBbFsSync: malloc failed");
	return BBC_NOMEM;
    }
#if BBC_MARK_BAD_FATS
restart:
#endif
    tries = 0;
    link = 0;
    target = hp->bh_fat_rotor;
    for(k = blocks/BB_FAT16_ENTRIES; --k >= 0;) {
	fat[k].seq++;
	fat[k].link = 0;
	sum = fat[k].cksum = 0;
	for(p = (u16*)(fat+k); p < (u16*)(fat+k)+BB_FL_BLOCK_SIZE/2; p++)
	    sum += *p;
	fat[k].cksum = BB_FAT16_CKSUM - sum;
    }

    memcpy(wfat, fat, BB_FL_MAX_FATS*sizeof(BbFat16));
    swab_fat(hp, wfat);
	
    for(k = blocks/BB_FAT16_ENTRIES; --k >= 0;) {
	fat[k].link = link;
	wfat[k].link = htons(link);
	/* adjust checksums */
	fat[k].cksum -= fat[k].link;
	wfat[k].cksum = htons( (u16) (ntohs(wfat[k].cksum) - link) ) ;
	for( ; tries < BB_FAT16_BLOCKS; tries++) {
	    target++;
	    if (target >= BB_FAT16_BLOCKS) target = 0;
	    link = blocks-1-target;
	    /* don't try to write blks known to be bad */
	    if (BB_FAT16_NEXT(fat,link) == BB_FAT_BAD) continue;
	    if ((rv = (*fif->write_blocks)(fif->f, link, 1, wfat+k, spare)) == BBC_OK)
                goto next;
#if BBC_MARK_BAD_FATS
            if (rv == BBC_DATAERR) {
                /*
                 * write failed, mark block bad in FAT and restart, since we need to
                 * recalculate the checksum and redo the byte-swapping
                 */
                BB_FAT16_NEXT(fat,link) = BB_FAT_BAD;
                goto restart;
            }
            else {
                /* Some horrible unknown error - abort */
                goto err;
            }
#else
            goto err;
#endif
	}
	/* all writes failed */
	rv = BBC_CARDFAILED;
	goto err;
next:;
    }
    hp->bh_fat_rotor = target;
    rv = BBC_OK;
err:
    free(wfat);
    BBC_LOG(MSG_DEBUG, "FsSync returns %d\n", rv);

    /* make sure BB has the same version of the FAT */
    if (!BBC_IO_ERR(rv)) {
        int res = __bbc_sync_fat(hp);
        if (rv == BBC_OK) rv = res;
    }
    return rv;
}


int
__BBC_FCreate(bbc_hand *hp, const char* name, u8 type, u32 len)
{
    u16 i, b, prev = 0;
    BbInode* in = 0;
    BbFat16* fat = hp->bh_fat;
    int blocks = hp->bh_cardsize;
    s32 rv = 0;
    s16 incr;
    char fname[BB_INODE16_NAMELEN];

    BBC_LOG(MSG_DEBUG, "fcreate %s len %ld\n", name, len);
    if (len&(BB_FL_BLOCK_SIZE-1)) return BBC_BADLENGTH;
    __osBbFsFormatName(fname, name);
    if (!fname[0]) {
        BBC_LOG(MSG_ERR, "__BBC_FCreate: Cannot format name %s\n", name);
        return BBC_ERROR;
    }
    /* check if entry already exists and find free inode */
    rv = BBC_ERROR;
    for(i = 0; i < BB_INODE16_ENTRIES; i++) {
        if (fat->inode[i].type && memcmp(fname, fat->inode[i].name, BB_INODE16_NAMELEN) == 0)
            goto out;
        if (fat->inode[i].type == 0 && !in)
            in = fat->inode+i;
    }
    if (!in) {
        rv = BBC_NOSPACE;
        goto out;
    }

    if (len > BB_BIG_FILE_THRESHOLD) {
        /* big files go low in the fat */
        b = BB_FL_BYTE_TO_BLOCK(BB_SYSTEM_AREA_SIZE); incr = 1;
    } else {
        /* small files at the other end */
        b = blocks-1; incr = -1;
    }
    in->block = BB_FAT_LAST;
    for(i = 0; i < BB_FL_BYTE_TO_BLOCK(len+BB_FL_BLOCK_SIZE-1); i++) {
        /* allocate a block */
        while(b < blocks && BB_FAT16_NEXT(fat,b) != BB_FAT_AVAIL)
            b += incr;
        if (b >= blocks) {
            rv = BBC_NOSPACE;
            goto error_undo;
        }
        BB_FAT16_NEXT(fat,b) = BB_FAT_LAST;
        if (prev) BB_FAT16_NEXT(fat,prev) = b;
        else in->block = b;
        prev = b;
    }
    memcpy(in->name, fname, BB_INODE16_NAMELEN);
    in->type = 1;
    in->size = len;
    if ((rv = __osBbFsSync(hp)) == 0) {
        rv = in-fat->inode;
        goto out;
    }
error_undo:
    BBC_LOG(MSG_ERR, "fcreate fails ... deallocate\n");
    /* deallocate pending allocations */
    b = in->block;
    while(b != BB_FAT_LAST) {
        u16 n = BB_FAT16_NEXT(fat,b);
        BB_FAT16_NEXT(fat,b) = BB_FAT_AVAIL;
        b = n;
    }
    in->name[0] = '\0';
    in->size = in->block = 0;
out:
    BBC_LOG(MSG_DEBUG, "fcreate returns %ld\n", rv);
    return rv;
}

int
__bbc_fopen(bbc_hand *hp, const char* name, const char* mode)
{
    unsigned char fname[BB_INODE16_NAMELEN+1];
    int i;
    int rv;
    BbFat16* fat = hp->bh_fat;

    __osBbFsFormatName(fname, name);
    fname[BB_INODE16_NAMELEN] = '\0';
    if (!fname[0]) {
        BBC_LOG(MSG_ERR, "__bbc_fopen: Cannot format name %s\n", name);
        return BBC_ERROR;
    }
    for(i = 0; i < BB_INODE16_ENTRIES; i++) {
	if (fat->inode[i].type &&
	    memcmp(fname, fat->inode[i].name, BB_INODE16_NAMELEN) == 0) {
	    rv = i;
            BBC_LOG(MSG_DEBUG, "__bbc_fopen %s (%s) at %d\n", name, fname, rv);
	    goto out;
	}
    }
    rv = BBC_NOFILE;
    BBC_LOG(MSG_DEBUG, "__bbc_fopen %s (%s) not found\n", name, fname);
out:
    return rv;
}

int
__bbc_fstat(bbc_hand *hp, int fd, OSBbStatBuf *sb, u16* blockList, u32 listLen)
{
    s32 rv = BBC_ERROR;
    BbInode* in;
    BbFat16* fat = hp->bh_fat;
    if (fd < 0 || fd >= BB_INODE16_ENTRIES) return rv;
    in = fat->inode+fd;
    /* check size, etc */
    if (!in->type) return rv;
    sb->type = in->type;
    sb->size = in->size;
    if (blockList && listLen) {
	u16 b;
        u32 i;
	/* retrieve block list */
	b = in->block;
	for(i = 0; b != BB_FAT_LAST && i < listLen; i++) {
	    blockList[i] = b;
	    b = BB_FAT16_NEXT(fat,b);
	}
	if (i < listLen)
	    blockList[i] = 0;
    }
    BBC_LOG(MSG_DEBUG, "fstat returns size %ld\n", sb->size);
    return BBC_OK;
}

static int
__osBbFReallocBlock(bbc_hand *hp, BbInode* in, u16 blk)
{
    u16 b, ob, prev = 0;
    int incr, rv;
    BbFat16* fat = hp->bh_fat;
    int blocks = hp->bh_cardsize;

    /* find new block */
    if (in->size > BB_BIG_FILE_THRESHOLD) {
	/* big files go low in the fat */
	b = BB_FL_BYTE_TO_BLOCK(BB_SYSTEM_AREA_SIZE); incr = 1;
    } else {
	/* small files at the other end */
	b = blocks-1; incr = -1;
    }
    while(b < blocks && BB_FAT16_NEXT(fat,b) != BB_FAT_AVAIL)
	b += incr;
    if (b >= blocks) goto error;

    /* find old block */
    ob = in->block;
    while(ob != blk) {
	prev = ob;
	ob = BB_FAT16_NEXT(fat,ob);
    }
    if (prev)
	BB_FAT16_NEXT(fat,prev) = b;
    else
	in->block = b;
    BB_FAT16_NEXT(fat,b) = BB_FAT16_NEXT(fat,ob);
    BB_FAT16_NEXT(fat,ob) = BB_FAT_BAD;
    /* sync the metadata */
    if ((rv = __osBbFsSync(hp)) == 0)
	return b;
    /*XXXblythe now what to do?*/
error:
    return BB_FAT_BAD;
}

int
__BBC_FReadDir(bbc_hand *hp, OSBbDirEnt *dir, u32 count)
{
    int rv = 0;
    u32 i, j;
    BbInode* in;
    BbFat16* fat = hp->bh_fat;
    OSBbDirEnt* d = dir;

    for (j = i = 0; i < BB_INODE16_ENTRIES; i++) {
	s32 k;
	if (!(in = fat->inode+i)->type) continue;
	rv++;
	if (!d && j >= count) continue;
	d->type = in->type;
	d->size = in->size;
	for(k = 0; in->name[k] && k < BB_INODE16_NAMELEN-3; k++)
	    d->name[k] = in->name[k];
	if (in->name[BB_INODE16_NAMELEN-3]) {
	    d->name[k] = '.';
	    memcpy(d->name+k+1, in->name+BB_INODE16_NAMELEN-3, 3);
	    d->name[k+1+3] = '\0';
	} else
	    d->name[k] = '\0';
	d++; j++;
    }
    BBC_LOG(MSG_DEBUG, "freaddir returns %d\n", rv);
    return rv;
}

int
__BBC_FRenameAll(bbc_hand *hp, const char* old, const char* new,
                 const char* ignoreExts[], int nIgnoreExts) 
{
    unsigned char fold[BB_INODE16_NAMELEN], fnew[BB_INODE16_NAMELEN];
    int rv;
    BbFat16* fat = hp->bh_fat;
    int i, count, namelen;
    BBC_LOG(MSG_DEBUG, "__BBC_FRenameAll %s.* to %s.*\n", old, new);
    __osBbFsFormatName(fold, old);
    __osBbFsFormatName(fnew, new);
    if (!fold[0] || !fnew[0]) {
        if (!fold[0]) {
            BBC_LOG(MSG_ERR, "__BBC_FRenameAll: Cannot format old name %s\n", old);
        }
        if (!fnew[0]) {
            BBC_LOG(MSG_ERR, "__BBC_FRenameAll: Cannot format new name %s\n", new);
        }
        return BBC_ERROR;
    }
    
    namelen = BB_INODE16_NAMELEN - 3;
    count = 0;
    for (i = 0; i < BB_INODE16_ENTRIES; i++) {
	if (fat->inode[i].type) {
            int j, ignoreFile = 0;
            for (j = 0; j < nIgnoreExts; j++) {
                if (memcmp(fat->inode[i].name + BB_INODE16_NAMELEN - 3,
                           ignoreExts[j], 3) == 0) {
                    ignoreFile = 1;
                    break;                    
                }
            }

            if (!ignoreFile) {
                if (memcmp(fold, fat->inode[i].name, namelen) == 0) {
                    /* Do rename */
                    memcpy(fat->inode[i].name, fnew, namelen);
                    count++;

                    /* Check if there is already file with same new name */
                    /* and delete that file */
                    for (j = 0; j < BB_INODE16_ENTRIES; j++) {
                        if ((j != i) && fat->inode[j].type) {
                            if (memcmp(fat->inode[i].name, 
                                       fat->inode[j].name,
                                       BB_INODE16_NAMELEN) == 0) {
                                u16 b;
                                /* free all of the blocks */
                                for (b = fat->inode[j].block; 
                                     b != BB_FAT_LAST; ) {
                                    u16 o = BB_FAT16_NEXT(fat,b);
                                    BB_FAT16_NEXT(fat,b) = BB_FAT_AVAIL;
                                    b = o;
                                }
                                memset(fat->inode+j, 0, sizeof(BbInode));
                            }
                        }
                    }
                }
            }
	}
    }

    if (count > 0) {
        rv = __osBbFsSync(hp);
        if (rv >= 0) rv = count;
    }
    else rv = 0;

    BBC_LOG(MSG_DEBUG, "__BBC_FRenameAll returns %d\n", rv);
    return rv;
}


int
__BBC_FRename(bbc_hand *hp, const char* old, const char* new) 
{
    unsigned char fold[BB_INODE16_NAMELEN], fnew[BB_INODE16_NAMELEN];
    int rv, inew = -1, iold = -1;
    BbFat16* fat = hp->bh_fat;
    int i;
    BBC_LOG(MSG_DEBUG, "frename %s to %s\n", old, new);
    __osBbFsFormatName(fold, old);
    __osBbFsFormatName(fnew, new);
    if (!fold[0] || !fnew[0]) {
        if (!fold[0]) {
            BBC_LOG(MSG_ERR, "__BBC_FRename: Cannot format old name %s\n", old);
        }
        if (!fnew[0]) {
            BBC_LOG(MSG_ERR, "__BBC_FRename: Cannot format new name %s\n", new);
        }
        return BBC_ERROR;
    }
    for (i = 0; i < BB_INODE16_ENTRIES; i++) {
	if (fat->inode[i].type) {
	    if (memcmp(fnew, fat->inode[i].name, BB_INODE16_NAMELEN) == 0)
		inew = i;
	    else if (memcmp(fold, fat->inode[i].name, BB_INODE16_NAMELEN) == 0)
	        iold = i;
	}
    }
    if (iold == -1) {
        BBC_LOG(MSG_ERR, "frename %s does not exist\n", old);
	rv = BBC_NOFILE;
	goto error;
    } else if (inew != -1) {
	u16 b;
	/* free all of the blocks */
	for (b = fat->inode[inew].block; b != BB_FAT_LAST; ) {
	    u16 o = BB_FAT16_NEXT(fat,b);
	    BB_FAT16_NEXT(fat,b) = BB_FAT_AVAIL;
	    b = o;
	}
	memset(fat->inode+inew, 0, sizeof(BbInode));
    }
    memcpy(fat->inode[iold].name, fnew, BB_INODE16_NAMELEN);
    rv = __osBbFsSync(hp);
error:
    BBC_LOG(MSG_DEBUG, "frename returns %d\n", rv);
    return rv;
}

int
__BBC_FRead(bbc_hand *hp, int fd, int off, void *buf, u32 len)
{
    TIME_T t1, t2;
    int rv = BBC_ERROR;
    BbInode* in;
    u32 count, i;
    BbFat16* fat = hp->bh_fat;
    int b, blocks = hp->bh_cardsize;
    flashif_t *fif = hp->bh_flashif;
    char spare[BB_FL_SPARE_SIZE];
#ifndef WIN32
#ifdef _DEBUG
    if ((u32)buf&15) return rv;
#endif
#endif
    if (fd < 0 || fd >= BB_INODE16_ENTRIES) return rv;
    in = fat->inode+fd;
    rv = BBC_BADLENGTH;
    if (len & (BB_FL_BLOCK_SIZE-1)) goto error;
    /* check size, etc */
    rv = BBC_ERROR;
    if (!in->type) goto error;
    if ((off & (BB_FL_BLOCK_SIZE-1)) || off >= in->size) goto error;
    if (off+len < off) goto error; /* overflow */
    if (off+len > in->size) len = in->size-off;
    if (!len) {
	rv = 0;
	goto error;
    }

    /* find starting block */
    b = in->block;
    for(i = 0; i < BB_FL_BYTE_TO_BLOCK(off); i++)
	b = BB_FAT16_NEXT(fat,b);
    count = 0;
    if (bbc_diag_mode) TIME(&t1);
    while(len > 0) {
	if (b == 0 || b >= blocks-BB_FAT16_BLOCKS) goto error;
	if ((rv = (*fif->read_blocks)(fif->f, b, 1, buf, spare)) != BBC_OK) goto error;
	b = BB_FAT16_NEXT(fat,b);
#ifndef WIN32
	buf += BB_FL_BLOCK_SIZE;
#else
	(u8*)buf += BB_FL_BLOCK_SIZE;
#endif
	len -= len > BB_FL_BLOCK_SIZE ? BB_FL_BLOCK_SIZE : len;
	count += BB_FL_BLOCK_SIZE;
	__bbc_bytes_read += BB_FL_BLOCK_SIZE;
    }
    rv = count;
    if (bbc_diag_mode) {
        TIME(&t2);
        BBC_LOG(MSG_DIAG, "BBCFRead read %d bytes in %d ms (%.1f KB/s)\n",
                count, __bbcdiag_deltat(t1, t2), 
                __bbcdiag_getKBs(count, __bbcdiag_deltat(t1,t2)));
    }
        
error:
    BBC_LOG(MSG_DEBUG, "fread returns %d\n", rv);
    return rv;
}


int
__BBC_FWrite(bbc_hand *hp, int fd, int off, const void *buf, u32 len)
{
    TIME_T t1, t2;
    int rv;
    BbInode* in;
    u32 count, i, totallen, startbytes;
    BbFat16* fat = hp->bh_fat;
    int blocks = hp->bh_cardsize;
    flashif_t *fif = hp->bh_flashif;
#define MULTIPLANE
#ifdef MULTIPLANE
    u16 blks[4], n, b;
    u8 spare[BB_FL_SPARE_SIZE*4] DCACHE_ALIGN;
#else
    u8 spare[BB_FL_SPARE_SIZE] DCACHE_ALIGN;
#endif
#ifndef WIN32
#ifdef _DEBUG
    if ((u32)buf&15) return BBC_ERROR;
#endif
#endif
    if (fd < 0 || fd >= BB_INODE16_ENTRIES) return BBC_ERROR;
    memset(spare, 0xff, sizeof(spare));
    in = fat->inode+fd;
    rv = BBC_BADLENGTH;
    if (len & (BB_FL_BLOCK_SIZE-1)) goto error;
    /* check size, etc */
    rv = BBC_ERROR;
    if (!in->type) goto error;
    if ((off & (BB_FL_BLOCK_SIZE-1)) || off >= in->size) goto error;
    if (len & (BB_FL_BLOCK_SIZE-1)) goto error;
    if (off+len < off) goto error; /* overflow */
    if (off+len > in->size) goto error;
    if (!len) {
	rv = 0;
	goto error;
    }

    /* find starting block */
    b = in->block;
    for(i = 0; i < BB_FL_BYTE_TO_BLOCK(off); i++)
	b = BB_FAT16_NEXT(fat,b);
    count = 0;
    if (bbc_diag_mode) TIME(&t1);
    totallen = len;
    startbytes = __bbc_bytes_written;
#ifdef MULTIPLANE
    /* do 4 blocks at a time */
    while (len > 0) {
	for(n = 0; len > 0 && n < 4; n++) {
	    if (b == 0 || b >= blocks-BB_FAT16_BLOCKS) goto error;
	    blks[n] = b;
	    b = BB_FAT16_NEXT(fat,b);
	    len = len > BB_FL_BLOCK_SIZE ? len - BB_FL_BLOCK_SIZE : 0;
	    count += BB_FL_BLOCK_SIZE;
	    if (b != blks[n]+1 || (b & 3) == 0) {
		n++;
		break;
	    }
	}
	if ((rv = (*fif->write_blocks)(fif->f, blks[0], n, buf, spare)) != BBC_OK) {
	    int i;
            /* Abort unless we have a bad block (BBC_DATAERR) */
	    if (rv != BBC_DATAERR) {
                BBC_LOG(MSG_ERR, "__BBC_FWrite: writing %d blocks, at block %d failed with %d\n",
                        n, blks[0], rv);
                BBC_LOG(MSG_INFO, "__BBC_FWrite: %d of %d bytes were successfully written\n",
                        __bbc_bytes_written - startbytes, totallen);
               goto error;
            }
            BBC_LOG(MSG_WARNING, "__BBC_FWrite: bad block while writing %d blocks: retrying one by one\n", n);
	    /* determine which blocks are bad, by repeating one at a time */
	    /* XXX this is a mistake!  Samsung says never retry failed erase or write */
	    for(i = 0; i < n; i++) {
		u16 b = blks[i];
retry:
#ifndef WIN32
	        if ((rv = (*fif->write_blocks)(fif->f, b, 1, buf+i*BB_FL_BLOCK_SIZE, spare)) != BBC_OK) {
#else
	        if ((rv = (*fif->write_blocks)(fif->f, b, 1, (u8*)buf+i*BB_FL_BLOCK_SIZE, spare)) != BBC_OK) {
#endif
                    if (rv == BBC_DATAERR) {
                        /* 
                         * Only try to reallocate block (which will mark the block as
                         *  bad in the FAT) if we get BBC_DATAERR.
                         */
                        if ((b = __osBbFReallocBlock(hp, in, b)) == BB_FAT_BAD)
                            goto error;
                        else goto retry; /* Block successfully reallocated */
                    }

                    /* For all other error codes, we will abort */
		    goto error;
		}
            }
	}        
#ifndef WIN32
	buf += BB_FL_BLOCK_SIZE*n;
#else
	(u8*)buf += BB_FL_BLOCK_SIZE*n;
#endif
	__bbc_bytes_written += BB_FL_BLOCK_SIZE*n;
    }
#else /* not MULTIPLANE */
    while (len > 0) {
	if (b == 0 || b >= blocks-BB_FAT16_BLOCKS) goto error;
retry:
	if ((rv = (*fif->write_blocks)(fif->f, b, 1, buf, spare)) != BBC_OK) {
            if (rv == BBC_DATAERR) {
                /* 
                 * Only try to reallocate block (which will mark the block as
                 *  bad in the FAT) if we get BBC_DATAERR.
                 */
                if ((b = __osBbFReallocBlock(hp, in, b)) == BB_FAT_BAD)
                    goto error;
                else goto retry; /* Block successfully reallocated */
            }
            
            /* For all other error codes, we will abort */
            goto error;
	}
	b = BB_FAT16_NEXT(fat,b);
	buf += BB_FL_BLOCK_SIZE;
	len = len > BB_FL_BLOCK_SIZE ? len - BB_FL_BLOCK_SIZE : 0;
	count += BB_FL_BLOCK_SIZE;
	__bbc_bytes_written += BB_FL_BLOCK_SIZE;
    }
#endif /* MULTIPLANE */
    rv = count;
    if (bbc_diag_mode) {
        TIME(&t2);
        BBC_LOG(MSG_DIAG, "BBCFWrite wrote %d bytes in %d ms (%.1f KB/s)\n",
                count, __bbcdiag_deltat(t1, t2), 
                __bbcdiag_getKBs(count, __bbcdiag_deltat(t1,t2)));
    }
error:
    BBC_LOG(MSG_DEBUG, "fwrite returns %d\n", rv);
    return rv;
}

int
__BBC_FDelete(bbc_hand *hp, const char *name)
{
    unsigned char fname[BB_INODE16_NAMELEN];
    s32 rv;
    BbFat16* fat = hp->bh_fat;
    int i;
    BBC_LOG(MSG_DEBUG, "fdelete %s\n", name);
    __osBbFsFormatName(fname, name);
    if (!fname[0]) {
        BBC_LOG(MSG_ERR, "__BBC_FDelete: Cannot format name %s\n", name);
        return BBC_ERROR;
    }
    rv = BBC_NOFILE;
    for(i = 0; i < BB_INODE16_ENTRIES; i++) {
	if (fat->inode[i].type &&
	    memcmp(fname, fat->inode[i].name, BB_INODE16_NAMELEN) == 0) {
	    u16 b;
	    /* free all of the blocks */
	    for(b = fat->inode[i].block; b != BB_FAT_LAST; ) {
		u16 o = BB_FAT16_NEXT(fat,b);
		BB_FAT16_NEXT(fat,b) = BB_FAT_AVAIL;
		b = o;
	    }
	    memset(fat->inode+i, 0, sizeof(BbInode));
	    rv = __osBbFsSync(hp);
	    break;
	}
    }
    BBC_LOG(MSG_DEBUG, "fdelete returns %ld\n", rv);
    return rv;
}

/*
 * Initial write of FAT, filling all the potential FAT blocks
 * with identical copies.
 */
static int
__bbc_write_fat(bbc_hand *hp)
{
    int rv, j, k;
    int lk, link;
    flashif_t *fif = hp->bh_flashif;
    int blocks = hp->bh_cardsize;
    BbFat16 *fat;
    u8 spare[BB_FL_SPARE_SIZE] DCACHE_ALIGN;

    fat = hp->bh_fat;
    for (k = 0; k < blocks/BB_FAT16_ENTRIES; k++) {
        memcpy(fat[k].magic, k ? BB_FAT16_LINK_MAGIC : BB_FAT16_MAGIC, sizeof fat[k].magic);
        fat[k].seq = 1;
    }

    /*
     * Make a separate copy to use for the endianness conversion
     */
    if ((fat = malloc(BB_FL_MAX_FATS*sizeof(BbFat16))) == NULL) {
	BBC_LOG_SYSERROR("__bbc_write_fat: malloc failed");
	return BBC_NOMEM;
    }
#if BBC_MARK_BAD_FATS
retry:
#endif
    link = 0;
    memcpy(fat, hp->bh_fat, BB_FL_MAX_FATS*sizeof(BbFat16));
    memset(spare, 0xff, sizeof(spare));

    /*
     * Set links for the multi-block case
     */
    lk = blocks - 1;
    for (k = blocks/BB_FAT16_ENTRIES; --k >= 0; ) {
        fat[k].link = link;
	while (BB_FAT16_NEXT(fat,lk) == BB_FAT_BAD) lk--;
	link = lk;
    }

    /* Fix endianness */
    swab_fat(hp, fat);

    /*
     * write multiple copies of the FAT working backwards.  no more
     * than BB_FAT16_BLOCKS will be used, even if some bad blocks
     * are encountered.
     */
    k = (blocks/BB_FAT16_ENTRIES-1);
    for (j = 0; j < BB_FAT16_BLOCKS; j++) {
        if (BB_FAT16_NEXT(fat,blocks-1-j) != htons(BB_FAT_BAD)) {
            rv = (*fif->write_blocks)(fif->f, blocks-1-j, 1, fat+k, spare);
	    if (rv < 0) {
#if BBC_MARK_BAD_FATS
                if (rv == BBC_DATAERR) {
                    /* mark block bad in FAT and restart */
                    BB_FAT16_NEXT(hp->bh_fat,blocks-1-j) = BB_FAT_BAD;
                    goto retry;
                }
                else {
                    /* Some other horrible error: abort */
                    goto err;
                }
#else
		goto err;
#endif
	    }
            if (--k < 0)
                k = (blocks/BB_FAT16_ENTRIES-1);
        }
    }

err:
    /*
     * Set the initial rotor value so that the top block does not get
     * overwritten right away.  In the > 64MB case, that block is the
     * link target of the first block in all the other FAT block sets.
     */
    hp->bh_fat_rotor = 1;
    free(fat);

    /* make sure BB has the same version of the FAT */
    rv = __bbc_sync_fat(hp);
    return rv;
}