rcp.c 79.8 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
#include "sim.h"

#include <stdio.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/file.h>
#include <sys/signal.h>
#ifndef __alpha
#ifndef i386
#include <sys/unistd.h>
#include <sys/ioccom.h>
#include <sys/filio.h>
#include <netinet/in.h>
#endif
#endif
#include <sys/time.h>
#include <sys/uio.h>
#include <unistd.h>
#include <string.h>

#ifdef sgi
#include <netinet/if_ether.h>
#endif

#include <errno.h>
#include <netdb.h>
#include <stdlib.h>

#include "PR/rcp.h"
#include "PR/rdb.h"
#define BBPLAYER
#ifdef BBPLAYER
#include <ctype.h>
#include "PR/bcp.h"
#include "PR/bbnvram.h"
#include "ecc256.h"
#include "aes_api.h"
#include "PR/bbdebug.h"
#endif

#include "machine_defs.h"

#include "syslimits.h"
#include "simtypes.h"
#include "checkpoint.h"
#include "machine_params.h"
#include "cpu_interface.h"
#include "cpu_state.h"
#include "sim_error.h"
#include "addr_layout.h"
#include "registry.h"
#include "dma.h"
#include "../../devices/disk/simos_interface.h"
#include "remote_access.h"
#include "simutil.h"
#include "../../memsystems/flashlite/flash_interface.h"
#include "../../memsystems/memsys.h"

#include "simmisc.h"
#include "simmagic.h"
#include "hd.h"
#include "console.h"
#include "ethernet.h"
#include "startup.h"

char n64_cartridge_file[256] = "/dev/null";
static void mi_intr(int intr, int set);
static void mi_intr_check(void);
#ifdef BBPLAYER
#include "nand.h"
static void mi_module_change(int status);
static void mi_button_change(int status);
static void mi_eintr(int intr, int set);
static void virage_init(void);
static int isbb = 1;
#endif
static void sram_map(void);
void rcp_init(void);

#define REG(x)	{ x##_REG, #x }
struct regs {
    int addr;
    char* name;
};


static char* __types[] = { "read ", "write" };
static void
print_reg(struct regs* regs, int addr, int type, int v) {
    char* name = "??";
    char addrstr[32];
    int i;
    for(i = 0; regs[i].addr; i++) {
    	if (addr == regs[i].addr) {
	    name = regs[i].name;
	    break;
	}
    }
    if (!strcmp(name, "??")) {
	snprintf(addrstr, 32, "%x", addr);
	name = addrstr;
    }
    fprintf(stderr, "%-14s %s %x\r\n", name, __types[type&1], BE2HO_4(v));
}

/*
 * SP
 */

struct regs sp_regs[] = {
    REG(SP_MEM_ADDR),
    REG(SP_DRAM_ADDR),
    REG(SP_RD_LEN),
    REG(SP_WR_LEN),
    REG(SP_STATUS),
    REG(SP_DMA_FULL),
    REG(SP_DMA_BUSY),
    REG(SP_SEMAPHORE),
    REG(SP_PC),
    {0, 0}
};

struct sp_state {
    int mem_addr;
    int dram_addr;
    int rd_len;
    int wr_len;
    int status;
    int dma_full;
    int dma_busy;
    int semaphore;
    int pc;
    unsigned char mem[2*4096];
    int debug;
} sp_state;

static void
sp_init(void) {
}

static void
sp_dma(int read) {
    char* dir[] = { "write", "read" };
    int len = BE2HO_4(read ? sp_state.rd_len : sp_state.wr_len);
    int paddr = BE2HO_4(sp_state.mem_addr);
    int raddr =  BE2HO_4(sp_state.dram_addr);
    fprintf(stderr, "sp dma %s %d bytes from 0x%x to 0x%x\r\n", dir[read],
	    len, paddr, raddr);
    if (read) {
    	memcpy(sp_state.mem+(paddr&0x1fff), K0_TO_MEMADDR(0, raddr), len);
    } else {
	memcpy(K0_TO_MEMADDR(0, raddr), sp_state.mem+(paddr&0x1fff), len);
    }
}

static int
sp(int addr, int type, void* buf) {
    int *p = &sp_state.mem_addr;
    int dma_read = 0, dma_write = 0;
    switch(addr) {
    case SP_MEM_ADDR_REG:
        p += 0;
    	break;
    case SP_DRAM_ADDR_REG:
        p += 1;
    	break;
    case SP_RD_LEN_REG:
	dma_read = 1;
        p += 2;
    	break;
    case SP_WR_LEN_REG:
	dma_write = 1;
    	p += 3;
	break;
    case SP_STATUS_REG:
    	p += 4;
	if (!BDOOR_IS_LOAD(type)) {
	    int t, v = BE2HO_4(*(int*)buf);
	    int set = 0, clr = 0;
    print_reg(sp_regs, addr, type, *(int*)buf);
	    if (v&SP_CLR_HALT) clr |= SP_STATUS_HALT;
	    if (v&SP_SET_HALT) set |= SP_STATUS_HALT;
	    if (v&SP_CLR_BROKE) clr |= SP_STATUS_BROKE;
	    if (v&SP_CLR_INTR) ;
	    if (v&SP_SET_INTR) ;
	    if (v&SP_CLR_INTR_BREAK) clr |= SP_STATUS_INTR_BREAK;
	    if (v&SP_SET_INTR_BREAK) set |= SP_STATUS_INTR_BREAK;
	    if (v&SP_CLR_SIG0) clr |= SP_STATUS_SIG0;
	    if (v&SP_SET_SIG0) set |= SP_STATUS_SIG0;
	    if (v&SP_CLR_SIG1) clr |= SP_STATUS_SIG1;
	    if (v&SP_SET_SIG1) set |= SP_STATUS_SIG1;
	    if (v&SP_CLR_SIG2) clr |= SP_STATUS_SIG2;
	    if (v&SP_SET_SIG2) set |= SP_STATUS_SIG2;
	    if (v&SP_CLR_SIG3) clr |= SP_STATUS_SIG3;
	    if (v&SP_SET_SIG3) set |= SP_STATUS_SIG3;
	    if (v&SP_CLR_SIG4) clr |= SP_STATUS_SIG4;
	    if (v&SP_SET_SIG4) set |= SP_STATUS_SIG4;
	    if (v&SP_CLR_SIG5) clr |= SP_STATUS_SIG5;
	    if (v&SP_SET_SIG5) set |= SP_STATUS_SIG5;
	    if (v&SP_CLR_SIG6) clr |= SP_STATUS_SIG6;
	    if (v&SP_SET_SIG6) set |= SP_STATUS_SIG6;
	    if (v&SP_CLR_SIG7) clr |= SP_STATUS_SIG7;
	    if (v&SP_SET_SIG7) set |= SP_STATUS_SIG7;
	    t = *p;
	    t &= HO2BE_4(~clr);
	    t |= HO2BE_4(set);
	    if (set & SP_STATUS_INTR_BREAK)
	    	t |= HO2BE_4(SP_STATUS_HALT);
	    buf = &t;
	}
	break;
    case SP_DMA_FULL_REG:
    	p += 5;
	break;
    case SP_DMA_BUSY_REG:
    	p += 6;
	break;
    case SP_SEMAPHORE_REG:
    	p += 7;
	break;
    case SP_PC_REG:
    	p += 8;
	break;
    default:
        fprintf(stderr, "undefined SP access 0x%x type 0x%x\r\n", addr, type);
	exit(0);
    }
    if (BDOOR_IS_LOAD(type))
    	*(int*)buf = *p;
    else
    	*p = *(int*)buf;
//out:
    if (sp_state.debug) print_reg(sp_regs, addr, type, *p);
    if (dma_read || dma_write)
    	sp_dma(dma_read);
    return 0;
}

/*
 * SI
 */

struct regs si_regs[] = {
    REG(SI_DRAM_ADDR),
    REG(SI_PIF_ADDR_RD64B),
    REG(SI_PIF_ADDR_WR64B),
    REG(SI_STATUS),
#ifdef BBPLAYER
    REG(SI_CONFIG),
    REG(SI_CTRL),
#endif
    {0, 0}
};

struct si_state {
    int dram_addr;
    int pif_addr_rd64b;
    int pif_addr_wr64b;
    int status;
#ifdef BBPLAYER
    int config;
    int ctrl;
#endif
    int buf[16];
    int debug;
} si_state;

struct si_req {
    unsigned char pad0, txsize, rxsize, cmd, typeh, typel, status, pad1;
};

static void
si_init(void) {
}

static int
si_emulate_request(unsigned char* buf, int pifstatus, int ch) {
    int next, len = 0;
    if (!(pifstatus & 1)) {
	fprintf(stderr, "pifstatus format bit not set\r\n");
    }
    if (buf[0] == 0) { /* skip */
	if (si_state.debug) fprintf(stderr, "ch %d skip\r\n", ch);
	return 1;
    } else if (buf[0] == 0xfd) {	/* channel reset */
	if (si_state.debug) fprintf(stderr, "ch %d reset\r\n", ch);
	return 1;
    } else if (buf[0] == 0xfe) { /* format end */
	if (si_state.debug) fprintf(stderr, "ch %d format end\r\n", ch);
	return 0;
    }
    while (buf[len+0] == 0xff) { /* dummy */
	len++;
    }
    if (si_state.debug) fprintf(stderr, "ch %d tx %x rx %d cmd %x\r\n", ch, buf[len+0], buf[len+1], buf[len+2]);
    next = buf[len+0] + buf[len+1] + 2; /* rxsize + txsize */
    switch(buf[len+2]) {
    case 0:	/* request */
	buf[len+0] = buf[len+1] = 1;  /* txsize, rx size */
	if (ch == 0) { /* controller 0 */
	    buf[len+3] = 1; /* typel */
	    buf[len+4] = 0; /* typeh */
	} else if (ch < 4 || ch == 5) { /* controller 1, 2, 3 -- ignore */
	    buf[len+3] = 0; /* typel */
	    buf[len+4] = 0; /* typeh */
	} else if (ch == 4) { /* eeprom - ignore */
	    buf[len+3] = 0; /* typel */
	    buf[len+4] = 0; /* typeh */
	}
	buf[len+5] = 0;	/* status */
	break;
    case 1: /* read */
	break;
    case 2: /* ram_read */
	break;
    case 3: /* ram_write */
	break;
    case 4: /* eeprom_read */
	break;
    case 5: /* eeprom_write */
	break;
    case 254: /* set ch */
	break;
    case 255: /* reset */
	break;
    default:
	fprintf(stderr, "unknown si controller cmd 0x%x\r\n", buf[2]);
	break;
    }
    len += next;
    while(buf[len] == 0xff) len++;
    return len;
}

static void
si_dma(int read) {
    char* dir[] = { "write", "read" };
    int len = 64;
    int paddr = BE2HO_4(read ? si_state.pif_addr_rd64b : si_state.pif_addr_wr64b);
    int raddr =  BE2HO_4(si_state.dram_addr);
    if (si_state.debug)
	fprintf(stderr, "si dma %s %d bytes from 0x%x to 0x%x\r\n", dir[read],
	    len, paddr, raddr);
    if (!read) {
    	memcpy(si_state.buf, PHYS_TO_MEMADDR(0, raddr), sizeof si_state.buf);
    } else {
	int i, p = 0;
	for(i = 0; i < 6; i++) {
	    int rv = si_emulate_request((unsigned char*)si_state.buf+p, BE2HO_4(si_state.buf[15]), i);
	    if (!rv) break;
	    p += rv;
	}
	memcpy(PHYS_TO_MEMADDR(0, raddr), si_state.buf, sizeof si_state.buf);
    }
    si_state.status |= HO2BE_4(SI_STATUS_INTERRUPT);
    mi_intr(MI_INTR_SI, 1);
}

static int
si(int addr, int type, void* buf) {
    int *p = &si_state.dram_addr;
    int dma_read = 0, dma_write = 0;
    switch(addr) {
    case SI_DRAM_ADDR_REG:
        p += 0;
    	break;
    case SI_PIF_ADDR_RD64B_REG:
	dma_read = 1;
        p += 1;
    	break;
    case SI_PIF_ADDR_WR64B_REG:
	dma_write = 1;
        p += 2;
    	break;
    case SI_STATUS_REG:
    	p += 3;
	if (!BDOOR_IS_LOAD(type)) {
	    *p &= ~HO2BE_4(SI_STATUS_INTERRUPT);
	    mi_intr(MI_INTR_SI, 0);
	    goto out;
	}
    	break;
#ifdef BBPLAYER
    case SI_CONFIG_REG:
    	p += 4; break;
    case SI_CTRL_REG:
    	p += 5; break;
#endif
    default:
        fprintf(stderr, "undefined SI access 0x%x type 0x%x\r\n", addr, type);
	exit(0);
    }
    if (BDOOR_IS_LOAD(type))
    	*(int*)buf = *p;
    else
    	*p = *(int*)buf;
out:
    if (si_state.debug) print_reg(si_regs, addr, type, *p);
    if (dma_read || dma_write)
    	si_dma(dma_read);
    return 0;
}

/*
 * MI
 */

struct regs mi_regs[] = {
    REG(MI_INIT_MODE),
    REG(MI_VERSION),
    REG(MI_INTR),
    REG(MI_INTR_MASK),
#ifdef BBPLAYER
    REG(MI_CTRL),
    REG(MI_SEC_MODE),
    REG(MI_SEC_TIMER),
    REG(MI_SEC_VTIMER),
    REG(MI_ERROR_ADDR),
    REG(MI_ERROR_DATA),
    REG(MI_ERROR_INFO),
    REG(MI_RANDOM),
    REG(MI_EINTR),
    REG(MI_INTR_EMASK),
    REG(MI_AVCTRL),
#endif
    { 0, 0 }
};

struct mi_state {
    int init_mode;
    int version;
    int intr;
    int intr_mask;
#ifdef BBPLAYER
    int ctrl;
    int sec_mode;
#define IS_SECURE()	(mi_state.sec_mode & HO2BE_4(MI_SEC_MODE_SECURE))
    int sec_timer;
    int sec_vtimer;
    int error_addr;
    int error_data;
    int error_info;
    int random;
    int eintr;
    int eintr_mask;
    int avctrl;
    int timer_count;
#endif
    int debug;
} mi_state;

static void
mi_init(void) {
    mi_state.version = 0xdeadbeef;
#ifdef BBPLAYER
    mi_state.ctrl = 0;
    mi_state.sec_mode = HO2BE_4(MI_SEC_MODE_BROM_LO|MI_SEC_MODE_SECURE);
    mi_state.sec_timer = 0;
    mi_state.sec_vtimer = 0x62;
    mi_state.error_addr = mi_state.error_info = mi_state.error_data = 0;
    mi_state.random = 0;
    mi_state.eintr = mi_state.eintr_mask = 0;
#endif
}

#ifdef BBPLAYER
static void
mi_secure_mode(int cause) {
    extern int MipsyNmi(void);
if (mi_state.sec_mode & HO2BE_4(MI_SEC_MODE_SECURE)) return;
    if (mi_state.sec_mode & HO2BE_4(cause)) {
    	fprintf(stderr, "rcp: blocked secure trap 0x%x\r\n", cause);
	return;
    }
printf("enter secure %x\r\n", cause);
    mi_state.sec_mode |= HO2BE_4(cause|MI_SEC_MODE_SECURE);
    MipsyNmi();
}

static void
mi_poll(void) {
    int timer = BE2HO_4(mi_state.sec_timer);
    if (timer>>MI_SEC_TIMER_PRESCALE_SHIFT) {
printf("timer %x\r\n", timer);
	if (mi_state.timer_count == 0) {
	    mi_state.timer_count = timer&MI_SEC_TIMER_START_MASK;
	    mi_secure_mode(MI_SEC_MODE_TIMER);
	}
	mi_state.timer_count--;
    }
}
#endif

static void
mi_intr(int intr, int set) {
#if 0
    fprintf(stderr, "mi intr 0x%x\r\n", intr);
#endif
    intr = HO2BE_4(intr);
    if (set)
    	mi_state.intr |= intr;
    else
    	mi_state.intr &= ~intr;

    mi_intr_check();
}

static void
mi_eintr(int intr, int set) {
	extern void ChangeInterrupt(int cpu, int code, int v);
#if 0
	if (mi_state.debug)
		fprintf(stderr, "mi eintr 0x%x %s\r\n", intr, (set?"set":"clear"));
#endif
	intr = HO2BE_4(intr);
	if (set)
		mi_state.eintr |= intr;
	else
		mi_state.eintr &= ~intr;

	mi_intr_check();
}

/*
 * Decide whether the MI interrupts to the CPU should be asserted or not
 */
static void
mi_intr_check() {
	extern void ChangeInterrupt(int cpu, int code, int v);
	int intr;

	/*
	 * Normal MI interrupts come in at IP3
	 */
        intr = BE2HO_4(mi_state.intr & mi_state.intr_mask) & 0x3f;
	ChangeInterrupt(0, CAUSE_IP3 >> CAUSE_IPSHIFT, (intr != 0));

	/*
	 * Extended MI interrupts come in at IP4 or IP5 (BUTTON CHG only)
	 */
	intr = BE2HO_4(mi_state.eintr & mi_state.eintr_mask) & 0x3fc0;
	ChangeInterrupt(0, CAUSE_IP5 >> CAUSE_IPSHIFT, ((intr&MI_INTR_BUT) != 0));

	intr &= ~MI_INTR_BUT;
	ChangeInterrupt(0, CAUSE_IP4 >> CAUSE_IPSHIFT, (intr != 0));
}

#ifdef BBPLAYER
static void
mi_module_change(int status) {
printf("module change %d\r\n", status);
    if(status) {
	mi_state.eintr |= HO2BE_4(MI_EINTR_MD_STATUS);
    } else {
	mi_state.eintr &= ~HO2BE_4(MI_EINTR_MD_STATUS);
    }
    mi_eintr(MI_INTR_MD, 1);
    if (mi_state.sec_mode & HO2BE_4(MI_SEC_MODE_MD_TRAP_EN))
	mi_secure_mode(MI_SEC_MODE_MD_TRAP);
}

static void
mi_button_change(int status) {
printf("button change %d\r\n", status);
    if(status) {
	mi_state.eintr |= HO2BE_4(MI_EINTR_BUT_STATUS);
    } else {
	mi_state.eintr &= ~HO2BE_4(MI_EINTR_BUT_STATUS);
    }
    mi_eintr(MI_INTR_BUT, 1);
    if (mi_state.sec_mode & HO2BE_4(MI_SEC_MODE_BUT_TRAP_EN))
	mi_secure_mode(MI_SEC_MODE_BUT_TRAP);
}
#endif

static void
mi(int addr, int type, void* buf) {
    int *p = &mi_state.init_mode;
    int t = 0;
    switch(addr) {
    case MI_INIT_MODE_REG:
        p += 0; break;
    case MI_VERSION_REG:
        p += 1; break;
    case MI_INTR_REG:
	if (BDOOR_IS_LOAD(type))
	    p += 2;
	else
	    p = &t;
	break;
    case MI_INTR_MASK_REG: {
    	p += 3;
	if (!BDOOR_IS_LOAD(type)) {
	    int i, v = BE2HO_4(*(int*)buf);
	    int set = 0, clr = 0;
    if (mi_state.debug) print_reg(mi_regs, addr, type, *(int*)buf);
	    for(i = 0; i < 6; i++) {
		if (v & 1) clr |= 1 << i;
		v >>= 1;
		if (v & 1) set |= 1 << i;
		v >>= 1;
	    }
	    t = *p;
	    t &= HO2BE_4(~clr);
	    t |= HO2BE_4(set);
	    buf = &t;
	}
	break;
    }
#ifdef BBPLAYER
    case MI_CTRL_REG:
        p += 4;
	if (!BDOOR_IS_LOAD(type)) {
	    t = BE2HO_4(*(int*)buf);
	    if (t&(MI_CTRL_SOFT_RESET|MI_CTRL_HARD_RESET)) {
	        rcp_init();
	    	/* do reset */
		/*XXXblythe these should be in MipsyResetCPU()*/
		SBase[0].nPC = FPROM_BASE;
		SBase[0].CP0[C0_SR] &= ~(SR_TS|SR_TS);
		SBase[0].CP0[C0_SR] |= SR_BEV|SR_ERL;
		SBase[0].CP0[C0_TLBWIRED] = 0;
		SBase[0].CP0[C0_RAND] = 63;
		CPUVec.ResetCPU(0);
	    }
	}
	break;
    case MI_SEC_MODE_REG:
	if (IS_SECURE()) {
	    p += 5;
	} else {
	    if (BDOOR_IS_LOAD(type)) {
	    	/* enter secure mode */
		mi_secure_mode(MI_SEC_MODE_APP);
	    } else {
	        p = &t;
	    }
	}
	break;
    case MI_SEC_TIMER_REG: {
	if (IS_SECURE()) {
	    p += 6;
	    if (BDOOR_IS_LOAD(type)) {
		int timer = BE2HO_4(mi_state.sec_timer);
		t = HO2BE_4((timer&MI_SEC_TIMER_START_MASK)|((mi_state.timer_count<<MI_SEC_TIMER_PRESCALE_SHIFT)&MI_SEC_TIMER_PRESCALE_MASK));
		p = &t;
	    } else {
		mi_state.timer_count = BE2HO_4(*(int*)buf)&MI_SEC_TIMER_START_MASK;
	    }
	} else
	    p = &t;
	break;
    }
    case MI_SEC_VTIMER_REG:
	if (IS_SECURE()) {
	    p += 7;
	} else
	    p = &t;
        break;
    case MI_ERROR_ADDR_REG:
        p += 8; break;
    case MI_ERROR_INFO_REG:
        p += 9; break;
    case MI_ERROR_DATA_REG:
        p += 10; break;
    case MI_RANDOM_REG:
      p += 11;
      if(BDOOR_IS_LOAD(type)) {
	t = rand();
	p = &t;
      }
      break;
    case MI_EINTR_REG:
	p += 12;
        if (BDOOR_IS_STORE(type)) {
	    t = *p;
	    if (*(int*)buf & HO2BE_4(MI_INTR_MD)) {
		t &= ~ HO2BE_4(MI_INTR_MD);
	        mi_eintr(MI_INTR_MD, 0);
	    }
	    p = &t;
	}
	break;
    case MI_INTR_EMASK_REG:
        p += 13;
	if (!BDOOR_IS_LOAD(type)) {
	    int i, v = BE2HO_4(*(int*)buf);
	    int set = 0, clr = 0;
#if 0
    print_reg(mi_regs, addr, type, *(int*)buf);
#endif
	    for(i = 0; i < 14; i++) {
		if (v & 1) clr |= 1 << i;
		v >>= 1;
		if (v & 1) set |= 1 << i;
		v >>= 1;
	    }
	    t = *p;
	    t &= HO2BE_4(~clr);
	    t |= HO2BE_4(set);
	    t |= mi_state.intr_mask&(HO2BE_4(0x3f));
	    buf = &t;
	}
	break;
    case MI_AVCTRL_REG:
	p += 14; break;
#endif
    default:
        fprintf(stderr, "undefined MI access 0x%x type 0x%x\r\n", addr, type);
	exit(0);
    }
    if (BDOOR_IS_LOAD(type))
    	*(int*)buf = *p;
    else {
    	*p = *(int*)buf;
	/*
	 * After a store, check to see if MI should still be interrupting
	 */
	mi_intr_check();
    }
    if (mi_state.debug) print_reg(mi_regs, addr, type, *p);
}

/*
 * PI
 */

#define PI_IS_IDE(a)	\
    (((a) >= PI_IDE0_BASE_REG && (a) < PI_IDE0_BASE_REG+0x20000) || \
    ((a) >= PI_IDE1_BASE_REG && (a) < PI_IDE1_BASE_REG+0x20000) || \
    ((a) >= PI_IDE2_BASE_REG && (a) < PI_IDE2_BASE_REG+0x20000) || \
    ((a) >= PI_IDE3_BASE_REG && (a) < PI_IDE3_BASE_REG+0x20000)) 

#define PI_IS_BUF_DATA_LOAD(a,t) \
    ((a) >= PI_BUFFER_BASE_REG && (a) < PI_BUFFER_BASE_REG+1024) \
    && BDOOR_IS_LOAD((t))

struct regs pi_regs[] = {
    REG(PI_DRAM_ADDR),
    REG(PI_CART_ADDR),
    REG(PI_RD_LEN),
    REG(PI_WR_LEN),
    REG(PI_STATUS),
    REG(PI_BSD_DOM1_LAT),
    REG(PI_BSD_DOM1_PWD),
    REG(PI_BSD_DOM1_PGS),
    REG(PI_BSD_DOM1_RLS),
    REG(PI_BSD_DOM2_LAT),
    REG(PI_BSD_DOM2_PWD),
    REG(PI_BSD_DOM2_PGS),
    REG(PI_BSD_DOM2_RLS),
#ifdef BBPLAYER
    REG(PI_AES_CTRL),
    REG(PI_FLASH_CTRL),
    REG(PI_FLASH_CONFIG),
    REG(PI_FLASH_ADDR),
    REG(PI_ATBU),
    REG(PI_GPIO),
    REG(PI_ACCESS),
    REG(PI_DMA_BUFFER_RD),
    REG(PI_DMA_BUFFER_WR),
    REG(PI_ERROR),
    REG(PI_IDE_CONFIG),
    REG(PI_IDE_CTRL),
    REG(PI_IDE_FC_BASE),
#endif
    { 0, 0 }
};

struct pi_state {
    int dram_addr;
    int cart_addr;
    int rd_len;
    int wr_len;
    int status;
    struct {
	int lat;
	int pwd;
	int pgs;
	int rls;
    } bsd_dom[2];
#ifdef BBPLAYER
    int aes_ctrl;
#define aes_ekey buffer[132][0]
#define aes_init buffer[154][0]
#define buf0 buffer[0][0]
#define oob0 buffer[128][0]
#define buf1 buffer[64][0]
#define oob1 buffer[130][0]
#define atb0 buffer[160][0]
    int flash_ctrl;
    int flash_config;
    int flash_addr;
    int atbu;
    int dma_buffer_rd;
    int dma_buffer_wr;
    int gpio;
    int access;
    int error;
    int edata;
    struct {
	int config;
	int control;
    } ide;
    unsigned buffer[256][2];
    unsigned short atbhi[512];
    AesCipherInstance cipher;
    AesKeyInstance key;
    int flash_ctrl_read;
#endif
    int debug;
} pi_state;

static void
pi_init(void) {
#ifdef BBPLAYER
    pi_state.flash_config = 0x753e3eff;
    pi_state.gpio = HO2BE_4((PI_ID_SYS_CLOCK_96<<PI_ID_SYS_CLOCK_SHIFT)|
	                    (PI_ID_CLOCK_MULT_X1_5<<PI_ID_CLOCK_MULT_SHIFT)|
			    (PI_ID_VIDEO_MODE_NTSC1<<PI_ID_VIDEO_MODE_SHIFT)|
			    (PI_ID_MEM_SIZE_16<<PI_ID_MEM_SIZE_SHIFT));
    pi_state.ide.config = HO2BE_4((1<<31)|(8<<26)|(7<<21)|(2<<16)|(9<<10)|(8<<5)|1);
#endif
}

#ifdef BBPLAYER
static unsigned
pi_atb_lookup(unsigned caddr, int* perm) {
    unsigned low = 0, hi = PI_ATB_NUM_ENTRIES, mid = hi>>1;
    unsigned al;
    unsigned short ah;
    unsigned short vaddr = (caddr >> 14)&0xffff;
    int asize;
    while(1) {
	al = BE2HO_4(*((unsigned*)&pi_state.atb0 + mid));
        ah = BE2HO_2(pi_state.atbhi[(PI_ATB_BUFFER_OFFSET>>2)+mid]);
        asize = 1<<((ah>>PI_ATBU_SIZE_SHIFT)&PI_ATBU_SIZE_MASK);
	if (vaddr > ((al & 0xffff)+(asize-1))) {
	    low = mid;
	} else if (vaddr <  (al & 0xffff)) {
	    hi = mid;
	} else
	    break;
	mid = (low+hi)>>1;
    }

//printf("mid %d vaddr %x paddr %x hi %x %d\r\n", mid, al & 0xffff, al >> 16, ah, (PI_ATB_BUFFER_OFFSET>>2)+mid);
    if ((ah & *perm)  == 0) {
	printf("atb access error for address %x\r\n", caddr);
	return -1;
    } else {
	unsigned fladdr = (((al >> PI_ATBL_PADDR_SHIFT)+
                            (vaddr-(al&0xffff)))<<14) | (caddr&((1<<14)-1));
	unsigned dev = (ah & PI_ATBU_DEV_MASK)>>PI_ATBU_DEV_SHIFT;
	if (dev) {
	    printf("unsupported device for flash dma\r\n");
	}
	if ((ah & (PI_ATBU_IV|PI_ATBU_PERM_DMA|PI_ATBU_PERM_PIO))
		== (PI_ATBU_IV|PI_ATBU_PERM_DMA|PI_ATBU_PERM_PIO))
	    *perm = 1;
	else
	    *perm = 0;
	return fladdr;
    }
}

static void
pi_aes(unsigned int ctrl) {
    int siz = (ctrl & PI_AES_CTRL_SIZE_MASK)>>PI_AES_CTRL_SIZE_SHIFT;
    unsigned char* b = (unsigned char*)pi_state.buffer+((ctrl&PI_AES_CTRL_DATA_MASK)>>PI_AES_CTRL_DATA_SHIFT)*16;
    unsigned int* k = (unsigned int*)pi_state.buffer+(PI_AES_EKEY_REG-PI_BUFFER_BASE_REG)/4;
    int z;

    /* re-initialize key and cipher every time - sigh */
    /* initialize key */
    pi_state.key.direction = AES_DIR_DECRYPT;
    pi_state.key.Nr = 10;
    for(z = 0; z < 44; z++)
	pi_state.key.rk[z] = BE2HO_4(k[z]);
    /* initialize cipher */
    pi_state.cipher.mode = AES_MODE_CBC;

    if (!(ctrl & PI_AES_CTRL_HC)) {
	unsigned char* iv = (unsigned char*)pi_state.buffer+((ctrl&PI_AES_CTRL_IV_MASK)>>PI_AES_CTRL_IV_SHIFT)*16;
	for(z = 0; z < 16; z++)
	    pi_state.cipher.IV[z] = iv[z];
    }
    if (ctrl & PI_AES_CTRL_START) {
	unsigned char tmp[1024];
	aesBlockDecrypt(&pi_state.cipher, &pi_state.key, b, (siz+1)*16*8, tmp);
	memcpy(b, tmp, (siz+1)*16);

	if (ctrl & PI_AES_CTRL_INTR)
	    mi_eintr(MI_INTR_AES, 1);
    } else {
	if (!(ctrl & PI_AES_CTRL_INTR))
	    mi_eintr(MI_INTR_AES, 0);
	}
}

static int
pi_flash(unsigned int ctrl) {
    /* do flash controller stuff */
    int dev = (ctrl&PI_FLASH_CTRL_DEV_MASK) >> PI_FLASH_CTRL_DEV_SHIFT;
    int aph = (ctrl&PI_FLASH_CTRL_ADPH_MASK) >> PI_FLASH_CTRL_ADPH_SHIFT;
    int cmd = (ctrl&PI_FLASH_CTRL_CMD_MASK) >> PI_FLASH_CTRL_CMD_SHIFT;
    int siz = (ctrl&PI_FLASH_CTRL_SIZE_MASK) >> PI_FLASH_CTRL_SIZE_SHIFT;
    int bf =  (ctrl&PI_FLASH_CTRL_BUF1) >> PI_FLASH_CTRL_BUF_SHIFT;
    unsigned a;
    unsigned char nctl, data;
    unsigned char* x = (unsigned char*)pi_state.buffer+512*bf;
    int result = 0;

    if (pi_state.debug) print_reg(pi_regs, PI_FLASH_CTRL_REG, BDOOR_STORE_WORD, HO2BE_4(ctrl));
    if (dev != 0) {
	fprintf(stderr, "pi: write to unsupported flash device\r\n");
	exit(1);
    }
    a = BE2HO_4(pi_state.flash_addr);
    cmd |= (a&0x100)>>8;
    a = (a&0xff) | (a&0xfffffe00)>>1;

    /* command phase */
    nctl = NAND_CLE;
    nand_ctrl(1, &nctl);
    data = cmd;
    nand_io(1, &data);

    /* address phase */
    nctl = NAND_ALE;
    nand_ctrl(1, &nctl);
    while(aph) {
	if (aph&1) {
	    data = a;
	    nand_io(1, &data);
	}
	a >>= 8;
	aph >>= 1;
    }

    /* read phase */
    if (ctrl & PI_FLASH_CTRL_RDPH) {
	int i = 0;
	nctl = 0;
	nand_ctrl(1, &nctl);
	while(siz > 0) {
	    nand_io(0, &data);
	    *x++ = data;
	    siz--;
	    if (++i == 512) x = (unsigned char*)pi_state.buffer+1024+16*bf;
	}
	if ((ctrl & PI_FLASH_CTRL_ECC) && i == 528) {
	    /* compute and correct ECC */
	    unsigned char calc_ecc[3];
	    int rv0, rv1;
	    ecc256_calculate((unsigned char*)pi_state.buffer+bf*512, calc_ecc);
	    rv0 = ecc256_correct((unsigned char*)pi_state.buffer+bf*512,
		   (unsigned char*)pi_state.buffer+1024+16*bf+13, calc_ecc);
	    ecc256_calculate((unsigned char*)pi_state.buffer+bf*512+256, calc_ecc);
	    rv1 = ecc256_correct((unsigned char*)pi_state.buffer+bf*512+256,
		   (unsigned char*)pi_state.buffer+1024+16*bf+8, calc_ecc);
	    if (rv0 < 0 || rv1 < 0) /* uncorrectable */
		result |= PI_FLASH_CTRL_DBERR;
	    else if (rv0 || rv1) /* correctable */
		result |= PI_FLASH_CTRL_SBERR;
if (/*pi_state.debug &&*/ (rv0 || rv1)) printf("ecc read error block %d page %d %d %d\r\n", BE2HO_4(pi_state.flash_addr)>>14, (BE2HO_4(pi_state.flash_addr)&0x3fff)>>9, rv0, rv1);
	}
    }

    /* write phase */
    if (ctrl & PI_FLASH_CTRL_WDPH) {
	int i = 0, do_ecc = (ctrl & PI_FLASH_CTRL_ECC) && siz == 528;
	unsigned char ecc[6];
	if (do_ecc) {
	    ecc256_calculate((unsigned char*)pi_state.buffer+bf*512, ecc);
	    ecc256_calculate((unsigned char*)pi_state.buffer+bf*512+256, ecc+3);
	}
	nctl = 0;
	nand_ctrl(1, &nctl);
	while(siz > 0) {
	    if (525 <= i && i <= 527 && do_ecc) {
		data = ecc[i-525];
		x++;
	    } else if (520 <= i && i <= 522 && do_ecc) {
		data = ecc[i-520+3];
		x++;
	    } else
		data = *x++;
	    nand_io(1, &data);
	    siz--;
	    if (++i == 512) x = (unsigned char*)pi_state.buffer+1024+16*bf;
	}
    }
    return result | (ctrl&PI_FLASH_CTRL_INTR);
}

static int
pi_check_ecc(int rv, unsigned int addr, int dma) {
    if (rv & (PI_FLASH_CTRL_SBERR|PI_FLASH_CTRL_DBERR)) {
printf("ecc error\r\n");
	if (rv & PI_FLASH_CTRL_DBERR) {
	    pi_state.error &= ~HO2BE_4(PI_ERROR_ADDR_MASK);
	    pi_state.error |= HO2BE_4(addr & PI_ERROR_ADDR_MASK);
	    pi_state.error |= HO2BE_4(PI_ERROR_UNCORRECTABLE_ECC);
	    if (dma)
		pi_state.status |= HO2BE_4(PI_STATUS_DMA_BUSY);
	    else
		pi_state.status |= HO2BE_4(PI_STATUS_IO_BUSY);
	    if (pi_state.error & HO2BE_4(PI_ERROR_KERNEL_INTR))
		mi_secure_mode(MI_SEC_MODE_FATAL);
	    if (pi_state.error & HO2BE_4(PI_ERROR_SYS_INTR))
		mi_eintr(MI_INTR_PI_ERR, 1);
	} else if (!(pi_state.error&HO2BE_4(PI_ERROR_CORRECTABLE_ECC))) {
	    pi_state.error |= HO2BE_4(PI_ERROR_CORRECTABLE_ECC);
	    pi_state.error &= ~HO2BE_4(PI_ERROR_ADDR_MASK);
	    pi_state.error |= HO2BE_4(addr & PI_ERROR_ADDR_MASK);
	    return 0;
	}
    }
    return 0;
}
#endif

#if 0
#define PI_DOM1_ADDR1		0x06000000	/* to 0x07FFFFFF */
#define PI_DOM1_ADDR2		0x10000000	/* to 0x1FBFFFFF */
#define PI_DOM1_ADDR3		0x1FD00000	/* to 0x7FFFFFFF */
#define PI_DOM2_ADDR1		0x05000000	/* to 0x05FFFFFF */
#define PI_DOM2_ADDR2		0x08000000	/* to 0x0FFFFFFF */
#endif

static void
pi_dma(int read) {
    char* dir[] = { "write", "read" };
    FILE *fp;
    int len = BE2HO_4(read ? pi_state.rd_len : pi_state.wr_len)+1;
    int caddr = BE2HO_4(pi_state.cart_addr);
    int raddr =  BE2HO_4(pi_state.dram_addr);
    if (pi_state.debug)
	fprintf(stderr, "pi dma %s %d bytes from 0x%x to 0x%x\r\n", dir[read],
	    len, caddr, raddr);
#ifdef BBPLAYER
    if (isbb && read) {
	/* writes to cartridge space fail */
	if(pi_state.error&HO2BE_4(PI_ERROR_SYS_INTR)) {
	    pi_state.status |= HO2BE_4(PI_STATUS_DMA_BUSY);
	    pi_state.error |= HO2BE_4(PI_ERROR_WRITE_TRAP);
	    mi_eintr(MI_INTR_PI_ERR, 1);
	}
	return;
    }
    if (isbb) {
	int rv, perm = PI_ATBU_PERM_DMA;
	int buffer = 0;
	void *dst = PHYS_TO_MEMADDR(0, raddr), *src;
#define FL_BLOCK_SIZE	(1<<14)
#define FL_PAGE_SIZE	(1<<9)
	if ((caddr&(FL_PAGE_SIZE-1)) < 16) {
	    /* need cbc iv from previous page */
	    unsigned int prev = (caddr-16)&~15;
	    unsigned int flprev =  pi_atb_lookup(prev, &perm);
	    if ((caddr&~(FL_BLOCK_SIZE-1)) != (prev&~(FL_BLOCK_SIZE-1))) {
		/* need to look in previous block */
		if (perm) {
		    /* get iv from pi buffer rather than previous block */
		    memcpy(pi_state.cipher.IV, &pi_state.aes_init, 16);
		    prev = 0;
		}
	    }
	    if (prev) {
		/* flash transfer page to buffer 1 */
		/* read whole page to get ecc */
		unsigned int ctrl = BE2HO_4(pi_state.flash_ctrl);
		unsigned char* iv = (void*)pi_state.buffer+512+512-16;
		if (flprev == (unsigned)-1) {
		    caddr = prev;
atbmiss:
		    pi_state.error |= HO2BE_4(PI_ERROR_ATB_DMA);
		    pi_state.error &= ~PI_ERROR_ADDR_MASK;
		    pi_state.error |= caddr & PI_ERROR_ADDR_MASK;
		    if (pi_state.error & HO2BE_4(PI_ERROR_KERNEL_INTR))
			mi_secure_mode(MI_SEC_MODE_FATAL);
		    if (pi_state.error & HO2BE_4(PI_ERROR_SYS_INTR))
			mi_eintr(MI_INTR_PI_ERR, 1);
		    return;
		}
		ctrl = (ctrl & ~PI_FLASH_CTRL_SIZE_MASK) | 528;
		ctrl = (ctrl & ~PI_FLASH_CTRL_BUF1) | PI_FLASH_CTRL_BUF1;
		pi_state.flash_addr = HO2BE_4(flprev&~(FL_PAGE_SIZE-1));
		rv = pi_flash(ctrl);
		if (pi_check_ecc(rv, prev, 1) < 0)
		    return;
//		iv = (void*)pi_state.buffer+512+(prev&(FL_PAGE_SIZE-1));
		memcpy(pi_state.cipher.IV, iv, 16);
	    }
	}
	while(len) {
	    unsigned fladdr;
	    unsigned next, n;
	    unsigned int ctrl;
	    perm = PI_ATBU_PERM_DMA;
	    fladdr = pi_atb_lookup(caddr, &perm);
	    if (fladdr == (unsigned)-1) goto atbmiss;
	    next = (caddr+FL_PAGE_SIZE)&~(FL_PAGE_SIZE-1);
	    n = next - caddr;
	    if (n > len) n = len;
	    if (!n) break;

//printf("transfer %d bytes from %x %x\r\n", n, caddr, fladdr);
	    /* flash transfer */
	    ctrl = BE2HO_4(pi_state.flash_ctrl);
	    ctrl = (ctrl & ~PI_FLASH_CTRL_SIZE_MASK) | 528;
	    ctrl = (ctrl & ~PI_FLASH_CTRL_BUF1) | (buffer << PI_FLASH_CTRL_BUF_SHIFT);
	    pi_state.flash_addr = HO2BE_4(fladdr&~(FL_PAGE_SIZE-1));
	    rv = pi_flash(ctrl);
	    /* check for ecc errors */
	    if (pi_check_ecc(rv, caddr, 1) < 0) return;

	    /* aes */
	    ctrl = BE2HO_4(pi_state.aes_ctrl);
	    ctrl |=  PI_AES_CTRL_START |
		    ((512/16)-1) << PI_AES_CTRL_SIZE_SHIFT |
		    (buffer ? 32 : 0)  << PI_AES_CTRL_DATA_SHIFT |
		    PI_AES_CTRL_HC;
	    pi_aes(ctrl);

	    /* copy out */
	    src = (unsigned char *)pi_state.buffer+512*buffer;
	    src += caddr & (FL_PAGE_SIZE-1);
	    memcpy(dst, src, n);
	    dst += n;
	    len -= n;
	    caddr = next;
	    buffer ^= 1;
	}
	mi_intr(MI_INTR_PI, 1);
	return;
    }
#endif
    if (caddr >= PI_DOM1_ADDR3) {
	caddr -= PI_DOM1_ADDR3;
    } else if (caddr >= PI_DOM1_ADDR2) {
	caddr -= PI_DOM1_ADDR2;
    } else if (caddr >= PI_DOM1_ADDR1) {
	caddr -= PI_DOM1_ADDR1;
    }
    if (!read) {
	if ((fp = fopen(n64_cartridge_file, "r")) == 0) {
	    perror(n64_cartridge_file);
	    exit(1);
	}
	fseek(fp, caddr, SEEK_SET);
	fread(PHYS_TO_MEMADDR(0, raddr), len, 1, fp);
	fclose(fp);
    }
    mi_intr(MI_INTR_PI, 1);
}

static int
pi_pio(int doff, int type, void* buf) {
    static int init, cd1_size;
    static void* cd1_map;

    if (BDOOR_SIZE(type) != sizeof(int)) {
    	fprintf(stderr, "non-word cartridge domain 1 access @ %08x type 0x%x\r\n", doff, type);
    }
    /* check for dev system probing */
    /* kmc - partner N64 */
    if (doff == 0x1ff00000 &&  BDOOR_IS_LOAD(type)) {
	*(int*)buf = 0;
        return 0;
    }
#ifdef BBPLAYER
    if (isbb && BDOOR_IS_STORE(type)) {
	/* generate a trap */
	if (pi_state.error&HO2BE_4(PI_ERROR_KERNEL_INTR))
	    mi_secure_mode(MI_SEC_MODE_FATAL);
	else if(pi_state.error&HO2BE_4(PI_ERROR_SYS_INTR)) {
	    pi_state.error |= HO2BE_4(PI_ERROR_WRITE_TRAP);
	    pi_state.edata = *(int*)buf;
	    pi_state.cart_addr = HO2BE_4(doff);
	    mi_eintr(MI_INTR_PI_ERR, 1);
	}
	return 0;
    }
    if (isbb) {
	/* atb read */
	int rv, perm = PI_ATBU_PERM_PIO;
	unsigned int caddr = doff, fladdr, ctrl;
	if ((caddr&(FL_PAGE_SIZE-1)) < 16) {
	    /* need cbc iv from previous page */
	    unsigned int prev = (caddr-16)&~15;
	    unsigned int flprev =  pi_atb_lookup(prev, &perm);
	    if ((caddr&~(FL_BLOCK_SIZE-1)) != (prev&~(FL_BLOCK_SIZE-1))) {
		/* need to look in previous block */
		if (perm) {
		    /* get iv from pi buffer rather than previous block */
		    memcpy(pi_state.cipher.IV, &pi_state.aes_init, 16);
		    prev = 0;
		}
	    }
	    if (prev) {
		/* flash transfer page to buffer 1 */
		/* read whole page to get ecc */
		unsigned int ctrl = BE2HO_4(pi_state.flash_ctrl);
		unsigned char* iv = (void*)pi_state.buffer+512+512-16;
		if (flprev == (unsigned)-1) {
		    caddr = prev;
atbmiss:
		    pi_state.error |= HO2BE_4(PI_ERROR_ATB_PIO);
		    pi_state.error &= ~PI_ERROR_ADDR_MASK;
		    pi_state.error |= caddr & PI_ERROR_ADDR_MASK;
		    if (pi_state.error & HO2BE_4(PI_ERROR_KERNEL_INTR))
			mi_secure_mode(MI_SEC_MODE_FATAL);
		    if (pi_state.error & HO2BE_4(PI_ERROR_SYS_INTR))
			mi_eintr(MI_INTR_PI_ERR, 1);
		    return 1;
		}
		ctrl = (ctrl & ~PI_FLASH_CTRL_SIZE_MASK) | 528;
		ctrl = (ctrl & ~PI_FLASH_CTRL_BUF1) | PI_FLASH_CTRL_BUF1;
		pi_state.flash_addr = HO2BE_4(flprev&~(FL_PAGE_SIZE-1));
		rv = pi_flash(ctrl);
		if (pi_check_ecc(rv, prev, 1) < 0)
		    return 1;
//		iv = (void*)pi_state.buffer+512+(prev&(FL_PAGE_SIZE-1));
		memcpy(pi_state.cipher.IV, iv, 16);
	    }
	}
	perm = PI_ATBU_PERM_PIO;
	fladdr = pi_atb_lookup(caddr, &perm);
	if (fladdr == (unsigned)-1) goto atbmiss;
	/* flash transfer */
	ctrl = BE2HO_4(pi_state.flash_ctrl);
	ctrl = (ctrl & ~PI_FLASH_CTRL_SIZE_MASK) | 528;
	ctrl = (ctrl & ~PI_FLASH_CTRL_BUF1) | (0 << PI_FLASH_CTRL_BUF_SHIFT);
	pi_state.flash_addr = HO2BE_4(fladdr&~(FL_PAGE_SIZE-1));
	rv = pi_flash(ctrl);
	/* check for ecc errors */
	if (pi_check_ecc(rv, caddr, 0) < 0) return 1;

	/* aes */
	ctrl = BE2HO_4(pi_state.aes_ctrl);
	ctrl |=  PI_AES_CTRL_START |
		((512/16)-1) << PI_AES_CTRL_SIZE_SHIFT |
		(0 ? 32 : 0)  << PI_AES_CTRL_DATA_SHIFT |
		PI_AES_CTRL_HC;
	pi_aes(ctrl);

	/* copy out */
	*(int*)buf = *(int*)((unsigned char *)pi_state.buffer+ (caddr & (FL_PAGE_SIZE-1)));
	return 0;
    }
#endif

    if (doff >= 0x10000000) {
    	doff -= 0x10000000;
    } else if (doff >= 0x06000000) {
    	doff -= 0x06000000;
    }
    if (!init) {
	struct stat sb;
    	int fd = open(n64_cartridge_file, O_RDONLY);
	if (fd < 0) {
	    perror(n64_cartridge_file);
	    exit(1);
	}
	fstat(fd, &sb);
	cd1_size = (sb.st_size + getpagesize()-1) & ~(getpagesize()-1);
	cd1_map = mmap(NULL, cd1_size, PROT_READ, MAP_SHARED, fd, 0);
	if ((int)cd1_map == -1) {
	    perror("mmap");
	    exit(1);
	}
	init = 1;
    }
    if (BDOOR_IS_LOAD(type)) {
	if (doff < cd1_size) {
	    *(int*)buf = *(int*)(cd1_map + doff);
	} else {
	    fprintf(stderr, "cartridge domain 1 read out of range @ %08x type 0x%x\r\n", doff, type);
	    *(int*)buf = 0;
	}
    } else {
    	fprintf(stderr, "write to cartridge domain 1 @ %08x type 0x%x\r\n", doff, type);
    }
    return 0;
}

#ifdef BBPLAYER
static void
pi_ide(int addr, int type, void* buf) {
    static char strbuf[256];
    static int bufp;

    if (pi_state.ide.config&HO2BE_4(PI_IDE_CONFIG_RESET)) {
	fprintf(stderr, "PI ide access while in reset\r\n");
	return;
    }

    if ((addr >= IDE_RDB_BASE_REG && addr < IDE_RDB_BASE_REG+0x800) ||
	    addr == IDE_RDB_CTRL_REG) {
	/* handle dbp access */
	static unsigned short ctrl, data[1024];
	if (BDOOR_SIZE(type) != 2)
	    fprintf(stderr, "PI ide non-halfword dbp access %x\r\n", (int)SBase[0].PC);
	if (addr == IDE_RDB_CTRL_REG) {
	    if (BDOOR_IS_LOAD(type)) {
		*(unsigned short*)buf = ctrl;
	    } else {
		int c = BE2HO_2(*(unsigned short*)buf);
		if (c == IDE_RDB_CTRL_RESET)
		    ctrl = 0;
		else {
		    if (c&IDE_RDB_CTRL_CLR_HOST_REQ)
			ctrl &= HO2BE_2(~IDE_RDB_STATUS_HOST_REQ);
		    if (c&IDE_RDB_CTRL_CLR_HOST_ACK)
			ctrl &= HO2BE_2(~IDE_RDB_STATUS_HOST_ACK);
		    if ((ctrl & HO2BE_2(IDE_RDB_STATUS_HOST_ACK|IDE_RDB_STATUS_HOST_REQ)) == 0)
			mi_eintr(MI_INTR_IDE, 0);

		    if (c&IDE_RDB_CTRL_SET_BB_REQ) {
			/*ctrl |= HO2BE_2(IDE_RDB_STATUS_BB_REQ);*/
			/* decode request */
			void rdb_decode(int d);
			rdb_decode(*(unsigned*)(data+0x200));
			/* ack request immediately */
			ctrl |= HO2BE_2(IDE_RDB_STATUS_HOST_ACK);
		    }
		    if (c&IDE_RDB_CTRL_SET_BB_ACK)
			ctrl |= HO2BE_2(IDE_RDB_STATUS_BB_ACK);
		}
	    }
	} else {
	    int p = addr-IDE_RDB_BASE_REG;
	    if (BDOOR_IS_LOAD(type))
		*(unsigned short*)buf = data[p>>1];
	    else
		data[p>>1] = *(unsigned short*)buf;
	}

    } else if (BDOOR_IS_STORE(type)) {
	if (addr == 0x046fffe0) {	/* backdoor print */
	    int c = BE2HO_2(*(unsigned short*)buf);
	    if (c == '\n') {
		fprintf(stderr, "ide print: %s\r\n", strbuf);
		memset(strbuf, 0, sizeof strbuf);
		bufp = 0;
	    } else
		strbuf[bufp++] = c;
	} else if (addr == 0x046fffe4) { /* backdoor module */
	    int c = BE2HO_2(*(unsigned short*)buf);
	    mi_module_change(c);
	} else if (addr == 0x046ffffa) { /* backdoor exit */
	    int c = BE2HO_2(*(unsigned short*)buf);
	    if (c) {
		printf("ide exit\r\n");
		nand_final();
		exit(0);
	    }
	} else if (addr == 0x046ffffc) { /* backdoor power */
	    int c = BE2HO_2(*(unsigned short*)buf);
	    mi_button_change(c);
	} else {
	    fprintf(stderr, "unknown ide store @ 0x%x 0x%x\r\n", addr, BE2HO_4(*(unsigned int*)buf));
	}
    } else {
	    fprintf(stderr, "unknown ide load @ 0x%x\r\n", addr);
    }
}
#endif

static void
pi(int addr, int type, void* buf) {
    int *p = &pi_state.dram_addr, tmp, printreg = 1;
    int dma_read = 0, dma_write = 0, t;
#ifdef BBPLAYER
    if (addr >= PI_ATB_BUFFER_HI_REG && addr < PI_ATB_BUFFER_HI_REG+256*4) {
	int x = (addr-PI_ATB_BUFFER_HI_REG)>>2;
	tmp = HO2BE_4((BE2HO_2(pi_state.atbhi[x]) << 16) | BE2HO_2(pi_state.atbhi[x+1]));
	p = &tmp;
        goto rw;
    } else if (addr >= PI_BUFFER_BASE_REG && addr < PI_BUFFER_BASE_REG+256*8) {
	p = (int*)((addr-PI_BUFFER_BASE_REG) + (char*)pi_state.buffer);
	if (addr >= PI_ATB_BUFFER_LO_REG && !BDOOR_IS_LOAD(type)) {
	    pi_state.atbhi[(addr-PI_BUFFER_BASE_REG)>>2] = HO2BE_2((unsigned short)BE2HO_4(pi_state.atbu));
	}
        goto rw;
    } else if (PI_IS_IDE(addr)) {
	pi_ide(addr, type, buf); return;
    }
#endif
    switch(addr) {
    case PI_DRAM_ADDR_REG:
        p += 0; break;
    case PI_CART_ADDR_REG:
        p += 1; break;
    case PI_RD_LEN_REG:
	dma_read = 1;
        p += 2; break;
    case PI_WR_LEN_REG: 
	dma_write = 1;
    	p += 3; break;
    case PI_STATUS_REG:
    	p += 4;
	if (!BDOOR_IS_LOAD(type)) {
	    t = BE2HO_4(*(int*)buf);
	    if (t & PI_STATUS_CLR_INTR) {
	    	mi_intr(MI_INTR_PI, 0);
	    }
	    if (t & PI_STATUS_RESET) {
	    	fprintf(stderr, "PI_STATUS_RESET not implemented\r\n");
	    }
	    if (t & PI_STATUS_DMA_BUSY)
		*p &= ~HO2BE_4(PI_STATUS_DMA_BUSY);
	    if (t & PI_STATUS_IO_BUSY)
		*p &= ~HO2BE_4(PI_STATUS_IO_BUSY);
	    goto out;
	}
	break;
    case PI_BSD_DOM1_LAT_REG:
    	p += 5; break;
    case PI_BSD_DOM1_PWD_REG:
    	p += 6; break;
    case PI_BSD_DOM1_PGS_REG:
    	p += 7; break;
    case PI_BSD_DOM1_RLS_REG:
    	p += 8; break;
    case PI_BSD_DOM2_LAT_REG:
    	p += 9; break;
    case PI_BSD_DOM2_PWD_REG:
    	p += 10; break;
    case PI_BSD_DOM2_PGS_REG:
    	p += 11; break;
    case PI_BSD_DOM2_RLS_REG:
    	p += 12; break;
#ifdef BBPLAYER
#define NO_ACCESS(x) (!IS_SECURE() && !(pi_state.access & HO2BE_4(x)))
    case PI_AES_CTRL_REG:
	if (NO_ACCESS(PI_ACCESS_AES)) goto noaccess;
	p += 13;
	if (BDOOR_IS_STORE(type)) {
	    pi_aes(BE2HO_4(*(int*)buf));
	    *p = 0;
	    goto out;
	}
	break;
    case PI_FLASH_CTRL_REG:
	if (NO_ACCESS(PI_ACCESS_FLASH)) goto noaccess;
	if (BDOOR_IS_STORE(type)) {
	    p += 14;
            if ((t = BE2HO_4(*(int*)buf))&PI_FLASH_CTRL_START) {
                int result = pi_flash(t);
                pi_state.flash_ctrl_read = HO2BE_4(result);
                if (result&PI_FLASH_CTRL_INTR) 
                    mi_eintr(MI_INTR_FLASH, 1);
            } else {
                if (!(t&PI_FLASH_CTRL_INTR)) mi_eintr(MI_INTR_FLASH, 0);
		pi_state.flash_ctrl_read = 
		    (pi_state.flash_ctrl_read&HO2BE_4(PI_FLASH_CTRL_SBERR|PI_FLASH_CTRL_DBERR)) | ((*(int*)buf)&~HO2BE_4(PI_FLASH_CTRL_SBERR|PI_FLASH_CTRL_DBERR));
                *p = (*(int*)buf)/*&HO2BE_4( ~(PI_FLASH_CTRL_SBERR|PI_FLASH_CTRL_DBERR) )*/;
            }
	    goto out;
	} else
	    p = &pi_state.flash_ctrl_read;
	break;
    case PI_FLASH_CONFIG_REG:
	if (NO_ACCESS(PI_ACCESS_FLASH)) goto noaccess;
	p += 15; break;
    case PI_FLASH_ADDR_REG:
	if (NO_ACCESS(PI_ACCESS_FLASH)) goto noaccess;
	p += 16; break;
    case PI_ATBU_REG:
	if (NO_ACCESS(PI_ACCESS_ATB)) goto noaccess;
	p += 17; break;
    case PI_DMA_BUFFER_RD_REG:
	if (NO_ACCESS(PI_ACCESS_BDMA)) goto noaccess;
	if ((BE2HO_4(pi_state.cart_addr)&7) || (BE2HO_4(pi_state.dram_addr)&7))
	    printf("dma to pi buffer is not 8 byte aligned\r\n");
	memcpy((void*)pi_state.buffer+(BE2HO_4(pi_state.cart_addr)&0x3ff),
	       PHYS_TO_MEMADDR(0, BE2HO_4(pi_state.dram_addr)),
	       (BE2HO_4(*(int*)buf)+8)&~7);
	mi_intr(MI_INTR_PI, 1);
	p += 18; break;
    case PI_DMA_BUFFER_WR_REG:
	if (NO_ACCESS(PI_ACCESS_BDMA)) goto noaccess;
	if ((BE2HO_4(pi_state.cart_addr)&1) || (BE2HO_4(pi_state.dram_addr)&1))
	    printf("dma from pi buffer is not 2 byte aligned\r\n");
	memcpy(PHYS_TO_MEMADDR(0, BE2HO_4(pi_state.dram_addr)),
	       (void*)pi_state.buffer+(BE2HO_4(pi_state.cart_addr)&0x3ff),
	       (BE2HO_4(*(int*)buf)+2)&~1);
	mi_intr(MI_INTR_PI, 1);
	p += 19; break;
    case PI_GPIO_REG:
	if (NO_ACCESS(PI_ACCESS_GPIO)) goto noaccess;
	p += 20;
	if (!BDOOR_IS_LOAD(type)) {
	    static char* off_on[] = { "off", "on" };
	    t = BE2HO_4(*(int*)buf)&0xffff;
            if (t&((PI_GPIO_POWER_BIT<<PI_GPIO_ENABLE_SHIFT)))
		fprintf(stderr, "power %s\r\n", off_on[t&PI_GPIO_POWER_BIT]);
	    *p = HO2BE_4(t|0xbabe0000);
	    if ((t&PI_GPIO_POWER_BIT) == 0) exit(0);
	    goto out;
	}
        break;
    case PI_ACCESS_REG:
	p += 21; break;
    case PI_ERROR_REG:
	if (NO_ACCESS(PI_ACCESS_ERROR)) goto noaccess;
	p += 22; break;
    case PI_EDATA_REG:
	p += 23; break;
    case PI_IDE_CONFIG_REG:
	if (NO_ACCESS(PI_ACCESS_IO)) goto noaccess;
	p += 24; break;
    case PI_IDE_CTRL_REG:
	if (NO_ACCESS(PI_ACCESS_IO)) goto noaccess;
	p += 25; break;
    case PI_IDE_FC_BASE_REG:
	tmp = 0; p = &tmp; printreg=0; break;
#endif
    default:
        fprintf(stderr, "undefined PI access 0x%x type 0x%x\r\n", addr, type);
	exit(0);
    }
rw:
    if (BDOOR_IS_LOAD(type))
    	*(int*)buf = *p;
    else
    	*p = *(int*)buf;
out:
    if (addr >= PI_BUFFER_BASE_REG && addr < PI_BUFFER_BASE_REG+256*8) {
//	if (addr >= PI_BUFFER_BASE_REG+2*528)
//	    fprintf(stderr, "%-14s[%d] %s %x\r\n", "PI_BUFFER_BASE_REG", (addr-PI_BUFFER_BASE_REG)/4, __types[type&1], BE2HO_4(*p));
    } else {
	if ( (pi_state.debug) && printreg ) {
            print_reg(pi_regs, addr, type, *p);
        }
    }
    if (dma_read || dma_write)
    	pi_dma(dma_read);
    return;
noaccess:
    fprintf(stderr, "access violation\r\n");
    tmp = 0; p = &tmp; goto rw;
}

#ifdef BBPLAYER
/*
 * UI - USB Interface
 */
struct regs ui_regs[] = {
    REG(USB0_PER_ID),
    REG(USB0_ID_COMP),
    REG(USB0_REV),
    REG(USB0_ADD_INFO),
    REG(USB0_OTG_INT_STAT),
    REG(USB0_OTG_INT_EN),
    REG(USB0_OTG_STATUS),
    REG(USB0_OTG_CTRL),
    REG(USB0_INT_STAT),
    REG(USB0_INT_ENB),
    REG(USB0_ERR_STAT),
    REG(USB0_ERR_ENB),
    REG(USB0_STAT),
    REG(USB0_CTL),
    REG(USB0_ADDR),
    REG(USB0_BDT_PAGE_01),
    REG(USB0_FRM_NUML),
    REG(USB0_FRM_NUMH),
    REG(USB0_TOKEN),
    REG(USB0_SOFTHLDL),
    REG(USB0_BDT_PAGE_02),
    REG(USB0_BDT_PAGE_03),
    REG(USB0_ENDPT0),
    REG(USB0_ENDPT1),
    REG(USB0_ENDPT2),
    REG(USB0_ENDPT3),
    REG(USB0_ENDPT4),
    REG(USB0_ENDPT5),
    REG(USB0_ENDPT6),
    REG(USB0_ENDPT7),
    REG(USB0_ENDPT8),
    REG(USB0_ENDPT9),
    REG(USB0_ENDPT10),
    REG(USB0_ENDPT11),
    REG(USB0_ENDPT12),
    REG(USB0_ENDPT13),
    REG(USB0_ENDPT14),
    REG(USB0_ENDPT15),
    REG(USB1_PER_ID),
    REG(USB1_ID_COMP),
    REG(USB1_REV),
    REG(USB1_ADD_INFO),
    REG(USB1_OTG_INT_STAT),
    REG(USB1_OTG_INT_EN),
    REG(USB1_OTG_STATUS),
    REG(USB1_OTG_CTRL),
    REG(USB1_INT_STAT),
    REG(USB1_INT_ENB),
    REG(USB1_ERR_STAT),
    REG(USB1_ERR_ENB),
    REG(USB1_STAT),
    REG(USB1_CTL),
    REG(USB1_ADDR),
    REG(USB1_BDT_PAGE_01),
    REG(USB1_FRM_NUML),
    REG(USB1_FRM_NUMH),
    REG(USB1_TOKEN),
    REG(USB1_SOFTHLDL),
    REG(USB1_BDT_PAGE_02),
    REG(USB1_BDT_PAGE_03),
    REG(USB1_ENDPT0),
    REG(USB1_ENDPT1),
    REG(USB1_ENDPT2),
    REG(USB1_ENDPT3),
    REG(USB1_ENDPT4),
    REG(USB1_ENDPT5),
    REG(USB1_ENDPT6),
    REG(USB1_ENDPT7),
    REG(USB1_ENDPT8),
    REG(USB1_ENDPT9),
    REG(USB1_ENDPT10),
    REG(USB1_ENDPT11),
    REG(USB1_ENDPT12),
    REG(USB1_ENDPT13),
    REG(USB1_ENDPT14),
    REG(USB1_ENDPT15),
    { 0, 0 }
};

#define	USB_MAX_CONTROLLERS	2

struct ui_state {
    /*
     * Register values used for behavioral simulation of ARC core.
     * The values shown by the simulator are stored in ui_reg_array.
     */
    int usb_per_id;
    int usb_id_comp;
    int usb_rev;
    int usb_add_info;
    int usb_otg_int_stat;
    int usb_otg_int_en;
    int usb_otg_status;
    int usb_otg_ctrl;
    int usb_int_stat;
    int usb_int_enb;
    int usb_err_stat;
    int usb_err_enb;
    int usb_stat;
    int usb_ctl;
    int usb_addr;
    int usb_bdt_page_01;
    int usb_frm_numl;
    int usb_frm_numh;
    int usb_token;
    int usb_softhldl;
    int usb_bdt_page_02;
    int usb_bdt_page_03;
    int usb_endpt0;
    int usb_endpt1;
    int usb_endpt2;
    int usb_endpt3;
    int usb_endpt4;
    int usb_endpt5;
    int usb_endpt6;
    int usb_endpt7;
    int usb_endpt8;
    int usb_endpt9;
    int usb_endpt10;
    int usb_endpt11;
    int usb_endpt12;
    int usb_endpt13;
    int usb_endpt14;
    int usb_endpt15;
    int usb_sec_mode;
    int usb_clock_select;
    int debug;
} ui_state[USB_MAX_CONTROLLERS];

#define	USB_BDT_SIZE	512
#define	USB_REG_SIZE	512
#define	USB_BDT_OFFSET	0x80000

#define USB_REG_OFFSET(u0reg)    ((u0reg) - USB0_BASE_REG)
#define USB_REG_ADDR(which,u0reg)        ((ui_reg_array[which])+\
		                (USB_REG_OFFSET(u0reg))/4)
#define USB_REG(which,u0reg)	(*USB_REG_ADDR(which,u0reg))
#define USB_BDT_BASE(which)	((which) ? USB1_BDT_SRAM : USB0_BDT_SRAM)

/*
 * This flag will cause the ui module to simulate the
 * USB0 port being connected to USB1 with a mini-B connector
 * on the USB1 end, meaning that it is the slave.
 */
#define USB_LOOPBACK	1

int *ui_reg_array[USB_MAX_CONTROLLERS];
char *ui_bdt[USB_MAX_CONTROLLERS];

void
ui_init()
{
	int i;

	fprintf(stderr, "ui_init\r\n");
	for (i = 0; i < USB_MAX_CONTROLLERS; i++) {
		if ((ui_reg_array[i] = (int *)malloc(USB_REG_SIZE)) == NULL) {
			fprintf(stderr, "ui_init malloc fails!\r\n");
			exit(1);
		}
		bzero((void *)(ui_reg_array[i]), USB_REG_SIZE);
		if ((ui_bdt[i] = (char *)malloc(USB_BDT_SIZE)) == NULL) {
			fprintf(stderr, "ui_init malloc fails!\r\n");
			exit(1);
		}
		bzero((void *)(ui_bdt[i]), USB_BDT_SIZE);
		fprintf(stderr, "ui_init: which %d, bdt 0x%x, reg 0x%x\r\n",
				i, (int)(ui_bdt[i]), (int)(ui_reg_array[i]));
	}

	/*
	 * Set initial register values
	 */
	for (i = 0; i < USB_MAX_CONTROLLERS; i++) {
		USB_REG(i, USB0_PER_ID_REG) = HO2BE_4(0x4);
		USB_REG(i, USB0_ID_COMP_REG) = HO2BE_4(0xfb);
		USB_REG(i, USB0_REV_REG) = HO2BE_4(0x12);
		USB_REG(i, USB0_ADD_INFO_REG) = HO2BE_4(0x1);
		if (i) {
			/*
			 * For USB1, default to being a device
			 */
			USB_REG(i, USB0_OTG_STATUS_REG) = HO2BE_4(0xa8);
		} else {
			USB_REG(i, USB0_OTG_STATUS_REG) = HO2BE_4(0x21);
		}
		ui_state[i].debug = 0;
	}

}

static void
ui_intr()
{
	/*
	 * Remember what we have told mi_eintr about the two USB interrupts.
	 * We only call mi_eintr when we really need to make a change.
	 */
	static unsigned int hw_usb_intr_state = 0;
	unsigned int newstate = 0;
	unsigned int intr, mask;
	int set, which;

	/*
	 * Do the "OR" for each USB controller to figure out whether
	 * any interrupts are currently active.
	 */
	for (which = 0; which < USB_MAX_CONTROLLERS; which++) {
		intr = BE2HO_4(ui_state[which].usb_int_stat);
		mask = BE2HO_4(ui_state[which].usb_int_enb);
		set = ((intr & mask) != 0);
		intr = BE2HO_4(ui_state[which].usb_otg_int_stat);
		mask = BE2HO_4(ui_state[which].usb_otg_int_en);
		set |= ((intr & mask) != 0);

		if (set)
			newstate |= (which ? MI_INTR_USB1 : MI_INTR_USB0);
	}

	/*
	 * First turn off any newly offed bits
	 */
	if ((hw_usb_intr_state & ~newstate) != 0) {
		mi_eintr(hw_usb_intr_state & ~newstate, 0);
	}

	/*
	 * Then turn on any newly on bits
	 */
	if ((newstate & ~hw_usb_intr_state) != 0) {
		mi_eintr(newstate & ~hw_usb_intr_state, 1);
	}

	hw_usb_intr_state = newstate;
	return;
}

#if USB_LOOPBACK
#define RELOAD_SOF_COUNT	16
static volatile int sof_count = -1;
#endif

static void
ui_state_machine(int which)
{
	struct ui_state *usp = &ui_state[which];

	/*
	 * Pass error interrupt status up to INT_STAT reg
	 */
	if ((usp->usb_err_enb & usp->usb_err_stat) != 0)
		usp->usb_int_stat |= HO2BE_4(0x02);
	else
		usp->usb_int_stat &= ~HO2BE_4(0x02);
	USB_REG(which, USB0_INT_STAT_REG) = usp->usb_int_stat;

#if USB_LOOPBACK
	/*
	 * If the host has set CTL USB_EN, then we need to generate
	 * SOF interrupts periodically on both host and slave.
	 */
	if (sof_count == 0) {
		usp->usb_int_stat |= HO2BE_4(0x04);
		USB_REG(which, USB0_INT_STAT_REG) = usp->usb_int_stat;
	}
#endif
	ui_intr();
}

static void
ui_poll()
{
#if USB_LOOPBACK
	if (sof_count > 0)
		if (--sof_count == 0) {
			ui_state_machine(0);
			ui_state_machine(1);
			sof_count = RELOAD_SOF_COUNT;
		}
#endif
}

static void
ui_ctl_write(int which, unsigned int val)
{
#if USB_LOOPBACK
	unsigned int newval;

	val = BE2HO_4(val);

fprintf(stderr, "==ui%d: write CTL 0x%x\r\n", which, val);
	/*
	 * When USB1 turns on VBUS by writing to CTL, generate an 
	 * ATTACH interrupt to USB0. 
	 *
	 * Turns out this generates too many ATTACH interrupts.
	 * We need to check and do it only if USB0 has not already
	 * turned on SOF interrupts.
	 */
	if ((which == 1) && ((val & 0x1) == 0x1)) {
		/* Get current CTL value for USB0 */
		newval = BE2HO_4(ui_state[0].usb_ctl);
		if ((newval & 0x1) == 0) {
			/* SOF interrupts are off, so send ATTACH intr */
			newval = HO2BE_4(
				BE2HO_4(ui_state[0].usb_int_stat) | 0x40);
			ui_state[0].usb_int_stat = newval;
			USB_REG(0, USB0_INT_STAT_REG) = newval;
			ui_intr();
fprintf(stderr, "==ui%d: send ATTACH to USB0\r\n", which);
		} else {
fprintf(stderr, "==ui%d: DONT send ATTACH to USB0\r\n", which);
		}
	}

	/*
	 * When USB0 turns on USB_RST and HOST_EN, generate a reset interrupt
	 * on USB1.
	 */
	if ((which == 0) && ((val & 0x18) == 0x18)) {
		newval = HO2BE_4(BE2HO_4(ui_state[1].usb_int_stat) | 0x01);
		ui_state[1].usb_int_stat = newval;
		USB_REG(1, USB0_INT_STAT_REG) = newval;
		ui_intr();
	}

	/*
	 * If USB0 turns on HOST_EN and USB_EN, start generating SOF interrupts
	 */
	if ((which == 0) && ((val & 0x09) == 0x09))
		if (sof_count == -1)
			sof_count = RELOAD_SOF_COUNT;

	/*
	 * If USB0 turns off USB_EN, then stop generating SOF interrupts
	 */
	if ((which == 0) && ((val & 0x01) == 0x00))
		if (sof_count >= 0)
			sof_count = -1;

	/*
	 * Store the value in the ui_state
	 */
	ui_state[which].usb_ctl = HO2BE_4(val);
#endif /* USB_LOOPBACK */
	return;
}

union bdt {
	struct {
		ushort	pid;
		ushort  bc;
		void *	bufp;
	} real;
};

#define	USB_TX	1	/* direction is from memory to VUSB */
#define	USB_RX	0	/* direction is from VUSB to memory */

/*
 * Here's where the main action happens for USB loopback.
 * Writing a token to the TOKEN register on the host side
 * initiates a transaction on the bus.
 */
static void
ui_token_write(int which, unsigned int val)
{
#if USB_LOOPBACK
	struct ui_state *usp;
	union bdt *hostbp;
	union bdt *devbp;
	int dest_addr;
	int ept;
	int token_pid;
	int direction;
	int host_bc;
	void *host_bufp;
	int dev_bc;
	void *dev_bufp;
	void *from, *to;
	int from_bc, to_bc;
	int other;
	int odd;
	unsigned int newval;

	/*
	 * The host writes the token register to start a transfer
	 */
	val = BE2HO_4(val);
	ept = val & 0xf;
	token_pid = (val & 0xf0) >> 4;
fprintf(stderr, "ui%d: send %x TOKEN to EPT %d\r\n", which, token_pid, ept);

	/*
	 * Only the host ever writes tokens, which means that
	 * USB1 never does it in loopback mode.
	 */
	if (which != 0) {
		fprintf(stderr, "ui%d: write TOKEN cant happen!\r\n", which);
		return;
	}

	/*
	 * Direction is determined by the setting of the token_pid:
	 */
	direction = (token_pid == 0x1 || token_pid == 0xd) ? USB_TX : USB_RX;
	if (direction == USB_RX && token_pid != 0x9) {
		/* Can't happen! */
		fprintf(stderr, "ui%d: invalid TOKEN PID 0x%x\r\n", which, token_pid);
		return;
	}

	/* destination device address */
	dest_addr = BE2HO_4(USB_REG(which, USB0_ADDR_REG)) & 0x7f;
fprintf(stderr, "ui%d: dest addr 0x%x\r\n", which, dest_addr);

	/* calculate the address of the BDT entry for this transaction */
	hostbp = (union bdt *) ui_bdt[which];

	hostbp += (direction << 1);	/* for Host EPT == 0 */

	/*
	 * If this one is still OWNed by the cpu, it must be the
	 * other one of this pair.
	 *
	 */
	odd = 0;
	if ((hostbp->real.pid & 0x80) == 0) {
		hostbp++;
		odd = 1;
		if ((hostbp->real.pid & 0x80) == 0) {
			/* shouldn't happen that both are owned by cpu */
			fprintf(stderr, "ui%d: both BDTs owned by CPU\r\n", which);
			/* Now what?? */
		}
	} else {
		/*
		 * It is technically possible that both are owned by
		 * the VBUS, in which case we need to guess which one
		 * should be used first.  Compare buffer addresses
		 * and use the lower of the two.
		 */
		union bdt *altbp = hostbp + 1;
		void *alt_bufp;

		if ((altbp->real.pid & 0x80) != 0) {
			alt_bufp = altbp->real.bufp;
			host_bufp = hostbp->real.bufp;

			if ((unsigned int)alt_bufp < (unsigned int)host_bufp) {
				hostbp = altbp;
				odd = 1;
			}
		}
	}

	host_bufp = hostbp->real.bufp;
	host_bc = hostbp->real.bc;

	/*
	 * Set the status register and post TOKEN_DONE for the Host to
	 * indicate completion of the transaction. 
	 *
	 * Device will get one too, but later.
	 */
        usp = &ui_state[which];
	usp->usb_stat = USB_REG(which, USB0_STAT_REG) =
	       	HO2BE_4((direction<<3) | (odd<<2));
	newval = BE2HO_4(USB_REG(which, USB0_INT_STAT_REG));
	usp->usb_int_stat =
	       	USB_REG(which, USB0_INT_STAT_REG) = HO2BE_4(newval | 0x08);

	/*
	 * Find the appropriate BDT on the other controller
	 */
	other = (which == 0);
	direction = (direction == 0);
	devbp = (union bdt *) ui_bdt[other];
	devbp += (ept << 2) | (direction << 1);

	/*
	 * Find BDT owned by the VBUS.
	 *
	 * If both are owned by the bus, then we need to pick the one
	 * with the lower buffer address.
	 */
	odd = 0;
	if ((devbp->real.pid & 0x80) == 0) {
		odd = 1;
		devbp++;
		if ((devbp->real.pid & 0x80) == 0) {
			/* shouldn't happen that both are owned by cpu */
			fprintf(stderr, "ui%d: both BDTs owned by CPU\r\n", other);
			/* XXX Now what?? */
		}
	} else {
		/*
		 * Even one is owned by the VBUS.  Check the other.
		 */
		union bdt *altbp = devbp+1;
		void *alt_bufp;
		if ((altbp->real.pid & 0x80) != 0) {
			/*
			 * Both are owned by VBUS, so use the one with the
			 * lower buffer address first.
			 */
			dev_bufp = devbp->real.bufp;
			alt_bufp = altbp->real.bufp;
			if ((unsigned int)alt_bufp < (unsigned int)dev_bufp) {
				devbp = altbp;
				odd = 1;
			}
		}
	}
	dev_bufp = devbp->real.bufp;
	dev_bc = devbp->real.bc;

	/*
	 * From and to depend on which direction the data is going, of course.
	 * By this point "direction" is from the POV of the device.
	 */
	if (direction) {
		/*
		 * Data is going from Device to Host
		 */
		from = dev_bufp;
		from_bc = dev_bc;
		to = host_bufp;
		to_bc = host_bc;
	} else {
		from = host_bufp;
		from_bc = host_bc;
		to = dev_bufp;
		to_bc = dev_bc;
	}

	if (from_bc > to_bc) {
		fprintf(stderr, "ui%d: recv BDT too small (f%d, t%d)\r\n",
			(direction ? which : other), from_bc, to_bc);
		from_bc = to_bc;
	}

	/*
	 * Note that the buffers here are PHYS addresses in the simulated
	 * machine.  We need to get at the data, so we convert to
	 * MEMADDR first.
	 */
	if (from != 0 && to != 0 && from_bc > 0) {

		if (IS_VALID_PA(0, from)) {
			from = (void *)PHYS_TO_MEMADDR(0, from);
			if (IS_VALID_PA(0, to)) {
				to = (void *)PHYS_TO_MEMADDR(0, to);
				bcopy(from, to, from_bc);
fprintf(stderr, "ui%d: bcopy(0x%x, 0x%x, %d)\r\n", which, (int)from, (int)to, from_bc);
			} else {
				fprintf(stderr, "ui%d: bad to addr 0x%x\r\n",
					       	which, (int)to);
			}
		} else {
			fprintf(stderr, "ui%d: bad from addr 0x%x\r\n",
					 which, (int)from);
		}
	}

	/*
	 * Update BDTs to reflect the completion of the transaction
	 */
	if (direction) {
		devbp->real.pid = token_pid << 2;

		/* Update Host BDT with transaction status */
		hostbp->real.bc = from_bc;
		hostbp->real.pid = 0x3 << 2;	/* DATA0 XXX */
	} else {
		devbp->real.bc = from_bc;
		devbp->real.pid = token_pid << 2;

		/* Update Host BDT with transaction status */
		hostbp->real.pid = 0x2 << 2;	/* ACK */
	}

	/*
	 * Set the status register and send TOKEN_DONE to the device
	 */
        usp = &ui_state[other];
	usp->usb_stat = USB_REG(other, USB0_STAT_REG) =
	       	HO2BE_4((ept<<4) | (direction<<3) | (odd<<2));
	newval = BE2HO_4(USB_REG(other, USB0_INT_STAT_REG));
	usp->usb_int_stat =
	       	USB_REG(other, USB0_INT_STAT_REG) = HO2BE_4(newval | 0x08);
	ui_intr();
#endif /* USB_LOOPBACK */
	return;
}

static void
ui(int which, int addr, int type, void* buf)
{
	int *p = 0;
	int base, offset;
	int runstate = 0;
	struct ui_state *usp = &ui_state[which];

	/*
	 * Check validity of address
	 */
	if (addr & 0x3) {
		fprintf(stderr, "ui%d: 0x%x not word aligned\r\n", which, addr);
	}
	base = (which ? USB1_BASE_REG : USB0_BASE_REG);
	offset = addr - base;
	if (offset >= USB_REG_SIZE) {
	        if (offset == USB_REG_OFFSET(USB0_SECURE_MODE_REG)) {
		    p = &usp->usb_sec_mode;
		} else if (offset == USB_REG_OFFSET(USB0_CLOCK_SELECT_REG)) {
		    p = &usp->usb_clock_select;
		} else if (offset < USB_BDT_OFFSET ||
				offset >= (USB_BDT_OFFSET+USB_BDT_SIZE))
			fprintf(stderr, "ui%d: 0x%x bad address\r\n", which, addr);
		else {
			/*
			 * It is a BDT Address
			 */
		       	offset -= USB_BDT_OFFSET;
		       	p = (int *)(ui_bdt[which] + offset);
		}
	} else {
		/*
		 * It is a register address
		 */
		p = ui_reg_array[which] + (offset/sizeof(int));
		if (BDOOR_IS_STORE(type)) {
			/*
			 * Check for registers with complicated behavior
			 */
			unsigned int val = *(unsigned int *)buf;

			/*
			 * Magic backdoor:  if high order 8 bits of
			 * word being stored is 0x42, set values rather than
			 * clearing them.
			 */
#define USB_MAGIC_MASK	0xff000000
#define USB_MAGIC_VAL	0x42000000
#define IS_USB_MAGIC(v)	(((BE2HO_4(v)) & USB_MAGIC_MASK) == USB_MAGIC_VAL)
#define UN_MAGIC(v)	(HO2BE_4((BE2HO_4(v)) & ~USB_MAGIC_MASK))
#if 0
if (IS_USB_MAGIC(val)) {
fprintf(stderr, "ui%d: backdoor write offset 0x%x val 0x%x\r\n", which, offset, BE2HO_4(val));
}
#endif
			switch (offset) {
			case USB_REG_OFFSET(USB0_OTG_INT_EN_REG):
				usp->usb_otg_int_en = val;
				break;
			case USB_REG_OFFSET(USB0_OTG_INT_STAT_REG):
				if (IS_USB_MAGIC(val))
					usp->usb_otg_int_stat = UN_MAGIC(val);
				else
					usp->usb_otg_int_stat &= ~val;
				*(unsigned int *)buf = usp->usb_otg_int_stat;
				break;
			case USB_REG_OFFSET(USB0_INT_ENB_REG):
				usp->usb_int_enb = val;
				break;
			case USB_REG_OFFSET(USB0_INT_STAT_REG):
				if (IS_USB_MAGIC(val))
					usp->usb_int_stat = UN_MAGIC(val);
				else
					usp->usb_int_stat &= ~val;
				*(unsigned int *)buf = usp->usb_int_stat;
				break;
			case USB_REG_OFFSET(USB0_ERR_ENB_REG):
				usp->usb_err_enb = val;
				break;
			case USB_REG_OFFSET(USB0_ERR_STAT_REG):
				if (IS_USB_MAGIC(val))
					usp->usb_err_stat = UN_MAGIC(val);
				else
					usp->usb_err_stat &= ~val;
				*(unsigned int *)buf = usp->usb_err_stat;
				break;
			case USB_REG_OFFSET(USB0_CTL_REG):
				ui_ctl_write(which, val);
				break;
			case USB_REG_OFFSET(USB0_TOKEN_REG):
				ui_token_write(which, val);
				break;
			default:
				break;
			}
			
			runstate++;
		}
	}

    	if (p) {
		if (BDOOR_IS_LOAD(type))
    			*(int*)buf = *p;
    		else {
    			*p = *(int*)buf;
		}
	}

	/*
	 * Run the state machine
	 */
	if (runstate)
		ui_state_machine(which);
	if (ui_state[which].debug)
		print_reg(ui_regs, addr, type, *p);
}
#endif /* BBPLAYER */

/*
 * VI
 */

struct regs vi_regs[] = {
    REG(VI_STATUS),
    REG(VI_ORIGIN),
    REG(VI_WIDTH),
    REG(VI_INTR),
    REG(VI_CURRENT),
    REG(VI_BURST),
    REG(VI_V_SYNC),
    REG(VI_H_SYNC),
    REG(VI_LEAP),
    REG(VI_H_START),
    REG(VI_V_START),
    REG(VI_V_BURST),
    REG(VI_X_SCALE),
    REG(VI_Y_SCALE),
    { 0, 0 }
};

struct vi_state {
    int status;
    int origin;
    int width;
    int intr;
    int current;
    int burst;
    int v_sync;
    int h_sync;
    int leap;
    int h_start;
    int v_start;
    int v_burst;
    int x_scale;
    int y_scale;
    int debug;
} vi_state;

static void
vi_init(void) {
}

static void
vi_poll(void) {
    static int counter;

    if (counter++ != 40) return;
    counter = 0;
    if (vi_state.intr) {
    	vi_state.intr = HO2BE_4(BE2HO_4(vi_state.intr) - 1);
	if (!vi_state.intr) {
	    fprintf(stderr, "vi intr\r\n");
	    mi_intr(MI_INTR_VI, 1);
	} else {
	    fprintf(stderr, "vi intr reg %d\r\n", BE2HO_4(vi_state.intr));
	}
    }
}

static void
vi(int addr, int type, void* buf) {
    int *p = &vi_state.status;
    switch(addr) {
    case VI_STATUS_REG:
        p += 0; break;
    case VI_ORIGIN_REG:
        p += 1; break;
    case VI_WIDTH_REG:
    	p += 2; break;
    case VI_INTR_REG:
    	p += 3; break;
    case VI_CURRENT_REG:
    	mi_intr(MI_INTR_VI, 0);
    	p += 4; break;
    case VI_BURST_REG:
    	p += 5; break;
    case VI_V_SYNC_REG:
    	p += 6; break;
    case VI_H_SYNC_REG:
    	p += 7; break;
    case VI_LEAP_REG:
    	p += 8; break;
    case VI_H_START_REG:
    	p += 9; break;
    case VI_V_START_REG:
    	p += 10; break;
    case VI_V_BURST_REG:
    	p += 11; break;
    case VI_X_SCALE_REG:
    	p += 12; break;
    case VI_Y_SCALE_REG:
    	p += 13; break;
    default:
        fprintf(stderr, "undefined VI access 0x%x type 0x%x\r\n", addr, type);
	exit(0);
    }
    if (BDOOR_IS_LOAD(type))
    	*(int*)buf = *p;
    else
    	*p = *(int*)buf;
    if (vi_state.debug) print_reg(vi_regs, addr, type, *p);
}

/*
 * AI
 */

struct regs ai_regs[] = {
    REG(AI_DRAM_ADDR),
    REG(AI_LEN),
    REG(AI_CONTROL),
    REG(AI_STATUS),
    REG(AI_DACRATE),
    REG(AI_BITRATE),
    { 0, 0 }
};

struct ai_state {
    int dram_addr;
    int len;
    int control;
    int status;
    int dacrate;
    int bitrate;
    int debug;
} ai_state;

static void
ai_init(void) {
}

static void
ai(int addr, int type, void* buf) {
    int *p = &ai_state.status;
    switch(addr) {
    case AI_DRAM_ADDR_REG:
        p += 0; break;
    case AI_LEN_REG:
        p += 1; break;
    case AI_CONTROL_REG:
    	p += 2; break;
    case AI_STATUS_REG:
    	p += 3; break;
    case AI_DACRATE_REG:
    	p += 4; break;
    case AI_BITRATE_REG:
    	p += 5; break;
    default:
        fprintf(stderr, "undefined AI access 0x%x type 0x%x\r\n", addr, type);
	exit(0);
    }
    if (BDOOR_IS_LOAD(type))
    	*(int*)buf = *p;
    else
    	*p = *(int*)buf;
    if (ai_state.debug) print_reg(ai_regs, addr, type, *p);
}

/*
 * RI
 */

struct regs ri_regs[] = {
#ifdef BBPLAYER
    REG(RI_NMODE),
    REG(RI_NREFRESH),
    REG(RI_XMEM),
    REG(RI_STROBE_REV),
    REG(RI_AUTO_PRE_CHG),
    REG(RI_DDR_CONFIG),
#endif
    { 0, 0 }
};

struct ri_state {
#ifdef BBPLAYER
    int nmode;
    int nrefresh;
    int xmem;
    int strobe_rev;
    int auto_precharge;
    int ddr_config;
#endif
    int debug;
} ri_state;

static void
ri_init(void) {
}

static void
ri(int addr, int type, void* buf) {
    int *p = &ri_state.nmode;
    switch(addr) {
#ifdef BBPLAYER
    case RI_NMODE_REG:
        p += 0; break;
    case RI_NREFRESH_REG:
        p += 1; break;
    case RI_XMEM_REG:
    	p += 2; break;
    case RI_STROBE_REV_REG:
    	p += 3; break;
    case RI_AUTO_PRE_CHG_REG:
    	p += 4; break;
    case RI_DDR_CONFIG_REG:
    	p += 5; break;
#endif
    default:
        fprintf(stderr, "undefined RI access 0x%x type 0x%x\r\n", addr, type);
	exit(0);
    }
    if (BDOOR_IS_LOAD(type))
    	*(int*)buf = *p;
    else
    	*p = *(int*)buf;
    if (ri_state.debug) print_reg(ri_regs, addr, type, *p);
}

static struct {
    char* name;
    int *debug;
} debug[] = {
    { "AI", &ai_state.debug },
    { "MI", &mi_state.debug },
    { "PI", &pi_state.debug },
    { "RI", &ri_state.debug },
    { "SI", &si_state.debug },
    { "SP", &sp_state.debug },
    { "VI", &vi_state.debug },
#ifdef BBPLAYER
    { "UI0", &ui_state[0].debug },
    { "UI1", &ui_state[1].debug },
#endif
    { 0, 0 }
};
void
rcp_init(void) {
    int i;
    sram_map();
    sp_init();
    si_init();
    pi_init();
    mi_init();
    vi_init();
    ai_init();
    ri_init();
#ifdef BBPLAYER
    virage_init();
    nand_init();
    ui_init();
#endif
    if (getenv("SIMOS_BCPDEBUG")) {
	for(i = 0; debug[i].name; i++) {
	    if (strstr(getenv("SIMOS_BCPDEBUG"), debug[i].name))
		*debug[i].debug = 1;
	}
    }
    if (getenv("SIMOS_ISBB"))
	isbb = atoi(getenv("SIMOS_ISBB"));
}

int
rcp_handler(int node, int nd, int doff, int type, void* buf) {
    if (BDOOR_SIZE(type) != sizeof(int) && !PI_IS_IDE(doff)
            && !PI_IS_BUF_DATA_LOAD(doff,type)) {
    	fprintf(stderr, "non-word RCP access @ %08x type 0x%x\r\n", doff, type);
    }
    switch((doff >> 20)&0xf) {
    case 0:	/* SP */
    	/*fprintf(stderr, "SP access %08x\r\n", doff);*/
	sp(doff, type, buf);
	break;
    case 1:	/* DP command */
    	fprintf(stderr, "DP cmd access %08x\r\n", doff);
	break;
    case 2:	/* DP span */
    	fprintf(stderr, "DP span access %08x\r\n", doff);
	break;
    case 3:	/* MI */
    	/*fprintf(stderr, "MI access %08x\r\n", doff);*/
	mi(doff, type, buf);
	break;
    case 4:	/* VI */
    	/*fprintf(stderr, "VI access %08x\r\n", doff);*/
	vi(doff, type, buf);
	break;
    case 5:	/* AI */
    	/*fprintf(stderr, "AI access %08x\r\n", doff);*/
	ai(doff, type, buf);
	break;
    case 6:	/* PI */
    	/*fprintf(stderr, "PI access %08x\r\n", doff);*/
	pi(doff, type, buf);
	break;
    case 7:	/* RI */
    	/*fprintf(stderr, "RI access %08x\r\n", doff);*/
	ri(doff, type, buf);
	break;
    case 8:	/* SI */
    	/*fprintf(stderr, "SI access %08x\r\n", doff);*/
	si(doff, type, buf);
	break;
#ifdef BBPLAYER
    case 9:	/* UI */
    	/*fprintf(stderr, "UI access %08x\r\n", doff);*/
	ui(0, doff, type, buf);
	break;
    case 10:	/* UI */
    	/*fprintf(stderr, "UI access %08x\r\n", doff);*/
	ui(1, doff, type, buf);
	break;
#endif
    default:	/* not used */
    	fprintf(stderr, "undefined RCP access @ %08x type 0x%x\r\n", doff, type);
    	exit(0);
    }
    return 0;
}

void
sim_rcp_poll(void) {
    /* generate a VI interrupt */
    vi_poll();
#ifdef BBPLAYER
    mi_poll();
    ui_poll();
#endif
}

struct pif_state {
    int data[16];	/* 60 bytes of data */
    int status;
    int debug;
} pif_state;

struct regs pif_regs[] = {
    { 0x1fc007fc, "PIF_STATUS" },
    { 0, 0 }
};

int
pif_handler(int node, int nd, int doff, int type, void* buf) {
    int *p = (int*)((char*)&pif_state + ((doff-0x7c0)&0xff));
    if (BDOOR_SIZE(type) != sizeof(int)) {
    	fprintf(stderr, "non-word PIF access @ %08x type 0x%x\r\n", doff, type);
    }
    if (BDOOR_IS_LOAD(type))
    	*(int*)buf = *p;
    else
    	*p = *(int*)buf;
    if (pif_state.debug) print_reg(pif_regs, doff, type, *p);
    return 0;
}

int
cd1_handler(int node, int nd, int doff, int type, void* buf) {
    return pi_pio(doff, type, buf);
}

void
rdb_decode(int d) {
    extern void ChangeInterrupt(int cpu, int code, int v);
    unsigned char* p = (unsigned char*)&d;
    int len = p[0]&3;
    int count, i, rdb;
    FILE* logfd = 0;
    switch(p[0] >> 2) {
    case RDB_TYPE_INVALID:
unhandled:
	fprintf(stderr, "unhandled rdb request %x\r\n", p[0]>>2);
	break;
    case RDB_TYPE_GtoH_PRINT:
	for(i = 0; i < len; i++) {
	    fprintf(stderr, "%c", p[i+1]);
	    if (p[i+1] == '\n') fprintf(stderr, "\r");
	}
	mi_eintr(MI_INTR_IDE, 1);
	break;
    case RDB_TYPE_GtoH_FAULT:
	goto unhandled;
    case RDB_TYPE_GtoH_LOG_CT: {
	count = (p[1] << 16)|(p[2]<<8)|p[3];
	fprintf(stderr, "write log, count = %d\r\n", count);
	ChangeInterrupt(0, CAUSE_IP6 >> CAUSE_IPSHIFT, 1);
	break;
    }
    case RDB_TYPE_GtoH_LOG:
	if (!logfd) {
	    int hdr[2] = { HO2BE_4(0x20736a73), HO2BE_4(1) };
	    logfd = fopen("ulog.dat", "w");
	    fwrite(hdr, sizeof hdr, 1, logfd);
	}
	fwrite(p+1, len, 1, logfd);
	fflush(logfd);
	count -= len;
	ChangeInterrupt(0, CAUSE_IP6 >> CAUSE_IPSHIFT, 1);
	if (count == 0) {
	    rdb = RDB_TYPE_HtoG_LOG_DONE << 2;
	    ChangeInterrupt(0, CAUSE_IP7 >> CAUSE_IPSHIFT, 1);
	}
	break;
    case RDB_TYPE_GtoH_READY_FOR_DATA:
	break;
    case RDB_TYPE_GtoH_DATA_CT:
    case RDB_TYPE_GtoH_DATA:
    case RDB_TYPE_GtoH_DEBUG:
    case RDB_TYPE_GtoH_RAMROM:
    case RDB_TYPE_GtoH_DEBUG_DONE:
    case RDB_TYPE_GtoH_DEBUG_READY:
    case RDB_TYPE_GtoH_KDEBUG:
    case RDB_TYPE_GtoH_PROF_DATA:
	goto unhandled;
	break;
    }
}

int
rdb_handler(int node, int nd, int doff, int type, void* buf) {
    extern void ChangeInterrupt(int cpu, int code, int v);
    int d;
    unsigned char* p = (unsigned char*)&d;
    static int count;
    static int rdb;
    static FILE* logfd;
    if (BDOOR_SIZE(type) != sizeof(int)) {
    	fprintf(stderr, "non-word RDB access @ %08x type 0x%x\r\n", doff, type);
    }
    if (BDOOR_IS_LOAD(type)) {
	*(int*)buf = rdb;
    } else {
	int len, i;
        d = *(int*)buf;
	if ((doff&0xf) == (RDB_READ_INTR_REG&0xf)) {
	    ChangeInterrupt(0, CAUSE_IP6 >> CAUSE_IPSHIFT, 0);
	    return 0;
	} else if ((doff&0xf) == (RDB_WRITE_INTR_REG&0xf)) {
	    ChangeInterrupt(0, CAUSE_IP7 >> CAUSE_IPSHIFT, 0);
	    return 0;
	}
	if (doff != RDB_BASE_VIRTUAL_ADDR) {
	    fprintf(stderr, "illegal rdb access 0x%x\r\n", doff);
	}
	rdb = d;
	len = p[0]&3;
        switch(p[0] >> 2) {
	case RDB_TYPE_INVALID:
unhandled:
	    fprintf(stderr, "unhandled rdb request %x\r\n", p[0]>>2);
	    break;
	case RDB_TYPE_GtoH_PRINT:
	    for(i = 0; i < len; i++) {
	    	fprintf(stderr, "%c", p[i+1]);
		if (p[i+1] == '\n') fprintf(stderr, "\r");
	    }
	    ChangeInterrupt(0, CAUSE_IP6 >> CAUSE_IPSHIFT, 1);
	    break;
	case RDB_TYPE_GtoH_FAULT:
	    goto unhandled;
	case RDB_TYPE_GtoH_LOG_CT: {
	    count = (p[1] << 16)|(p[2]<<8)|p[3];
	    fprintf(stderr, "write log, count = %d\r\n", count);
	    ChangeInterrupt(0, CAUSE_IP6 >> CAUSE_IPSHIFT, 1);
	    break;
	}
	case RDB_TYPE_GtoH_LOG:
	    if (!logfd) {
		int hdr[2] = { HO2BE_4(0x20736a73), HO2BE_4(1) };
	    	logfd = fopen("ulog.dat", "w");
		fwrite(hdr, sizeof hdr, 1, logfd);
	    }
	    fwrite(p+1, len, 1, logfd);
	    fflush(logfd);
	    count -= len;
	    ChangeInterrupt(0, CAUSE_IP6 >> CAUSE_IPSHIFT, 1);
	    if (count == 0) {
	    	rdb = RDB_TYPE_HtoG_LOG_DONE << 2;
		ChangeInterrupt(0, CAUSE_IP7 >> CAUSE_IPSHIFT, 1);
	    }
	    break;
	case RDB_TYPE_GtoH_READY_FOR_DATA:
	case RDB_TYPE_GtoH_DATA_CT:
	case RDB_TYPE_GtoH_DATA:
	case RDB_TYPE_GtoH_DEBUG:
	case RDB_TYPE_GtoH_RAMROM:
	case RDB_TYPE_GtoH_DEBUG_DONE:
	case RDB_TYPE_GtoH_DEBUG_READY:
	case RDB_TYPE_GtoH_KDEBUG:
	case RDB_TYPE_GtoH_PROF_DATA:
	    goto unhandled;
	    break;
        }
    }
    return 0;
}

#ifdef BBPLAYER
static unsigned char bram[BOOT_RAM_HI_END-BOOT_RAM_HI_START];
static unsigned char iram[INTERNAL_RAM_END-INTERNAL_RAM_START];
static unsigned char virage0[VIRAGE0_RAM_END-VIRAGE0_RAM_START];
static unsigned char virage1[VIRAGE1_RAM_END-VIRAGE1_RAM_START];
static unsigned char virage2[VIRAGE2_RAM_END-VIRAGE2_RAM_START];

static void
sram_map(void) {
    static int init;
    if (init) return;
    init = 1;
    RegistryAddRange((VA)_SEXT(0x1fc20000), 65536,
                      REG_DATA, (void*)bram, "Phys Boot RAM");
    RegistryAddRange((VA)_SEXT(0x1fc40000), 32768,
                      REG_DATA, (void*)iram, "Phys IRAM");
    RegistryAddRange((VA)_SEXT(0x1fc80000), 64,
                      REG_DATA, (void*)virage0, "Phys Virage0");
    RegistryAddRange((VA)_SEXT(0x1fc90000), 64,
                      REG_DATA, (void*)virage1, "Phys Virage1");
    RegistryAddRange((VA)_SEXT(0x1fca0000), 256,
                      REG_DATA, (void*)virage2, "Phys Virage2");
}

int
sram_handler(int node, int nd, int doff, int type, void* buf) {
    void* addr = 0;
    doff &= 0x1fffffff;

#if 0
fprintf(stderr, "sram access @ 0x%x\r\n", doff);
#endif
    if (doff >= VIRAGE2_RAM_START && IS_SECURE()) {
	addr = virage2 + doff - VIRAGE2_RAM_START;
	if (BDOOR_SIZE(type) != BDOOR_WORD)
	    CPUWarning("Warning: non-word access to v2 address 0x%x %x\r\n", (int)doff, (int)SBase[0].PC);
    } else if (doff >= VIRAGE1_RAM_START && IS_SECURE()) {
	addr = virage1 + doff - VIRAGE1_RAM_START;
	if (BDOOR_SIZE(type) != BDOOR_WORD)
	    CPUWarning("Warning: non-word access to v1 address 0x%x\r\n", (int)doff);
    } else if (doff >= VIRAGE0_RAM_START && IS_SECURE()) {
	addr = virage0 + doff - VIRAGE0_RAM_START;
	if (BDOOR_SIZE(type) != BDOOR_WORD)
	    CPUWarning("Warning: non-word access to v0 address 0x%x\r\n", (int)doff);
    } else if (doff >= INTERNAL_RAM_START) {
	addr = iram + doff - INTERNAL_RAM_START;
#if 0
	if (!(mi_state.sec_mode & HO2BE_4(MI_SEC_MODE_IRAM_ACCESS)) ) {
	    fprintf(stderr, "rcp: protected IRAM access @ 0x%x\r\n", doff);
	    return 1;
	}
#endif
    } else if (doff >= BOOT_RAM_HI_START ) {
	if (mi_state.sec_mode & HO2BE_4(MI_SEC_MODE_BROM_LO))
	    addr = bram + doff - BOOT_RAM_HI_START;
	else {
	    /* boot rom is at this address */
	    addr = sim_misc.fprom[0] + doff - BOOT_RAM_HI_START;
	    if (BDOOR_IS_STORE(type))
		CPUWarning("Warning: writing to rom address 0x%x\r\n", (int)doff);
	}
    } else if (doff >= BOOT_RAM_LO_START ) {
	if (mi_state.sec_mode & HO2BE_4(MI_SEC_MODE_BROM_LO)) {
	    /* boot rom is at this address */
	    addr = sim_misc.fprom[0] + doff - BOOT_RAM_LO_START ;
	    if (BDOOR_IS_STORE(type))
		CPUWarning("Warning: writing to rom address 0x%x\r\n", (int)doff);
	} else
	    addr = bram + doff - BOOT_RAM_LO_START;
	/* is it to PIF RAM? */
	if (doff >= PIF_RAM_START && doff <= PIF_RAM_END) {
	    static char* a[] = {"load", "store"};
	    if (!isbb || !IS_SECURE() ||
		!(mi_state.sec_mode & HO2BE_4(MI_SEC_MODE_BROM_LO)))
		fprintf(stderr, "rcp: warning %s PIF RAM @ 0x%x\r\n", a[BDOOR_IS_STORE(type)], doff);
	    /* trap ? */
	}
    } else {
	if (BDOOR_IS_STORE(type)) {
	    fprintf(stderr, "rcp: unknown SRAM write @ 0x%x\r\n", doff);
	    if (pi_state.error&HO2BE_4(PI_ERROR_KERNEL_INTR)) {
		mi_secure_mode(MI_SEC_MODE_FATAL);
		return 0;
	    } else if (mi_state.ctrl & HO2BE_4(MI_CTRL_SK_TRAP_PIF)) {
		mi_secure_mode(MI_SEC_MODE_TRAP);
		return 0;
	    }
	} else {
	    fprintf(stderr, "rcp: unknown SRAM read @ 0x%x\r\n", doff);
	    if (!IS_SECURE()) {
		if (mi_state.ctrl & HO2BE_4(MI_CTRL_BUS_ERROR_PIF)) {
		} else {
		    static unsigned char zero[16];
		    addr = zero;
		    goto out;
		}
	    }
	}

	return 1;
    }
    
out:
    switch (type) {
    case BDOOR_LOAD_BYTE:
	*(byte *)buf = *(byte *)addr;
	break;
    case BDOOR_LOAD_HALF:
	*(unsigned short *)buf = *(unsigned short *)addr;
	break;
    case BDOOR_LOAD_WORD:
	*(uint *)buf = *(uint *)addr;
	break;
    case BDOOR_LOAD_DOUBLE:
	*(uint64*)buf = *(uint64*)addr;
	break;
    case BDOOR_STORE_BYTE:
 	*(byte *)addr = *(byte *)buf;
 	break;
    case BDOOR_STORE_HALF:
 	*(unsigned short *)addr = *(unsigned short *)buf;
 	break;
    case BDOOR_STORE_WORD:
 	*(uint *)addr = *(uint *)buf;
 	break;
    case BDOOR_STORE_DOUBLE:
 	*(uint64*)addr = *(uint64*)buf;
 	break;
    default:
 	CPUError("rcp SRAM access is not supported by type %d", type);
  }
  return 0;
}

MA
sram_addr(int machNo, uint pAddr) {
    if (pAddr >= BOOT_RAM_LO_START && pAddr < BOOT_RAM_LO_END &&
	!(mi_state.sec_mode & HO2BE_4(MI_SEC_MODE_BROM_LO)))
	return bram + pAddr-BOOT_RAM_LO_START;
    else if (pAddr >= BOOT_RAM_HI_START && pAddr < BOOT_RAM_HI_END &&
	(mi_state.sec_mode & HO2BE_4(MI_SEC_MODE_BROM_LO)) )
	return bram + pAddr-BOOT_RAM_HI_START;
    else if (pAddr >= BOOT_RAM_LO_START && pAddr < BOOT_RAM_HI_END){
        /* this is bad. the most likely reason to get here is the
         * dcache is populated, pre- bram/brom flip, with an address
         * in the BOOT_RAM_HI range. then, after the flip, an attempt
         * is made to write this value back. the check if the phys
         * addr is valid comes here. the assumed real address is
         * returned, but i don't believe the data is actually ever
         * written on the writeback. rather, cache system sets up
         * timing events to model the writeback. so, this should
         * be pretty harmless.
         */
        return bram + pAddr-BOOT_RAM_HI_START;
    }
    else if (pAddr >= INTERNAL_RAM_START && pAddr < INTERNAL_RAM_END &&
	    (1 || (mi_state.sec_mode&HO2BE_4(MI_SEC_MODE_IRAM_ACCESS))))
	return iram + pAddr-INTERNAL_RAM_START;
    else if (pAddr >= VIRAGE0_RAM_START && pAddr < VIRAGE0_RAM_END )
	return virage0 + pAddr-VIRAGE0_RAM_START;
    else if (pAddr >= VIRAGE1_RAM_START && pAddr < VIRAGE1_RAM_END )
	return virage1 + pAddr-VIRAGE1_RAM_START;
    else if (pAddr >= VIRAGE2_RAM_START && pAddr < VIRAGE2_RAM_END )
	return virage2 + pAddr-VIRAGE2_RAM_START;
    return 0;
}


static void
read_data(unsigned char** data, int size, const char* file) {
    FILE* fp;
    int x, n, *p;
    struct stat sb;
    char line[1024];

    if (!file) {
	*data = (unsigned char*)p = malloc(size);
	return;
    }

    if (!(fp = fopen(file, "r"))) {
	perror(file);
	exit(1);
    }
    n = fread(line, 1, sizeof line, fp);
    for(x = 0; x < n; x++)
	if (!isascii(line[x])) goto binary;
    fseek(fp, 0L, SEEK_SET);
    *data = (unsigned char*)p = malloc(size);
    while ((unsigned char*)p < *data+size && fscanf(fp, "%x", &x) == 1) {
	*p++ = HO2BE_4(x);
    }
    fclose(fp);
    return;
binary:
    if ((fp = freopen(file, "r+", fp)) == NULL) {
	perror(file);
	exit(1);
    }
    fstat(fileno(fp), &sb);
    if ( (*data = 
              mmap(0, sb.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fileno(fp), 0))
             == (void*)-1) {
	perror("virage mmap");
	exit(1);
    }
}

struct regs virage_regs[] = {
    REG(VIRAGE0_CTRL),
    REG(VIRAGE1_CTRL),
    REG(VIRAGE2_CTRL),
    REG(VIRAGE0_NMS),
    REG(VIRAGE1_NMS),
    REG(VIRAGE2_NMS),
    REG(VIRAGE0_CP),
    REG(VIRAGE1_CP),
    REG(VIRAGE2_CP),

    REG(VIRAGE0_NMS_CRSTO_0),
    REG(VIRAGE0_NMS_CRSTO_1),
    REG(VIRAGE0_NMS_CRM_0),
    REG(VIRAGE0_NMS_CRM_1),
    REG(VIRAGE0_NMS_CRM_2),
    REG(VIRAGE0_NMS_CRM_3),

    REG(VIRAGE1_NMS_CRSTO_0),
    REG(VIRAGE1_NMS_CRSTO_1),
    REG(VIRAGE1_NMS_CRM_0),
    REG(VIRAGE1_NMS_CRM_1),
    REG(VIRAGE1_NMS_CRM_2),
    REG(VIRAGE1_NMS_CRM_3),

    REG(VIRAGE2_NMS_CRSTO_0),
    REG(VIRAGE2_NMS_CRSTO_1),
    REG(VIRAGE2_NMS_CRM_0),
    REG(VIRAGE2_NMS_CRM_1),
    REG(VIRAGE2_NMS_CRM_2),
    REG(VIRAGE2_NMS_CRM_3),
    {0, 0},
};

#define VIRAGE_IO_STORE     0x80000000
#define VIRAGE_IO_PREVMASK (~(VIRAGE_IO_STORE))
struct virage {
    int ctrl;
    int nms;
    int cp;
    int crsto0;
    int crsto1;
    int crm0;
    int crm1;
    int crm2;
    int crm3;
    int size;
    unsigned char* sram;
    unsigned char* data;
    unsigned long iostate; /* state to simulate what bb io code expects */
} virage_state[3];

static void
virage_init(void) {
    int i;
    for(i = 0; i < 3; i++) {
	virage_state[i].nms |= HO2BE_4(VIRAGE_CTRL_NMS_READY);
        virage_state[i].ctrl |= HO2BE_4(VIRAGE_CTRL_NMS_READY);
        virage_state[i].iostate = 0;
    }
    virage_state[0].size = 64; virage_state[0].sram = virage0;
    virage_state[1].size = 64; virage_state[1].sram = virage1;
    virage_state[2].size = 256; virage_state[2].sram = virage2;
    read_data(&virage_state[0].data, virage_state[0].size, getenv("SIMOS_VIRAGE0"));
    read_data(&virage_state[1].data, virage_state[1].size, getenv("SIMOS_VIRAGE1"));
    read_data(&virage_state[2].data, virage_state[2].size, getenv("SIMOS_VIRAGE2"));
    /* emulate a recall from virage2 */
    memcpy(virage_state[2].sram, virage_state[2].data, virage_state[2].size);
    virage_state[2].ctrl |= HO2BE_4(VIRAGE_CTRL_NV_RCREADY);
}

int
virage_handler(int node, int nd, int doff, int type, void* buf) {
    int* p, i = ((doff&0xf0000) >> 16)-8, t;
    struct virage* v = virage_state+i;
    doff &= 0x1fffffff;

    switch(doff) {
    case VIRAGE0_CTRL_REG:
    case VIRAGE1_CTRL_REG:
    case VIRAGE2_CTRL_REG:
	p = &v->ctrl;
        /* quick statefull hack. should check if applies to V0 or V1. */
        if (BDOOR_IS_LOAD(type) &&
            !( (v->iostate&VIRAGE_IO_STORE) && ( 
               (v->iostate&VIRAGE_IO_PREVMASK)==VIRAGE0_NMS_REG || 
               (v->iostate&VIRAGE_IO_PREVMASK)==VIRAGE1_NMS_REG || 
               (v->iostate&VIRAGE_IO_PREVMASK)==VIRAGE2_NMS_REG ) ) )
            *p |= BE2HO_4(VIRAGE_CTRL_NMS_READY);
        else
            *p &= ~BE2HO_4(VIRAGE_CTRL_NMS_READY);
        *p |= BE2HO_4(VIRAGE_CTRL_NMS_PASS);
        v->iostate &= ~VIRAGE_IO_STORE;
	break;

    case VIRAGE0_NMS_REG:
    case VIRAGE1_NMS_REG:
    case VIRAGE2_NMS_REG:
	p = &v->nms;
	if (BDOOR_IS_STORE(type)) {
	    t = BE2HO_4(*(int*)buf);
	    switch((t&VIRAGE_CTRL_NMS_CMD_MASK) >> VIRAGE_CTRL_NMS_CMD_SHIFT) {
	    case NMS_CMD_IDLE:
	    case NMS_CMD_SERIAL_SRAM:
		break;
	    case NMS_CMD_STORE:
                v->iostate |= VIRAGE_IO_STORE;
		memcpy(v->data, v->sram, v->size);
		msync(v->data, v->size, MS_SYNC);
		v->nms |=  HO2BE_4(VIRAGE_CTRL_NMS_READY|VIRAGE_CTRL_NMS_PASS);
		break;
	    case NMS_CMD_RECALL:
		memcpy(v->sram, v->data, v->size);
		v->nms |=  HO2BE_4(VIRAGE_CTRL_NMS_READY);
		break;
	    case NMS_CMD_COMPARE:
	    case NMS_CMD_KEEP:
	    case NMS_CMD_RECALL_AUTO:
		break;
	    }
	goto out;
	}
	break;

    case VIRAGE0_CP_REG:
    case VIRAGE1_CP_REG:
    case VIRAGE2_CP_REG:
	p = &v->cp;
	break;

    case VIRAGE0_NMS_CRSTO_0_REG:
    case VIRAGE1_NMS_CRSTO_0_REG:
    case VIRAGE2_NMS_CRSTO_0_REG:
	p = &v->crsto0;
	break;

    case VIRAGE0_NMS_CRSTO_1_REG:
    case VIRAGE1_NMS_CRSTO_1_REG:
    case VIRAGE2_NMS_CRSTO_1_REG:
	p = &v->crsto1;
	break;

    case VIRAGE0_NMS_CRM_0_REG:
    case VIRAGE1_NMS_CRM_0_REG:
    case VIRAGE2_NMS_CRM_0_REG:
	p = &v->crm0;
	break;

    case VIRAGE0_NMS_CRM_1_REG:
    case VIRAGE1_NMS_CRM_1_REG:
    case VIRAGE2_NMS_CRM_1_REG:
	p = &v->crm1;
	break;

    case VIRAGE0_NMS_CRM_2_REG:
    case VIRAGE1_NMS_CRM_2_REG:
    case VIRAGE2_NMS_CRM_2_REG:
	p = &v->crm2;
	break;

    case VIRAGE0_NMS_CRM_3_REG:
    case VIRAGE1_NMS_CRM_3_REG:
    case VIRAGE2_NMS_CRM_3_REG:
	p = &v->crm3;
	break;
    default:
        fprintf(stderr, "undefined VIRAGE access 0x%x type 0x%x\r\n", doff, type);
	exit(0);
    }
    if (BDOOR_IS_LOAD(type))
    	*(int*)buf = *p;
    else
    	*p = *(int*)buf;
out:
    v->iostate = doff | (v->iostate&VIRAGE_IO_STORE);
    if (!BDOOR_IS_LOAD(type)){
        print_reg(virage_regs, doff, type, *p);
    }
    return 0;
}
#endif