bcptestsi.c 269 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637

/*************************************************************************
 *
 *  File: bcptestsi.c
 *
 *  This file contains test routines for the BCP Serial Interface (SI).
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <time.h>
#include "bcp.h"
#include "os_thread.h"
#include "os_cont.h"
#include "iomap.h"
#include "trace.h"
#include "iotest.h"
#include "bcp_util.h"
#include "bcptest.h"
#define BCP_IPC
#include "simipc.h"
#include "bcptestsi.h"

#define RestrictDump 0

#define DBGOUT                  LogFp

// To get debug outputs use either '-d 0x141'  or '-d0x8101' on the iosim cmd line
#define DSI                     (0x00008000|DLOG)

#define SI_DMA_XFER_BYTES       32
#define DEF_DATA_TO_START_DMA   PIF_RAM_START
#define DEF_XZ_TO_START_DMA     0
#define STD_GUARD_BAND_BYTES    16
#define GUARD_BAND_INC_PAT      0x01010101
#define JCTRL_DELAY_AFTER_DONE  128000
#define MIN_JCRST_DURATION      110000

// some controller defines can be found in os_cont.h

#define CTRL_JSRST_BUTTONS      (START_BUTTON | L_TRIG | R_TRIG)
#define CTRL_JSRST_BIT          (0x0080)
#define CTRL_BUTTON_MASK        (0xFF3F)
#define LCTRL_TYPE_STATUS       (ntohl(CONT_TYPE_NORMAL))
#define CTRL_SLAVE_RX_FOR_XMIT  (1)

#define CTRL_ERR_NO_RESPONSE    0x10
#define CTRL_ERR_REQUEST        0x08
#define CTRL_ERR_FRAME          0x04
#define CTRL_ERR_COLLISION      0x02
#define CTRL_ERR_CTLR_RESET     0x01

static int no_random_jsrst;  // Set true to prevent JSRST in buttons()

static int jsrst_button_components[] = {
    START_BUTTON,
    L_TRIG,
    R_TRIG };



#define LC ctrlr[0]
#define J1 ctrlr[1]
#define J2 ctrlr[2]
#define J3 ctrlr[3]

/* SET and CLEARED can be used with SiTimeout() */
#define CLEARED                 1
#define SET                     0


// DMA timeout in nanoseconds
#define DEFAULT_DMA_TIMEOUT     500000
#define RSP_RND_DMA_TIMEOUT     2000000
#define W4MC_DMA_TIMEOUT        DEFAULT_DMA_TIMEOUT
#define DMA_MAX_WRITE_ns        10000

// Use RQSC(c) to make the compiler require that
// a macro is terminated with a semicolon.  It's use
// can avoid strange bugs for some macros when a
// semicolon is left out or added when it shouldn't be.
#define RQSC( code )    do { code } while (0)

static int stop_tests_on_err =  0;
static int stop_test_on_err  =  0;
#define INC_ON_ERR(ret,count)   RQSC( if(ret==-1) {++count; if(stop_test_on_err) return ret; } else {ret = 0;} )

#define NUM_ELEMENTS(a)         ((int)(sizeof(a)/sizeof(a[0])))

#define MAX_DESCRIPTION_SIZE    (512)


typedef enum { Dir_From =1,
               Dir_To  = 2  } Direction;


// Types of failures that can be specified as expected in function calls
typedef enum {
    ExpectedFail_None                       =  0,
    ExpectedFail_ctrl_0_tx_rx_buf           =  1 <<  0,
    ExpectedFail_ctrl_1_tx_rx_buf           =  1 <<  1,
    ExpectedFail_ctrl_2_tx_rx_buf           =  1 <<  2,
    ExpectedFail_ctrl_3_tx_rx_buf           =  1 <<  3,
    ExpectedFail_all_ctrl_tx_rx_buf         =  0xF,
    ExpectedFail_ctrl_0_tx_rx_buf_or_not    =  1 <<  4,
    ExpectedFail_ctrl_1_tx_rx_buf_or_not    =  1 <<  5,
    ExpectedFail_ctrl_2_tx_rx_buf_or_not    =  1 <<  6,
    ExpectedFail_ctrl_3_tx_rx_buf_or_not    =  1 <<  7,
    ExpectedFail_all_ctrl_tx_rx_buf_or_not  =  0xF0,
    ExpectedFail_ctrl_0_any_fail            =  1 <<  8,
    ExpectedFail_ctrl_1_any_fail            =  1 <<  9,
    ExpectedFail_ctrl_2_any_fail            =  1 << 10,
    ExpectedFail_ctrl_3_any_fail            =  1 << 11,
    ExpectedFail_all_ctrl_fail              =  0xF00,
    ExpectedFail_any_ctrl_fail              =  1 << 12,
    ExpectedFail_DmaTimeout                 =  1 << 13,
    ExpectedFail_DmaError                   =  1 << 14,
    ExpectedFail_No_int_l_AfterDma          =  1 << 15  }  ExpectedFailure;

// Types of failures or failure modes that can be specified for test cases
// Note: The case of unsupported cmd type for lctrl is done by specifying
//       CtrlJcUnsupCmd when creating the cmd.  All in range cmd types
//       are valid for jc ctrlrs.
typedef enum {
    ForceFail_None                      = 0,
    ForceFail_Random                    = 1,  // force a random failure
    ForceFail_Occasionally              = 2,  // occasionally force a random failure

    ForceFail_StartOfFailures           = 3,  // real fail types below here
    ForceFail_NoResponse                = 4,
    ForceFail_Collision                 = 5,
    ForceFail_Frame                     = 6,
    ForceFail_tx_TooBigForAnyCmdType    = 7,
    ForceFail_tx_InvalidForCmdType      = 8,
    ForceFail_rx_TooBigForAnyCmdType    = 9,
    ForceFail_rx_Zero                   = 10,
    ForceFail_rx_InvalidForCmdType      = 11,
    ForceFail_ClearSiIntMask            = 12,
    ForceFail_EndOfFailures             = 13  } ForceFail;

static char *force_fail_name[] = {
    "None",
    "Random",
    "Occasionally",

    "StartOfFailures",
    "NoResponse",
    "Collision",
    "Frame",
    "tx_TooBigForAnyCmdType",
    "tx_InvalidForCmdType",
    "rx_TooBigForAnyCmdType",
    "rx_Zero",
    "rx_InvalidForCmdType",
    "ClearSiIntMask",
    "EndOfFailures"
};

// ForceFail_None parameter values
#define JChannel_Resp_Rand      (1<<0)
#define StartWithXs             (1<<1)


typedef enum { ToStartDmaUse_Random_IO_WRITE,
               ToStartDmaUse_AllBitsX,
               ToStartDmaUse_reg_value       } DmaStartOption;


typedef enum { LcButWait_Compute = 0,
               LcButWait_UseDelayBeforeRqst,
               LcButWait_UseDontRqstBefore,
               LcButWait_None
               
} LcButWait;


typedef struct {
    unsigned long long start;
    unsigned long long end;
    unsigned int       duration;
    unsigned int       limit;       } SiTimeoutInfo;

typedef struct {
    int block_code;
    int tx_size;
    int error;
    int rx_size;
    int cmd;
    int tx_rx_buf;      } SiCtrlBufParams;



typedef struct {

    // See comments in SiSetupDmaParam()

    int use_dram_addr;
    unsigned int dram_addr;

    int use_fill_value;
    unsigned int fill_value;

    unsigned int guard_band_bytes;

    ExpectedFailure    expected_failure;

    DmaStartOption     start_option;
    int reg_data;      // value to write to the register to start the dma
    int reg_xz;        // If xz_part is non-zero, an extended write is done to start the dma

    int                use_timeout;
    SiTimeoutInfo      timeout;

    SiCtrlBufParams ctrlr[4]; // 0 is lc, 1 is j1, 2 is j2, 3 is j3

} SiDmaParam;



typedef struct {

    // See comments after this definition and in
    // SiSetupDmaTestParam() and SiSetupDmaParam()

    char *testname;
    char *description;
    int   test_case_count;

    SiDmaParam  w;  // dma write parameters
    SiDmaParam  r;  // dma read  parameters

    unsigned int delayAfterDone;

    // LC button parameters
    LcButWait           lc_but_wait;  // See comments below
    int                 offset_from_computed_rqst_time;
    int                 button_periods_to_delay;
    unsigned int        delay_before_rqst;
    // LC button computed values
    unsigned long long  dont_rqst_before;
    unsigned long long  min_time_till_readable;
    unsigned long long  max_time_till_readable;
    unsigned int        button_period;

    SiCtrlBufParams result[4]; // 0 is lc, 1 is j1, 2 is j2, 3 is j3

} SiDmaTestParam;

// lc_but_wait
//
// Need to wait till lc button values polled before
// requesting the values be put in the SI DMA buffer.
// Due to deglicthing, it takes 3 to 4 sample periods
// before a button change will be seen in the DMA.
// lc_but_wait can be set to specify to either
//   LcButWait_Compute
//      Compute "dont_rqst_before" based on when
//     the backdoor is used to set the lc values
//     and the jc_div/but_rate settings.
//     You can specify the number of button sample
//     periods to delay before initating a DMA request
//     by setting button_periods_to_delay to a non-zero
//     value.  Leaving or setting button_periods_to_delay
//     to zero, results in the default of 4 button_periods.
//     Also, offset_from_computed_rqst_time will be added
//     to the computed dont_rqst_before. The offset
//     is normally zero, but can be set to a positive
//     or negative value.
//   LcButWait_UseDelayBeforeRqst
//      Set dont_rqst_before to the time the
//      button values are set via the backdoor plus
//      delay_before_rqst.
//   LcButWait_UseDontRqstBefore
//      Use the current value of dont_rqst_before
//     (set before the test routines are called),
//   LcButWait_None
//      Set "dont_rqst_before" to 0 to cause no wait,
// The default lc_but_value after memset to 0 is:
//      lc_but_wait = LcButWait_COMPUTE
// If an lc button request is not done, lc_but_wait
// can be left as LcButWait_Compute or set to LcButWait_None
// SiSetupDmaTestParm will preserve lc_but_wait and
// and set dont_rqst_before and delay_before_rqst to 0 for
// LcButWait_Compute and LcButWait_None.
// SiSetupDmaTestParm will preserve dont_rqst_before if
// lc_but_wait is LcButWait_UseDontRqstBefore, and
// preseve delay_before_rqst for LcButWait_UseDelayBeforeRqst.
// The values of button_periods_to_delay and
// offset_from_computed_rqst_time are always preserved,
// but only used when lc_but_wait is LcButWait_Compute.
// SiSetupButtonTest will compute values as needed.
// Computed values are left 0 if an lc button request isn't done.
// If you set the config reg but_rate field to 0 you will
// get a button poll every jc_clk and you can afford to
// leave lc_but_wait as LcButWait_Compute.  The default
// jc_div of 31 and but_rate 0 results in button sampling
// every 512 nanosec.  The max jc_div of 127 with a
// but_rate of 0 results in button sampling every 2 microsec.
// Remember, it takes 3 to 4 samples to deglitch before the
// value can be seen in the dma.




typedef enum {
    CtrlQueryStatus  = 0,
    CtrlQueryButtons = 1,
    CtrlRead         = 2,
    CtrlWrite        = 3,
    CtrlReset        = 255,
    CtrlNoXmitStat   = 256,
    CtrlNoXmitButt   = 257,
    CtrlNoXmitRead   = 258,
    CtrlNoXmitWrit   = 259,
    CtrlNoXmitRset   = 511,
    CtrlNoXmitUsup   = 512,
    CtrlNoXmitRand   = 513,
    CtrlJcUnsupCmd   = 514,
    CtrlRandomCmd    = 515,  } CtrlCmdCode;


typedef struct {
     CtrlCmdCode code;
     char*       name;
     int         tx_size;
     int         rx_size;    } CmdInfo;


static const CmdInfo supported_cmd[] = {

    {CtrlQueryStatus,  "CtrlQueryStatus",  1,  3},
    {CtrlQueryButtons, "CtrlQueryButtons", 1,  4},
    {CtrlRead,         "CtrlRead",         3, 33},
    {CtrlWrite,        "CtrlWrite",        35, 1},
    {CtrlReset,        "CtrlReset",        1,  3}

};


static const CmdInfo no_xmit_cmd[] = {

    {CtrlNoXmitStat,  "CtrlNoXmitStat"  },
    {CtrlNoXmitButt,  "CtrlNoXmitButt"  },
    {CtrlNoXmitRead,  "CtrlNoXmitRead"  },
    {CtrlNoXmitWrit,  "CtrlNoXmitWrite" },
    {CtrlNoXmitRset,  "CtrlNoXmitRset"  },
    {CtrlNoXmitUsup,  "CtrlNoXmitUsup"  },
    {CtrlNoXmitRand,  "CtrlNoXmitRand"  }

};



#define LCTRL_MAX_X         (127)
#define LCTRL_MAX_Y         (127)
#define LCTRL_MIN_X         (-128)
#define LCTRL_MIN_Y         (-128)

#define LCTRL_SOMEJITTER    (0xFF)

typedef struct {

    unsigned long long  bd_write_time;

    int                 ns_jsmove_1;
    int                 tPulse;
    int                 tGlitch;
    int                 jitter;

    int                 inmotion_x;
    int                 last_x;
    int                 last_x_known;
    int                 target_x;
    unsigned long long  keep_x_idle;
    unsigned long long  xmove_start;
    unsigned int        xmove_timeout;

    int                 inmotion_y;
    int                 last_y;
    int                 last_y_known;
    int                 target_y;
    unsigned long long  keep_y_idle;
    unsigned long long  ymove_start;
    unsigned int        ymove_timeout;  }   Lctrl_State;


static Lctrl_State lctrl = { 0, 0, 2000, 800, 0 };


// dedicated_env non-zero means the env is dedicated to the SI tests.
static int dedicated_env = 1;
// random_env non-zero means the test is being run under the random test harness.
static int random_env    = 0;


#define SI_MAX_DMA_MEM64_SIZE         (0x02000000) // 32MB
static unsigned int mem_info;
static unsigned int mem_size;
static unsigned int si_ltd_mem_start;   // 0 unless changed by SiTestRandEnv
static unsigned int si_ltd_mem_size;    // ditto
static unsigned int si_dma_mem64_size;  // init by SiDefaults() based on mem_size
static unsigned int si_dma_addr64_top;  // ditto
static unsigned int si_dma_addr64_mask; // ditto
static unsigned int si_dma_mem36_size;  // ditto
static unsigned int si_dma_addr36_top;  // ditto
static unsigned int si_dma_addr36_mask; // ditto


static const char* ctrlr_name[] = { "lc", "j1", "j2", "j3" };

static int random_seed;

static int si_log_fail_count;

static int si_use_io_read_io_write;

static int use_rsp_echo[4] = { 0, 1, 1, 1 };

static int use_rsp_rand[4];
static int use_rsp_rand_any;  // true if use_rsp_rand[1], use_rsp_rand[2], or use_rsp_rand[3] is true

static  unsigned int dsi = DSI;

static int doing_ctrl_sim_init;

static unsigned int sysclk_period;  // in ps, set by SiDefaults

static unsigned long long lctrl_but_sam_sync_time;

#define  MJCTRL_START_CMD (1<<0)
#define  MJCTRL_JCRESET   (1<<1)
#define  DEF_SmModelJCResetDuration   150000
#define  DEF_SmJCResetDelay           (DEF_SmModelJCResetDuration+10000)
//#define  DEF_SmJCResetDelay           (DEF_SmModelJCResetDuration+64000+32000+50000)
#define  DEF_SmJCResetWithCmdDelay    DEF_SmJCResetDelay
#define  DEF_SmMJCResetDurCmdDelay    115000
#define  DEF_SmJCResetDurCmdDelay      15000
#define  DEF_SmCmdFrameErr            (0x20 | 0x2)
#define  DEF_SmRspCollision           (0x08 | 0x2)

static int isSlaveMode;
static int isUseMJCTRL;
static int isCoQuerySlaveButtons;
static int isSmJCResetWithCmd;
static int SmJCResetWithCmdDelay;
static int isSmJCResetDurCmd;
static int SmJCResetDurCmdDelay;
static int isSmJCResetBeforeRcv;
static int isSmPollTilJCResetDone;
static int isSmCheckRcvNoRqstCmd;
static int isSmTruncCmd;
static int isSmRspCollision;
static int isSmCmdFrameErr;
static int SmCmdFrameErr;   // bit 5 enables, bits 4-0 indicate when
static int SmRspCollision;  // bit 3 enables, bits 2-1 indicate when
SiDmaTestParam dma_slave_transactions;

static int jcrst_duration;

static u8  read_cmd_rcv_data  [4][32]; // data recvd by read cmd per ctrlr
static u8  read_cmd_xmit_data [4][ 3]; // data xmited by read cmd per ctrlr
static u8  write_cmd_data     [4][ 5]; // data xmited by write cmd per ctrlr


static int
SiSetAsSlave();

static void
SiSetupDmaTestParam(SiDmaTestParam *dma);

static int
SiLctrlJsxyMoveAndVerify (SiDmaTestParam *dma, int first_buttons, int count_x, int count_y, int jc_no_xmit);





static void
logMsg(const char *msg)
{
    static int  idval;
    char lid[64];

    snprintf(lid, sizeof lid, "%s: %d", msg, ++idval);
    displayMsg(lid);
    fprintf(DBGOUT, "\n##    %s", lid);
}


static char*
SiResult(int ret, char result[32])
{
    char *status;
    char  buf[24];

    if (ret == 0) {
        status = PASS_STR;
    } else if (ret == -1) {
        status = FAIL_STR;
        si_log_fail_count++;
    } else if (ret == 1) {
        status = "Expected";
    } else {
        snprintf (buf, sizeof buf, "%d", ret);
        status = buf;
        si_log_fail_count++;
    }
    sprintf (result, "  -> %s", status);
    return result;
}


static int
SiLogResult(int ret, const char* test, const char* op, int a1, int a2, int a3, int a4)
{
    char  buf[32];
    unsigned long long now;
    SIM_TIME(&now);
    logMsg(test);
    fprintf(LogFp, "\n  %s: %8llu: %s %08x, %08x, %08x, %08x%s", test, now, op, a1, a2, a3, a4, SiResult(ret, buf));
    return ret;
}


static int
SiLogRes(int ret, const char* test, const char* str1, const char* str2)
{
    char  buf[32];
    unsigned long long now;
    SIM_TIME(&now);
    logMsg(test);
    fprintf(LogFp, "\n  %s: %8llu: %s%s%s", test, now, str1, str2, SiResult(ret, buf));
    return ret;
}


static char *
durstr(int secs)
{
    static char buf[64];
    int hrs = secs/3600;
    int min = (secs - hrs*3600)/60;
    int sec = secs - hrs*3600 - min*60;

    if(hrs)
        snprintf(buf, sizeof buf, "%d hrs %d min %d sec", hrs, min, sec);
    else if(min)
        snprintf(buf, sizeof buf, "%d min %d sec", min, sec);
    else
        snprintf(buf, sizeof buf, "%d sec", sec);
    return buf;
}


static int
SiWait(unsigned int nanosecs)
{
    unsigned long long now;
    unsigned long long end;
    int                nclks;

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiWait:  Wait for %u nanosecs ", nanosecs));

    if (nanosecs == 0)
        return 0;

    if (random_env) {
        SIM_TIME(&now);
        end = now + nanosecs;
        while (end > now) {
            bcp_stall(1);
            SIM_TIME(&now);
        }
    } else {
        nclks = (((unsigned long long)nanosecs * 1000) + sysclk_period/2) / sysclk_period;
        bcp_stall( nclks );
    }

    return 0;
}



static int
SiWaitTill(unsigned long long sim_time)
{
    unsigned long long now;

    if (sim_time == 0)
        return 0;

    SIM_TIME(&now);

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiWaitTill:  Wait till %llu sim time, it is now %llu", sim_time, now));

    if (random_env) while (sim_time > now) {
        bcp_stall(1);
        SIM_TIME(&now);
    } else if (sim_time > now) {
        SiWait (sim_time - now);
        SIM_TIME(&now);
    }

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiWaitTill:  Done waiting for %llu sim time: now: %llu", sim_time, now));
    return 0;
}



static int
SiCheckInterrupt(unsigned int intrBit, unsigned int *stat)
{
    unsigned int ret;
    ret = (vu_int )(IO_READ(MI_INTR_REG));
    if(stat) *stat = ret;
    return(ret & intrBit);
}

static void
SiSetInterruptMask(int set)
{
    IO_WRITE(MI_INTR_MASK_REG, set ? MI_INTR_MASK_SET_SI : MI_INTR_MASK_CLR_SI);
}


static unsigned int
getJcPeriod(unsigned int config, unsigned int *returned_jc_div)
{
    // jc_clk  = sysclk/(1+jc_div)
    // jc_per  = sys_per*(1+jc_div)

    unsigned int jc_div, jc_per;
    jc_div   = (config & SI_CONFIG_JC_DIV_MASK)  >>  SI_CONFIG_JC_DIV_SHIFT;
    // sysclk_period is in ps
    jc_per   = (((unsigned long long)sysclk_period)*(1+jc_div) + 500)/1000;
    if (returned_jc_div)
        *returned_jc_div = jc_div;
    return jc_per;
}




static unsigned int
SiAlignedDmaBufAddr(unsigned int dram_addr)
{
    // Make sure 8 byte aligned and not outside legal mem
    // Does not avoid illegal crossovers
    // See isValidSiDmaBufferAddr() as well.
    unsigned int buf_addr;
    unsigned int top = (dram_addr < DDRRAM64_START) ? si_dma_addr36_top : si_dma_addr64_top;
    if (si_ltd_mem_size)
        top = si_ltd_mem_start + si_ltd_mem_size;
    buf_addr = dram_addr & 0xFFFFFFF8;
    if ((buf_addr + SI_DMA_XFER_BYTES) >= top)
        buf_addr = (top - SI_DMA_XFER_BYTES);

    return buf_addr;
}






static int
SiLowerGuardBandBytes(unsigned int dram_addr, unsigned int guard_band_bytes)
{
    unsigned int offset = (dram_addr < DDRRAM64_START) ?
                                 dram_addr : dram_addr-DDRRAM64_START;
    return (offset > guard_band_bytes) ?  guard_band_bytes : offset;
}



static int
SiUpperGuardBandBytes(unsigned int dram_addr, unsigned int guard_band_bytes)
{
    unsigned int upgb_addr = SiAlignedDmaBufAddr(dram_addr) + SI_DMA_XFER_BYTES;
    unsigned int top = (dram_addr < DDRRAM64_START) ? si_dma_addr36_top : si_dma_addr64_top;
    if (si_ltd_mem_size)
        top = si_ltd_mem_start + si_ltd_mem_size;
    return ((top - upgb_addr) > guard_band_bytes) ?  guard_band_bytes : (top - upgb_addr);
}


static unsigned int
ranbits(int bit_position, int num_bits)
{
    return (random() & ~(0xFFFFFFFF<<(num_bits%33))) << bit_position;
}


static unsigned int
isValidSiDmaBufferAddr(unsigned int addr)
{
    // assume terminology that page is
    // 1MB for 36 bit mode and 2MB for 64 bit mode
    // DMA can't crose page boundary
    #define MB  (1024*1024)
    int mode, page_size, page_boundary_offset;
    unsigned int top, start = 0;
    int ltd = si_ltd_mem_size ? 1:0;

    if(ltd) {
        mode  = 1;
        start = si_ltd_mem_start;
        top   = start + si_ltd_mem_size;
    } else if(addr < DDRRAM64_START) {
        mode  = 1;
        top   = si_dma_addr36_top;
    } else {
        mode  = 2;
        top   = si_dma_addr64_top;
    }
    page_size = MB*mode;
    page_boundary_offset = addr % page_size;

    return     (addr >= start)
           && !(addr & 0x7)
           &&  ((page_boundary_offset + SI_DMA_XFER_BYTES) <= page_size)
           &&  ((addr                 + SI_DMA_XFER_BYTES) <= top);
}


static unsigned int
bufAddr()
{
    unsigned addr;
    int      m64 = 0;  // let 1 out of 5 random addrs be 64 bit mode
    int      ltd = si_ltd_mem_size ? 1:0;

    if ( !(random()%5) )
        m64 = 1;

    do {
        if (ltd)
            addr =  random() % si_ltd_mem_size   + si_ltd_mem_start;
        else if (m64)
            addr =  random() % si_dma_mem64_size + DDRRAM64_START;
        else
            addr =  random() % si_dma_mem36_size;
        addr &= ~7;
    } while (!isValidSiDmaBufferAddr(addr));

    return addr;
}

static int
buttons()
{
    static int since_jsrst;
    int b = random() & CTRL_BUTTON_MASK;
    if ((b & CTRL_JSRST_BUTTONS) == CTRL_JSRST_BUTTONS) {
        if ( since_jsrst < 20  || no_random_jsrst) {
            ++ since_jsrst;
            b = b ^ jsrst_button_components[random() % NUM_ELEMENTS(jsrst_button_components)];
        } else
            since_jsrst = 0;
    } else {
        ++ since_jsrst;
    }
    return  b;
}

static int
jcount()
{
    return (random() % 256) - 128;
}

static int
type_L()
{
    return random() & 0xFF;
}

static int
type_H()
{
    return random() & 0xFF;
}

static int
cstatus()
{
    return random() & 0xFF;
}

static u16
read_addr()
{
    return random() & 0xFFFF;
}

static u8*
read_data()
{
    static u8 d[32];
    int i;
    for(i=0; i<32; ++i)
        d[i] = random();
    return d;
}

static u16
write_addr()
{
    return random() & 0xFFFF;
}

static u8*
write_data()
{
    static u8 d[5];
    u16 addr = write_addr();
    d[0] = 0; // not really used.  cmd on model side
    d[1] = (addr>>8)&0x00FF;
    d[2] =  addr    &0x00FF;
    d[3] =  random();
    d[4] =  random();
    return d;
}

static int
buttonRate()
{
    return random() % 64;
}

static void
setLctrlButSamEna(int state)
{
    IO_WRITE( SI_CONFIG_REG,
                ( (IO_READ(SI_CONFIG_REG) & ~SI_CONFIG_BUT_ENA)
                     | ((state?1:0) << SI_CONFIG_BUT_ENA_SHIFT)
                ));
}

static void
setLctrlButRate(int but_rate)
{
    // Disable button sampling, set new but_rat, enable button_sampling
    setLctrlButSamEna(FALSE);
    IO_WRITE( SI_CONFIG_REG,
                ( (IO_READ(SI_CONFIG_REG) & ~SI_CONFIG_BUT_RATE_MASK)
                     | (but_rate << SI_CONFIG_BUT_RATE_SHIFT)
                ));
    setLctrlButSamEna(TRUE);
    SIM_TIME(&lctrl_but_sam_sync_time);
    _TRACE(dsi, fprintf(DBGOUT, "\n\tsetLctrlButRate:  lctrl but rate change time:  %llu", lctrl_but_sam_sync_time));
}

#if 0  /* currently not used */

static int
joyChannelDivider()
{
    return random() % 128;
}


static void
SiSet_jc_div(int jc_div)
{
    IO_WRITE( SI_CONFIG_REG,
                ( (IO_READ(SI_CONFIG_REG) & ~SI_CONFIG_JC_DIV_MASK)
                     | (jc_div << SI_CONFIG_JC_DIV_SHIFT)
                ));
}

#endif /* currently not used */


static int
randomFailure(int ctrlr, SiDmaTestParam *dma)
{
    ForceFail fail;

    do {
        fail = (ForceFail_StartOfFailures + 1)
           + (random() % (ForceFail_EndOfFailures - ForceFail_StartOfFailures - 1));

        if (   (ctrlr == 0 && (   fail == ForceFail_NoResponse
                               || fail == ForceFail_Collision
                               || fail == ForceFail_Frame ))
            || (    fail == ForceFail_tx_InvalidForCmdType
                 && dma->w.ctrlr[ctrlr].tx_size == 0)
            || fail == ForceFail_ClearSiIntMask )

            fail = ForceFail_None;

    } while ( fail == ForceFail_None );

    return fail;
}

static int
isSupportedCmd(CtrlCmdCode cmd)
{
    int i;
    for (i = 0;  i < NUM_ELEMENTS(supported_cmd);  i++) {
        if ( cmd == supported_cmd[i].code )
            return 1;
    }
    return 0;
}

static int
isValidUnsupCmd(CtrlCmdCode cmd)
{
    return (cmd > 3 && cmd < 255 && !isSupportedCmd(cmd)) ? 1: 0;
}

static const char*
cmdName(CtrlCmdCode cmd)
{
    static char unsupported[] = "Unsupported cmd type";
    int i;
    for (i = 0;  i < NUM_ELEMENTS(supported_cmd);  ++i)
        if ( cmd == supported_cmd[i].code ) 
            return supported_cmd[i].name;
    for (i = 0;  i < NUM_ELEMENTS(no_xmit_cmd);  ++i)
        if ( cmd == no_xmit_cmd[i].code )
            return no_xmit_cmd[i].name;
    return unsupported;
}


static int
cmdRxSize(int cmd)
{
    int i;
    for (i = 0;  i < NUM_ELEMENTS(supported_cmd);  ++i){
        if ( cmd == supported_cmd[i].code )
            return supported_cmd[i].rx_size;
    }
    if ( cmd < 256 )
        return (cmd & 3) + 1;
    return 0;
}


static int
cmdTxSize(int cmd)
{
    int i;
    for (i = 0;  i < NUM_ELEMENTS(supported_cmd);  ++i) {
        if ( cmd == supported_cmd[i].code )
            return supported_cmd[i].tx_size;
    }
    if ( cmd < 256 )
        return (cmd & 3) + 2;
    return 0;
}

#if 0 //These are not currently needed
static int
cmdRxInvalidSize(int cmd)
{
    // For valid cmds, returns random num from
    // 1 to 63 that is nod valid size for cmd
    // Returns 0 for cmd > 255
    int i, v;
    if(cmd>255)
        return 0;
    v = cmdRxSize(cmd);
    do{r=1+random()%(64-1)}while(r==v);
    return r;
}


static int
cmdTxInvalidSize(int cmd)
{
    // For valid cmds, returns random num from
    // 1 to 63 that is nod valid size for cmd
    // Returns 0 for cmd > 255
    int i, v;
    if(cmd>255)
        return 0;
    v = cmdTxSize(cmd);
    do{r=1+random()%(64-1)}while(r==v);
    return r;
}
#endif

static CtrlCmdCode
supportedCmd()
{
    int cmd;
    do {
        cmd = supported_cmd[ random() % NUM_ELEMENTS(supported_cmd) ].code;
    } while (cmd==CtrlRead || cmd==CtrlWrite);
    return cmd;
}

static int
unsupportedCmd()
{
    int cmd;
    do {
        cmd = 4 + random() % 251; /* 4 to 254 */
    } while (isSupportedCmd((CtrlCmdCode)cmd));
    return cmd;
}



static int
mjctrl_cmd(CtrlCmdCode cmd)
{
    int result;

    switch (cmd) {
        case CtrlQueryStatus:
            result = MJCTRL_CMD0;
            break;
        case CtrlQueryButtons:
            result = MJCTRL_CMD1;
            break;
        case CtrlReset:
            result = MJCTRL_CMD255;
            break;
        default:
            if(cmd<255)
                result=cmd;
            else
                result=MJCTRL_CMD0;
            break;
    }
    return result;
}


static void
dump (char* description_part_1, char* description_part_2, int dram_addr, int bytes)
{
    int da, end;
    fprintf(DBGOUT, "\n\t%s%s", description_part_1, description_part_2);
    // Make sure it is 4 byte aligned
    for (da=(dram_addr & 0xFFFFFFFC), end=dram_addr+bytes;  da<end; da+=4)
         fprintf(DBGOUT, "\n\t\t%08x:\t%08x", da, IO_READ(da));
}


static int
shiftButtons(int buttons)
{
    // buttons is a 16 bit mask composed of bytes buttons_L and buttons_H
    // buttons  = (buttons_L << 8)  |  buttons_H
    // bit 6 and 7 of buttons_H are read only.  bit 6 is always 0, bit 7 is JSRST
    // This routine does not treat bits 6 and 7 as special
    if ( (buttons <<= 1) > 0x0000FFFF ) {
        buttons = (buttons & 0x0000FFFF) | ((buttons & 0xFFFF0000) >> 16);
    }
    return buttons;
}



static void
SiResetLctrlJsXyStateData()
{
    lctrl.last_x_known  = lctrl.last_y_known  = FALSE;
    lctrl.target_x      = lctrl.target_y      = 0;
    lctrl.inmotion_x    = lctrl.inmotion_y    = TRUE;
    lctrl.keep_x_idle   = lctrl.keep_y_idle   = 0;
    lctrl.xmove_timeout = lctrl.ymove_timeout = 0;
    lctrl.xmove_start   = lctrl.ymove_start   = 0;
    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiResetLctrlJsXyStateData:  reset lctrl x,y state data"));
}


static void
cycle_ctrl_enable(int ctrlr)
{
    bd_si_ctrl_setup(ctrlr, CTRL_ENALE, 0, 0);
    SiWait(10000);
    bd_si_ctrl_setup(ctrlr, CTRL_ENALE, 1, 0);
}



static int
SiInitCtrlSim (int lc, int j1, int j2, int j3)
{
    int ret = 0, ret2 = 0;
    unsigned int i, config, lwait =0 , jwait = 0;
    int jc[] = { 0, j1, j2, j3 };
    static char rn[] = "SiInitCtrlSim";

    if (doing_ctrl_sim_init) {
        _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  called recursively", rn));
        return -1;
    }

    doing_ctrl_sim_init = 1;

    if(isSlaveMode) {
        lc=1, jc[1]=j1=1, jc[2]=j2=1, jc[3]=j3=1;
    }

    bd_si_ctrl_setup(MJCTRL, MJCTRL_ENALE, 0, 0);

    if (lc) {
        _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  reset lc sim to default values", rn));
        bd_si_ctrl_setup(0, LCTRL_JITTER , lctrl.jitter, 0);
        SiWait(lctrl.ns_jsmove_1*2);
        lctrl.ns_jsmove_1   = lctrl.tPulse + lctrl.jitter;
        SiResetLctrlJsXyStateData();
        lwait = 1;
    }

    logMsg(rn);
    for (i=1; i<4; i++) {
        if (jc[i]) {
            _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  reset jc %d sim to default values", rn, i));
            bd_si_ctrl_setup(i, CTRL_ENALE    , 0, 0);
            jwait = 1;
        }
    }

    if (lwait) {
        SiDmaTestParam dma;
        memset(&dma, 0, sizeof(SiDmaTestParam));
        dma.testname = rn;
        dma.test_case_count ++;
        dma.description = "JSRST and wait for lctrl x,y == 0,0";
        SiSetupDmaTestParam(&dma);
        ret = SiLctrlJsxyMoveAndVerify(&dma, CTRL_JSRST_BUTTONS, 0, 0, 1);
        _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  Done waiting for lctrl x,y == 0,0 after JSRST", rn));
    } else if (jwait) {
        config = IO_READ(SI_CONFIG_REG);
        SiWait( getJcPeriod(config, NULL) * (use_rsp_rand_any ? 24:8) );
    }

    logMsg(rn);
    for (i=1; i<4; i++) {
        if (jc[i]) {
            int e;
            bd_si_ctrl_setup(i, CTRL_DIV      , 9, 0);
            bd_si_ctrl_setup(i, CTRL_TYPE_L   , 2, 0);
            bd_si_ctrl_setup(i, CTRL_TYPE_H   , 0, 0);
            bd_si_ctrl_setup(i, CTRL_STATUS   , 0, 0);
            bd_si_ctrl_setup(i, CTRL_BUTTON   , 0, 0);
            bd_si_ctrl_setup(i, CTRL_X        , 0, 0);
            bd_si_ctrl_setup(i, CTRL_Y        , 0, 0);
            if(isSlaveMode)
                bd_si_ctrl_setup(i, CTRL_RSP_ECHO , 0, 0);
            else
                bd_si_ctrl_setup(i, CTRL_RSP_ECHO , use_rsp_echo[i], 0);
            bd_si_ctrl_setup(i, CTRL_RSP_RAND , use_rsp_rand[i], 0);
            bd_si_ctrl_setup(i, CTRL_COLLISION, 0, 0);
            bd_si_ctrl_setup(i, CTRL_FRAMEERR , 0, 0);
            bd_si_ctrl_setup(i, CTRL_GLITCH_DETECT, 1, 0);
         // bd_si_ctrl_setup(i, CTRL_RESET,     0, 0);
            bd_si_ctrl_setup(i, CTRL_MASTER,     0, 0);
            e = (!isSlaveMode || !i) ? 1:0;
            bd_si_ctrl_setup(i, CTRL_ENALE    , e, 0);
        }
    }

    if(isSlaveMode) ret2 = SiSetAsSlave();

    doing_ctrl_sim_init = 0;

    return ret ? ret : ret2;
}


static char*
SiRegInfo (char buf[128],
           unsigned int *status,
           unsigned int *config,
           unsigned int *mi_intr,
           unsigned int *si_intr,
           unsigned int *ints)
{
    unsigned long long now;
    SIM_TIME(&now);
    *status = IO_READ(SI_STATUS_REG);
    *config = IO_READ(SI_CONFIG_REG);
    *si_intr = SiCheckInterrupt(MI_INTR_SI, mi_intr);
    *ints = CHECK_INTERRUPT;
    snprintf(buf, 128, "at %llu: status %08x  config/ctrl %08x  ints %08x  mi_intr %08x",
                 now, *status, *config, *ints, *mi_intr);
    return buf;
}




static int
SiTimeout(int addr, int bits, int cleared, SiTimeoutInfo *t)
{
    /* Poll a register status until the bits are either set or cleared
     * Return err if timeout
     */

    int stat;
    // t->start, t->end, and t->timeout are in nanoseconds;

    SIM_TIME(&t->start);
    t->end = t->start;
    t->duration = 0;
    while (1) {
        stat = IO_READ(SI_STATUS_REG);

        if (cleared) {
            if (!(stat & bits)) break;
        } else {
            if (stat & bits) break;
        }

        SIM_TIME(&t->end);
        t->duration = (unsigned int) (t->end - t->start);
        if ((t->duration) >= t->limit) {
            _TRACE(dsi,
                fprintf(DBGOUT, "\n\tsiTimeoutStatus: Polling Status timeout.  "
                                "Addr 0x%08x,  bits 0x%08x, cleared 0x%08x, "
                                "Status = 0x%08x, start %llu, end %llu, duration %u, limit %u",
                                addr, bits, cleared, stat, t->start, t->end, t->duration, t->limit));
                return 1;
        }
    }
    _TRACE(DSTATUS,
        fprintf(DBGOUT, "\n\tsiTimeoutStatus: Success.  "
                        "Addr 0x%08x,  bits 0x%08x, cleared 0x%08x, "
                        "Status = 0x%08x, start %llu, end %llu, duration %u, limit %u",
                        addr, bits, cleared, stat, t->start, t->end, t->duration, t->limit));

    return(0);

}  /* SiTimeout */


static int
SiMemWriteRead(int dram_addr, int data, int mask, int bytes)
{
    int a, res, errCount = 0;

    // Make sure it is 4 byte aligned
    for (a=(dram_addr & 0xFFFFFFFC); a<(dram_addr + bytes); a+=4) {

        IO_WRITE(a, data);
        res = IO_READ(a);
        if ((res&mask) != (data&mask)) {
            errCount++;
            SiLogResult(-1, "SiMemWriteRead", "read after write didn't match mask bits: addr, data, result, mask", dram_addr, data, res, mask);
        }
    }

    return((errCount == 0) ? 0 : -1);
}


static int
SiCmpBlock(int dram_addr, int value, int bytes)
{
    // Make sure it is 4 byte aligned
    int ret, r;
    int a   = dram_addr & 0xFFFFFFFC;
    int e   = dram_addr + bytes;

    for (ret = 0;  ret == 0 && a < e;  a += 4) {
        if ( (r=IO_READ(a)) != value ) {
            fprintf(DBGOUT, "\n\tSiCmpBlock: Error: Mem content (%0x8) doesn't match expected (%08x)",
                            r, value);
            ret = -1;
        }
    }
    return ret;
}




static int Si_v_int_compare(
    PV_INT data, unsigned int data_part, unsigned int xz_part, int mask )
{
        if ( ((data->data_part) & mask) == ((data_part|xz_part) & mask) &&
                 (data->xz_part & mask) == (xz_part & mask))
                return 0;

        return 0x100;
}

static int SiExtMemReadComp(int addr, int data_part, int xz_part, int mask)
{
    int ret;
    V_INT data;

    if(si_use_io_read_io_write || addr >= DDRRAM64_START) {
        if(SiMemWriteRead(addr, data_part, mask, 4))
            return -1;  
    } else {
        memset(&data, 0, sizeof(V_INT));
        ret = V_IO_SREAD_WORD(addr, BCP_SPLIT_XZ | BCP_WORD_SPLIT(1), &data);
        //_TRACE(DALL, fprintf(LogFp, "\n\tRead: @%08x: data = %08x %08x",
        //                                             addr, data.data_part, data.xz_part));
        if (ret) {
            fprintf(DBGOUT, "\n\t Error: in SiExtMemReadComp() ret=%x", ret);
            SiLogRes(ret, "SiExtMemReadComp", "V_IO_SREAD_WORD", "");
            return -1;
        }

        if (Si_v_int_compare(&data, data_part, xz_part, mask)) {
            fprintf(DBGOUT, "\n\t Error: SiExtMemReadComp @%x expected to read %08x %08x, but %08x %08x, with mask %08x",
                            addr, data_part, xz_part, data.data_part, data.xz_part, mask);
            SiLogRes(-1, "SiExtMemReadComp", "read after write didn't match mask bits", "");
            return -1;
        }
    }

    return 0;
}



static int
SiExtMemWrite(int addr, int data, int xz_part)
{
    int a, ret;

    a = addr & 0xFFFFFFFC; // Make sure it is 4 byte aligned
    if(si_use_io_read_io_write || addr >= DDRRAM64_START) {
        IO_WRITE(a, data);
    } else {
        if ((ret = ExtMemWrite(a, data, xz_part, 0)) == -1)
            return SiLogResult(ret, "SiExtMemWrite", "ExtMemWrite", a, data, xz_part, 0);
    }
    //_TRACE(dsi, fprintf(DBGOUT, "\n\tSiExtMemWrite:   addr %08x  data %08x  bytes %08x  xz_part: %08x",
    //                            addr, data, bytes, xz_part));
    return 0;
}


#if 0   /* Currently not being used */

static int
SiExtMemWriteRead(int addr, int data, int xz_part, int mask)
{
    int a, ret;

    if(si_use_io_read_io_write || addr >= DDRRAM64_START) {
        if(SiMemWriteRead(addr, data, 0xFFFFFFFF, 4))
            return -1;  
    } else {
        a = addr & 0xFFFFFFFC; // Make sure it is 4 byte aligned
        if ((ret = SiExtMemWrite(a, data, xz_part)) == -1)
            return SiLogResult(ret, "SiExtMemWriteRead", "SiExtMemWrite", a, data, xz_part, 0);
        if ((ret = SiExtMemReadComp(a, data, xz_part, mask)) == -1)
            return SiLogResult(ret, "SiExtMemWriteRead", "SiExtMemReadComp", a, data, xz_part, mask);
    }
    //_TRACE(dsi, fprintf(DBGOUT, "\n\tSiExtMemWriteRead:   addr %08x  data %08x  bytes %08x  xz_part: %08x",
    //                            addr, data, bytes, xz_part));
    return 0;
}

#endif  /* Currently not being used */


static int
SiBDMemWrite(int addr, int data, int xz_part)
{
    int a, ret;

    a = addr & 0xFFFFFFFC; // Make sure it is 4 byte aligned
    if(si_use_io_read_io_write || addr >= DDRRAM64_START) {
        IO_WRITE(a, data);
    } else {
        if ((ret = BDMemWrite(a, data, xz_part, 0)) == -1)
            return SiLogResult(ret, "SiBDMemWrite", "BDMemWrite", a, data, xz_part, 0);
    }
    //_TRACE(DWRITE, fprintf(DBGOUT, "\n\tSiBDMemWrite:  addr %08x  data  %08x  bytes  %08x  xz_part  %08x",
    //                               addr, data, bytes, xz_part));
    return 0;
}

static int
SiBDMemWriteRead(int addr, int data_part, int xz_part, int bytes, int inc_pat)
{
    int a, ret, data, errCount = 0;

    data = data_part;

    // Make sure it is 4 byte aligned
    for (a=(addr & 0xFFFFFFFC); a<(addr + bytes); a+=4, data += inc_pat) {
        if ((ret = SiBDMemWrite(a, data, xz_part)) == -1)
            return SiLogResult(ret, "SiBDMemWriteRead", "SiBDMemWrite", a, data, xz_part, 0);
        if ((ret = SiExtMemReadComp(a, data, xz_part, 0xFFFFFFFF)) == -1) {
            errCount++;
            SiLogResult(ret, "SiBDMemWriteRead", "SiExtMemReadComp", a, data, xz_part, 0);
        }
    }
    //_TRACE(DWRITE, fprintf(DBGOUT, "\n\tSiBDMemWriteRead:  addr %08x  data  %08x  bytes  %08x  xz_part  %08x",
    //                               addr, data, bytes, xz_part));
    return((errCount == 0) ? 0 : -1);
}




static int
SiDmaStart( Direction direction, int dram_addr,
            int data, int xz_part,
            ExpectedFailure expected_fail)
{
    // data is the value to write to the register to start the dma
    // If xz_part is non-zero, an extended write is done to start the dma
    // direction must be either Dir_From or Dir_To

    int  ret = 0;
    char reg_info[128];
    char tst_info[128];
    unsigned int status, config, mi_intr, si_intr, ints;
    int  start_reg = (direction == Dir_From) ? SI_DMA_WR_REG : SI_DMA_RD_REG;
    char siDmaReadOrWrite[20];
    snprintf(siDmaReadOrWrite, sizeof siDmaReadOrWrite, "SiDmaStart %s", (direction == Dir_From) ? "Write":"Read");
    snprintf(tst_info, sizeof tst_info, "dram_addr %08x  reg_data %08x  reg_xz %08x  exp_fail %d",
                       dram_addr, data, xz_part, expected_fail);
    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);

    if ( (status & SI_STATUS_DMA_ERROR) && !(expected_fail & ExpectedFail_DmaError) ) {
        fprintf(DBGOUT, "\n\t%s: DMA error before start DMA:\n\t\t%s\n\t\t%s", siDmaReadOrWrite, reg_info, tst_info);
        return -1;
    }
    if ( status & SI_STATUS_DMA_BUSY ) {
        fprintf(DBGOUT, "\n\t%s: DMA busy before SI DMA test:\n\t\t%s\n\t\t%s", siDmaReadOrWrite, reg_info, tst_info);
        return -1;
    }
    if (si_intr) {
        fprintf(DBGOUT, "\n\t%s: SI_INTR bit in MI_INTR already set before SI DMA test:\n\t\t%s\n\t\t%s", siDmaReadOrWrite, reg_info, tst_info);
        return -1;
    }
    if (dedicated_env && (ints & 1)) {
        fprintf(DBGOUT, "\n\t%s: lsb of int_l already set before SI DMA test:\n\t\t%s\n\t\t%s", siDmaReadOrWrite, reg_info, tst_info);
        return -1;
    }

    _TRACE(dsi, fprintf(DBGOUT, "\n\tBefore %s:\n\t\t%s\n\t\t%s", siDmaReadOrWrite, reg_info, tst_info));

    IO_WRITE(SI_DRAM_ADDR_REG, dram_addr);

    if ( xz_part ) {
        if ((ret = SiExtMemWrite(start_reg, data, xz_part)))
            return SiLogResult(ret, siDmaReadOrWrite, "SiExtMemWrite", start_reg, data, xz_part, 0);
    } else
        IO_WRITE(start_reg, data);

    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);

    if (status & SI_STATUS_DMA_ERROR) {
        ret = (expected_fail & ExpectedFail_DmaError)  ?  1 : -1;
        fprintf(DBGOUT, "\n\t%s: %sDMA error occured after start DMA:\n\t\t%s\n\t\t%s",
                         siDmaReadOrWrite, ((ret == 1) ? "Expected ":""), reg_info, tst_info);
        return ret;
    } else if (expected_fail & ExpectedFail_DmaError) {
        fprintf(DBGOUT, "\n\t%s: Expected DMA error did not occur after start DMA:\n\t\t%s\n\t\t%s",
                         siDmaReadOrWrite, reg_info, tst_info);
        return -1;
    }

    if (dedicated_env && !(status & SI_STATUS_DMA_BUSY)) {
        fprintf(DBGOUT, "\n\t%s: DMA not busy after start DMA:\n\t\t%s\n\t\t%s", siDmaReadOrWrite, reg_info, tst_info);
        return -1;
    }

    _TRACE(dsi, fprintf(DBGOUT, "\n\tAfter %s:\n\t\t%s\n\t\t%s", siDmaReadOrWrite, reg_info, tst_info));

    return(ret);

}  /* SiDmaStart */


static int
SiClearStatus()
{
    int  ret = 0;
    char reg_info[128];
    unsigned int status, config, mi_intr, si_intr, ints;

    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiClearStatus:  Before clear status:  %s", reg_info));
    IO_WRITE(SI_STATUS_REG, 0);
    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);

    if (status)
        return SiLogRes(-1, "SiClearStatus", "Expected SI_STATUS bits to be reset:  ", reg_info);

    if (si_intr)
        return SiLogRes(-1, "SiClearStatus", "Expected SI_INTR bit in MI_INTR to be reset:  ", reg_info);

    if (dedicated_env && (ints & 1))
        return SiLogRes(-1, "SiClearStatus", "Expected lsb of int_l to be reset:  ", reg_info);

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiClearStatus:  After clear status:  %s", reg_info));

    return ret;
}


static int
SiDmaWait( Direction direction, int dram_addr,
           SiTimeoutInfo *timeout, ExpectedFailure expected_fail )
{
    // dram_addr is only used for dumping if dsi is set.
    // direction is only used for err logs and must be either Dir_From or Dir_To

    int  ret = 0;
    char reg_info[128];
    char siDmaReadOrWrite[20];
    unsigned int status, config, mi_intr, si_intr, ints;
    unsigned int buf_addr, lgbbs, ugbbs, lgb_addr, total_bytes;

    buf_addr    = SiAlignedDmaBufAddr  (dram_addr);
    lgbbs       = SiLowerGuardBandBytes(buf_addr, STD_GUARD_BAND_BYTES);
    ugbbs       = SiUpperGuardBandBytes(buf_addr, STD_GUARD_BAND_BYTES);
    total_bytes = lgbbs + SI_DMA_XFER_BYTES + ugbbs;
    lgb_addr    = buf_addr - lgbbs;

    snprintf(siDmaReadOrWrite, sizeof siDmaReadOrWrite, "SiDmaWait %s", (direction == Dir_From) ? "Write":"Read");

    ret = SiTimeout(SI_STATUS_REG, SI_STATUS_DMA_BUSY, CLEARED, timeout);

    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);

    if (ret) fprintf(DBGOUT, "\n\t%s: Timeout waiting for DMA not busy:  duration %u\n\t\t%s  dram_addr %08x",
                             siDmaReadOrWrite, timeout->duration, reg_info, dram_addr);
    else _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: On return from SiTimeout.  duration %u\n\t\t%s  dram_addr %08x",
                             siDmaReadOrWrite, timeout->duration, reg_info, dram_addr));

    _TRACE(dsi, dump(siDmaReadOrWrite, ": After DMA Busy bit cleared", lgb_addr, total_bytes));

    if (ret)
        return (expected_fail & ExpectedFail_DmaTimeout)  ?  1 : ((stop_test_on_err = stop_tests_on_err = 1),-1);

    if (status & SI_STATUS_DMA_ERROR) {
        fprintf(DBGOUT, "\n\t%s: DMA Error bit set after DMA:\n\t\t%s  dram_addr %08x", siDmaReadOrWrite, reg_info, dram_addr);
        return (expected_fail & ExpectedFail_DmaError)  ?  1 : -1;
    }

    if (!(status & SI_STATUS_INTERRUPT)) {
        fprintf(DBGOUT, "\n\t%s: SI Status interrupt bit not set after DMA:\n\t\t%s  dram_addr %08x", siDmaReadOrWrite, reg_info, dram_addr);
        return -1;
    }

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: After Busy cleared:\n\t\t%s  dram_addr %08x", siDmaReadOrWrite, reg_info, dram_addr));

    if (!si_intr) {
        fprintf(DBGOUT, "\n\t%s: MI SI interrupt bit not set after DMA:\n\t\t%s  dram_addr %08x", siDmaReadOrWrite, reg_info, dram_addr);
        return -1;
    }

    if (dedicated_env && !(ints & 1)) {
        char *expected = (expected_fail & ExpectedFail_No_int_l_AfterDma) ? "Expected":"";
        fprintf(DBGOUT, "\n\t%s: lsb of int_l  not set after DMA:  %s\n\t\t%s  dram_addr %08x", siDmaReadOrWrite, expected, reg_info, dram_addr);
        return *expected ? 1 : -1;
    }

    if(direction == Dir_From && timeout->duration > DMA_MAX_WRITE_ns) {
        fprintf(DBGOUT, "\n\t%s: SI Write DMA took too long:  duration %u\n\t\t%s  dram_addr %08x",
                        siDmaReadOrWrite, timeout->duration, reg_info, dram_addr);
        return -1;
    }

    if (expected_fail & ExpectedFail_DmaTimeout) {
        fprintf(DBGOUT, "\n\t%s: Expected Timeout waiting for DMA not busy did not occur:  duration %u\n\t\t%s  dram_addr %08x",
                             siDmaReadOrWrite, timeout->duration, reg_info, dram_addr);
        return -1;
    }

    if (expected_fail & ExpectedFail_DmaError) {
        fprintf(DBGOUT, "\n\t%s: Expected DMA Error did not occur:  duration %u\n\t\t%s  dram_addr %08x",
                             siDmaReadOrWrite, timeout->duration, reg_info, dram_addr);
        return -1;
    }

    if (expected_fail & ExpectedFail_No_int_l_AfterDma) {
        fprintf(DBGOUT, "\n\t%s: Didn't expect lsb of int_l to be set after DMA:  duration %u\n\t\t%s  dram_addr %08x",
                             siDmaReadOrWrite, timeout->duration, reg_info, dram_addr);
        return -1;
    }

    ret = SiClearStatus();

    return(ret);

}  /* SiDmaWait */





static int
SiDma( Direction direction, int dram_addr, int data, int xz_part )
{
    // data is the value to write to the register to start the dma
    // If xz_part is non-zero, an extended write is done to start the dma
    // direction must be either Dir_From or Dir_To

    int ret;
    SiTimeoutInfo timeout;

    memset(&timeout, 0, sizeof(SiTimeoutInfo));
    timeout.limit = DEFAULT_DMA_TIMEOUT;

    ret          = SiDmaStart(direction, dram_addr, data, xz_part, ExpectedFail_None);
    if(!ret) ret = SiDmaWait (direction, dram_addr, &timeout, ExpectedFail_None);

    return(ret);

}  /* SiDma */





static int
SiFillDmaBuf( int dram_addr, int guard_band_bytes, int fill_value  )
{
    int ret = 0;
    unsigned int  buf_addr, lgbbs, ugbbs, lgb_addr, total_bytes;

    buf_addr    = SiAlignedDmaBufAddr  (dram_addr);
    lgbbs       = SiLowerGuardBandBytes(buf_addr, guard_band_bytes);
    ugbbs       = SiUpperGuardBandBytes(buf_addr, guard_band_bytes);
    total_bytes = lgbbs + SI_DMA_XFER_BYTES + ugbbs;
    lgb_addr    = buf_addr - lgbbs;

    if((ret = SiBDMemWriteRead(lgb_addr, fill_value, 0, total_bytes, GUARD_BAND_INC_PAT)))
        SiLogResult(ret, "SiFillDmaBuf", "SiBDMemWriteRead", lgb_addr, fill_value, 0, total_bytes);

    return ret;
}
 



static void
setCtrlCmdData(  SiCtrlBufParams *b,
                 int block_code,
                 int error,
                 int tx_size,
                 int rx_size,
                 CtrlCmdCode cmd,
                 int tx_rx_buf )
{
    b->block_code  = block_code;
    b->tx_size     = tx_size;
    b->error       = error;
    b->rx_size     = rx_size;
    b->cmd         = cmd;
    b->tx_rx_buf   = tx_rx_buf;
}



static void
SiSetupFailureTest (int ctrlr, SiDmaTestParam *dma,
                    ForceFail failure, int fail_param, int cmd_count)
{
    // Requires dma->w and dma->r have already been setup for a valid cmd
    // If failure isn't ForceFail_None,
    //     setup to cause or simulate the specified failure
    // ForceFail_Random can be specified to create random a failure
    // If ForceFail_Occasionally is specified
    //     A random failure will be created every time
    //     cmd_count % fail_param is 0 (i.e. every fail_param'th
    //     time the cmd is tested based on cmd_count) 
    // Some ForceFail's are not applicable to the lc
    // fail_param can be used to specify specific parameters or 
    // variations on a failure.  It is only significant if the specified
    // failure makes use of it in this function.
    // Check the code below for each fail type to see if and how
    // the fail_param can be used

    SiCtrlBufParams * w = &dma->w.ctrlr[ctrlr];
    SiCtrlBufParams * r = &dma->r.ctrlr[ctrlr];

    int e = 1; // enable

    ForceFail failure_arg    = failure;
    int       fail_param_arg = fail_param;

    if (     failure == ForceFail_Random
         || (failure == ForceFail_Occasionally && !(cmd_count % fail_param)) )
    {
        failure = randomFailure (ctrlr, dma);
        fail_param = 0;
    }

    if (isSlaveMode && ctrlr) {
        // In slave mode, although jctrl 1 is enabled, only lctrl is available for normal ops
        // jctrl 1 is manipulated by SiSlaveTest and SiSetupSmReceive for slave mode ops
        // The sm dma parameters set up for jctrl 1 here are only used with no xmit cmds
        failure = ForceFail_None;
        fail_param = 0;
        if(isUseMJCTRL || ctrlr != 1)
            e = 0;
    }

    if (ctrlr) {
        // first handle failures that don't apply to lc
        // init to no backdoor errors

        switch (failure) {
            case ForceFail_NoResponse:
                if (w->tx_size) // no error if no xmit cmd
                    r->error = CTRL_ERR_NO_RESPONSE;
                bd_si_ctrl_setup(ctrlr, CTRL_ENALE,     0, 0);
                bd_si_ctrl_setup(ctrlr, CTRL_COLLISION, 0, 0);
                bd_si_ctrl_setup(ctrlr, CTRL_FRAMEERR , 0, 0);
                break;
            case ForceFail_Collision:
                if (w->tx_size) // no error if no xmit cmd
                    r->error = CTRL_ERR_COLLISION;
                bd_si_ctrl_setup(ctrlr, CTRL_ENALE,     1, 0);
                fail_param = fail_param ? (fail_param - 1) : 0x2; // bit 3 enables, bits 2-1 indicate when
                bd_si_ctrl_setup(ctrlr, CTRL_COLLISION, 0x08 | fail_param , 0);
                bd_si_ctrl_setup(ctrlr, CTRL_FRAMEERR , 0, 0);
                dma->delayAfterDone = JCTRL_DELAY_AFTER_DONE;
                break;
            case ForceFail_Frame:
                if (w->tx_size) // no error if no xmit cmd
                    r->error = CTRL_ERR_FRAME;
                bd_si_ctrl_setup(ctrlr, CTRL_ENALE,     1, 0);
                bd_si_ctrl_setup(ctrlr, CTRL_COLLISION, 0, 0);
                fail_param = fail_param ? (fail_param - 1) : 0x2;  // bit 5 enables, bits 4-0 indicate when
                bd_si_ctrl_setup(ctrlr, CTRL_FRAMEERR,  0x20 | fail_param, 0);
                dma->delayAfterDone = JCTRL_DELAY_AFTER_DONE;
                break;
            default:
                bd_si_ctrl_setup(ctrlr, CTRL_COLLISION, 0, 0);
                bd_si_ctrl_setup(ctrlr, CTRL_FRAMEERR , 0, 0);
                bd_si_ctrl_setup(ctrlr, CTRL_GLITCH_DETECT, 1, 0);
                bd_si_ctrl_setup(ctrlr, CTRL_ENALE,     e, 0);
                dma->delayAfterDone = 0;
        }
    }

    // then handle failures applicable to all
    switch (failure) {
        case ForceFail_None:
        case ForceFail_Occasionally:
        case ForceFail_NoResponse:
        case ForceFail_Collision:
        case ForceFail_Frame:
            break;

        case ForceFail_tx_TooBigForAnyCmdType:
            if ( w->tx_size == 0) {
                failure = ForceFail_None;
                fail_param = 0;
                _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupFailureTest:  ForceFail_tx_TooBigForAnyCmdType ignored for no xmit:"
                                            "\n\t\tctrlr %d  Failure %d  fail_param %#x  failure_arg %d  fail_param_arg %#x  cmd_count: %d"
                                            , ctrlr, failure, fail_param, failure_arg, fail_param_arg, cmd_count));
                break; // skip no xmit cmds
            }
            if (ctrlr || (isSupportedCmd(r->cmd) && r->cmd != CtrlRead && r->cmd != CtrlWrite))
                r->error = CTRL_ERR_REQUEST;
            else
                r->error = CTRL_ERR_REQUEST | CTRL_ERR_NO_RESPONSE;
            if (ctrlr)
                dma->delayAfterDone = JCTRL_DELAY_AFTER_DONE;
            if (fail_param) {
                w->tx_size = fail_param;
                if ( fail_param & 0xFFFFFF00 )
                    SiLogResult(-1, "SiSetupFailureTest", "ForceFail_tx_TooBigForAnyCmdType: fail_parm too big for tx size field"
                                    , ctrlr, failure, fail_param, cmd_count);
            } else
                w->tx_size = 64 + random() % (256-64);
            if(ctrlr && w->tx_size > r->tx_size)
                bd_si_ctrl_setup(ctrlr, CTRL_GLITCH_DETECT, 0, 0);
            r->tx_size = w->tx_size;
            break;

        case ForceFail_tx_InvalidForCmdType:
            if ( w->tx_size == 0) {
                failure = ForceFail_None;
                fail_param = 0;
                _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupFailureTest:  ForceFail_tx_InvalidForCmdType ignored for no xmit:"
                                            "\n\t\tctrlr %d  Failure %d  fail_param %#x  failure_arg %d  fail_param_arg %#x  cmd_count: %d"
                                            , ctrlr, failure, fail_param, failure_arg, fail_param_arg, cmd_count));
                break; // skip no xmit cmds
            }
            if (ctrlr) {
                r->error = CTRL_ERR_NO_RESPONSE;
                dma->delayAfterDone = JCTRL_DELAY_AFTER_DONE;
            } else {
                r->error = CTRL_ERR_REQUEST;
                if (!isSupportedCmd(r->cmd) || r->cmd == CtrlRead || r->cmd == CtrlWrite)
                    r->error |= CTRL_ERR_NO_RESPONSE;
            }
            if (fail_param) {
                w->tx_size = fail_param;
                if ( fail_param & 0xFFFFFFC0 )
                    SiLogResult(-1, "SiSetupFailureTest", "ForceFail_tx_InvalidForCmdType: fail_parm too big for tx size field"
                                    , ctrlr, failure, fail_param, cmd_count);
            } else {
                // tx_size is 1 for status,buttons, and reset, but not for read, write or pass through cmds
                while (w->tx_size == r->tx_size )
                    w->tx_size = 1 + random() % (16-1);
            }
           
            w->tx_rx_buf = 0xffffffff; 
            if(ctrlr && w->tx_size > r->tx_size)
                bd_si_ctrl_setup(ctrlr, CTRL_GLITCH_DETECT, 0, 0);
            r->tx_size = w->tx_size;
            break;

        case ForceFail_rx_TooBigForAnyCmdType:
            // get a request error even if no xmit cmd
            r->error = CTRL_ERR_REQUEST;
            if (!ctrlr) {
                if (!isSupportedCmd(r->cmd) || r->cmd == CtrlRead || r->cmd == CtrlWrite)
                    r->error |= CTRL_ERR_NO_RESPONSE;
            }
            if (fail_param) {
                w->rx_size = fail_param;
                if ( fail_param & 0xFFFFFF00 )
                    SiLogResult(-1, "SiSetupFailureTest", "ForceFail_rx_TooBigForAnyCmdType: fail_parm too big for rx size field", ctrlr, failure, fail_param, cmd_count);
            } else
                w->rx_size = 64 + random() % (256-64);
            r->rx_size = w->rx_size;
            if(ctrlr)
                dma->delayAfterDone = JCTRL_DELAY_AFTER_DONE;
            break;

        case ForceFail_rx_InvalidForCmdType: {
            int w_rx_size = w->rx_size;
            int w_tx_rx_buf = w->tx_rx_buf;
            int r_tx_rx_buf = r->tx_rx_buf;
            if (fail_param) {
                w_rx_size = fail_param;
                if ( fail_param & 0xFFFFFFC0 )
                    SiLogResult(-1, "SiSetupFailureTest", "ForceFail_rx_InvalidForCmdType: fail_parm too big for rx size field", ctrlr, failure, fail_param, cmd_count);
                else if (w_rx_size == r->rx_size)
                    SiLogResult(-1, "SiSetupFailureTest", "ForceFail_rx_InvalidForCmdType: fail_parm == correct rx size field", ctrlr, failure, fail_param, cmd_count);
            } else {
                while (w_rx_size == r->rx_size) {
                    w_rx_size = 1 + random() % (64-1);
                }
            }
            if (!ctrlr && !isSupportedCmd(r->cmd)) {
                r->error = CTRL_ERR_REQUEST | CTRL_ERR_NO_RESPONSE;
            } else if (!ctrlr) {
                r->error = CTRL_ERR_REQUEST;
                if(r->cmd == CtrlRead || r->cmd == CtrlWrite)
                    r->error |= CTRL_ERR_NO_RESPONSE;
            } else if (w->tx_size) {
                if (w_rx_size > w->rx_size) {
                    r->error = CTRL_ERR_NO_RESPONSE;
                } else if (r->rx_size > w_rx_size) {
                    if (w_rx_size < 4) {
                        int i, limit = r->rx_size < 4 ? r->rx_size : 4;
                        for (i=w_rx_size;  i < limit;  ++i ) {
                            unsigned int bytemask = 0x00FF0000 >> ((i-1)*8);
                            if (!(w_tx_rx_buf & bytemask))
                                w_tx_rx_buf |= bytemask;
                            r_tx_rx_buf &= ~bytemask;
                        }
                    } else if (r->cmd == CtrlRead) {
                        r_tx_rx_buf = (r_tx_rx_buf & 0xFFFFFF00) | read_cmd_rcv_data[ctrlr][w_rx_size-1];
                    }
                }
            }
            w->rx_size = w_rx_size;
            r->rx_size = w->rx_size;
            w->tx_rx_buf = w_tx_rx_buf;
            r->tx_rx_buf = r_tx_rx_buf;
            if(ctrlr)
                dma->delayAfterDone = JCTRL_DELAY_AFTER_DONE;
            break;
        }

        case ForceFail_rx_Zero:
            r->rx_size = w->rx_size = 0;
            // get a lctrl request error even if no xmit cmd
            if (!ctrlr) {
                r->error = CTRL_ERR_REQUEST;
                if(!isSupportedCmd(r->cmd) || r->cmd == CtrlRead || r->cmd == CtrlWrite)
                    r->error |= CTRL_ERR_NO_RESPONSE;
            } else {
                dma->delayAfterDone = JCTRL_DELAY_AFTER_DONE;
                if(w->tx_size) {
                    if (w->tx_size == 1)
                        w->tx_rx_buf = 0xFFFFFFFF;
                    r->tx_rx_buf = 0;
                }
            }
            break;

        case ForceFail_ClearSiIntMask:
            SiSetInterruptMask(0);
            dma->w.expected_failure |= ExpectedFail_No_int_l_AfterDma;
            dma->r.expected_failure |= ExpectedFail_No_int_l_AfterDma;
            break;

        default:
            SiLogResult(-1, "SiSetupFailureTest", "Invalid FailureTest specified", ctrlr, failure, fail_param, cmd_count);
            break;
    }

    if ( failure != ForceFail_None  &&  failure != ForceFail_Occasionally ) {
        unsigned long long now;
        SIM_TIME(&now);
        _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupFailureTest:  now %llu  ctrlr %d  Failure %d  fail_param %#x  failure_arg %d  fail_param_arg %#x  cmd_count: %d",
                                     now, ctrlr, failure, fail_param, failure_arg, fail_param_arg, cmd_count));
    }
}




static int
SiSetupUnsupCmdTest(int ctrlr, SiDmaTestParam *dma,
                  int cmd, int tx_rx_buf,
                  ForceFail failure,   int fail_param,  int no_xmit)
{
    // ctrlr is 0 for lc, 1 for j1, 2 for j2, 3 for j3
    // cmd is either CtrlRandomCmd, CtrlJcUnsupCmd,
    // or an 8 bit unsupported cmd code (i.e. not 0, 1, or 255)
    // jc's will return the written tx_rx_buf in the read tx_rx_buf
    // Set dma->w.ctrlr[ctrlr].tx_rx_buf to specified data
    // set dma->r to expected values
    // expect lc err bits:  11000 (no response and overrun/request)
    // j1, j2, and j3 will return 0x00 in error field
    // For no_xmit set tx_size to 0 and expect 0 tx_rx and
    //   lc err bit: 11000 (no response and overrun/request)
    //   j1, j2, and j3 will return 0x00 in error field

    // See comments in SiSetupFailureTest() for how to use failure and fail_param,

    // tx_rx_buf is a 4 byte value

    // Slave Mode:
    //   See comments in SiSlaveTest.                        

    static int cmd_count;

    int ret = 0;
    int i = ctrlr;
    int expected_rx;
    int tx_size, rx_size, error;

    if ( (CtrlCmdCode)cmd == CtrlRandomCmd || (CtrlCmdCode)cmd == CtrlJcUnsupCmd)
        cmd = unsupportedCmd();
    else if ( cmd < 0 || cmd > 255 ) {
        fprintf(DBGOUT, "\n\tOut of range cmd type passed to SiSetupUnsupCmdTest, picking a random unsuported cmd");
        cmd = unsupportedCmd();
    } else if ( isSupportedCmd((CtrlCmdCode)cmd) ) {
        fprintf(DBGOUT, "\n\tSupported cmd type passed to SiSetupUnsupCmdTest, picking a random unsuported cmd");
        cmd = unsupportedCmd();
    }

    if(!ctrlr && isSlaveMode) {
        // cmds with bits 2-0 == 0 behave different
        // Per the hw it means send no bytes (not even the cmd)
        // If the master sends a cmd with bits 2-0 == 0, the dma finishes,
        // but the request bit doesn't come on and the rx_size says 0
        rx_size = cmd&7;
        tx_size = no_xmit ? 0 : cmd&7;
    } else {
        rx_size = (cmd&3) + 1;
        tx_size = no_xmit ? 0 : rx_size + 1;
    }
    error   = i ? 0 : (CTRL_ERR_REQUEST | CTRL_ERR_NO_RESPONSE);
    if (ctrlr) {
        if(isSlaveMode)
            no_xmit = TRUE;
        if (no_xmit)
            expected_rx = tx_rx_buf;
        else
            expected_rx = tx_rx_buf & (0xFFFFFFFF << (4-rx_size)*8);
    } else
        expected_rx = 0;

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupUnsupCmdTest: ctrlr %d:  %scmd %02x  tx_rx_buf: %08x  expected_rx: %08x",
                                ctrlr, no_xmit?"no_xmit:  ":"", cmd, tx_rx_buf, expected_rx));

    if(isSlaveMode && ctrlr)
        rx_size = 0; // SiStartSlaveReceive and SiSlaveTest modify jctrl 1 tx/rx size's

    setCtrlCmdData(&dma->w.ctrlr[i], 0xFF,     0, tx_size, rx_size, cmd, tx_rx_buf  );
    setCtrlCmdData(&dma->r.ctrlr[i], 0xFF, error, tx_size, rx_size, cmd, expected_rx);

    SiSetupFailureTest (ctrlr, dma, failure, fail_param, ++cmd_count);

    return ret;
}





static int
SiSetupCtrlResetTest(int ctrlr, SiDmaTestParam *dma,
                     int type_L, int type_H,  int status,
                     ForceFail failure, int fail_param, int no_xmit)
{
    // ctrlr is 0 for lc, 1 for j1, 2 for j2, 3 for j3
    // Set ctrlr status via BD
    // Set dma->w data struct to get status
    // set dma->r data struct to expected values
    // For no_xmit set tx_size to 0 and expect 0 tx_rx and
    // expect no errors

    // See comments in SiSetupFailureTest() for how to use failure and fail_param,

    // type_L, type_H, and status are all 8 bit values
    // lc (i.e. ctrlr 0) has no backdoor for setting type/status

    // Slave Mode:
    //   See comments in SiSlaveTest.

    static int cmd_count;

    int ret = 0;
    int i = ctrlr;
    int expected_rx = 0;
    int tx_size, rx_size, error;
    unsigned long long bd_write_time;

    if (ctrlr) {
        if(isSlaveMode)
            no_xmit = TRUE;
        if (!no_xmit)
            expected_rx = (type_L << 24) | ((type_H & 0xFF) << 16) | ((status & 0xFF) << 8);
        bd_si_ctrl_setup(ctrlr, CTRL_TYPE_L, type_L, 0);
        bd_si_ctrl_setup(ctrlr, CTRL_TYPE_H, type_H, 0);
        bd_si_ctrl_setup(ctrlr, CTRL_STATUS, status, 0);
        SIM_TIME(&bd_write_time);
        _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupCtrlResetTest: ctrlr %d:   %sCTRL_TYPE_L: %08x  CTRL_TYPE_H: %08x  CTRL_STATUS: %08x  expected_rx: %08x  bd_write_time %llu",
                                    ctrlr, no_xmit?"no_xmit:  ":"", type_L, type_H, status, expected_rx, bd_write_time));
    } else {
        expected_rx = ntohl(CONT_TYPE_NORMAL);
        if (!no_xmit) {
            bd_si_ctrl_setup(ctrlr, LCTRL_XMOVE, 0, 0);
            bd_si_ctrl_setup(ctrlr, LCTRL_YMOVE, 0, 0);
            SIM_TIME(&bd_write_time);
            SiResetLctrlJsXyStateData();
            _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupCtrlResetTest: ctrlr %d:   Wait for bd to sync with 0 xmove,ymove:  bd_write_time %llu", ctrlr, bd_write_time));
            SiWait(lctrl.ns_jsmove_1);
        }
        _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupCtrlResetTest: ctrlr %d:   %sexpected_rx: %08x", ctrlr, no_xmit?"no_xmit:  ":"", expected_rx));
    }

    tx_size = no_xmit ? 0 : 1;
    error   = 0;

    if(isSlaveMode && ctrlr)
        rx_size = 0; // SiStartSlaveReceive and SiSlaveTest modify jctrl 1 tx/rx size's
    else
        rx_size = 3;

    setCtrlCmdData(&dma->w.ctrlr[i], 0xFF,     0, tx_size, rx_size, CtrlReset, 0);
    setCtrlCmdData(&dma->r.ctrlr[i], 0xFF, error, tx_size, rx_size, CtrlReset, expected_rx);

    SiSetupFailureTest (ctrlr, dma, failure, fail_param, ++cmd_count);

    return ret;
}



static int
SiSetupStatusTest(int ctrlr, SiDmaTestParam *dma,
                  int type_L, int type_H,  int status,
                  ForceFail failure,  int fail_param, int no_xmit)
{
    // ctrlr is 0 for lc, 1 for j1, 2 for j2, 3 for j3
    // Set ctrlr status via BD
    // Set dma->w data struct to get status
    // set dma->r data struct to expected values
    // For no_xmit set tx_size to 0 and expect 0 tx_rx and
    // expect no errors

    // See comments in SiSetupFailureTest() for how to use failure and fail_param,

    // type_L, type_H, and status are all 8 bit values
    // lc (i.e. ctrlr 0) has no backdoor for setting type/status

    // Slave Mode:
    //   See comments in SiSlaveTest.                        

    static int cmd_count;

    int ret = 0;
    int i = ctrlr;
    int expected_rx = 0;
    int tx_size, rx_size, error;
    unsigned long long bd_write_time;

    if (ctrlr) {
        if(isSlaveMode)
            no_xmit = TRUE;
        if (!no_xmit)
            expected_rx = (type_L << 24) | ((type_H & 0xFF) << 16) | ((status & 0xFF) << 8);
        bd_si_ctrl_setup(ctrlr, CTRL_TYPE_L   , type_L, 0);
        bd_si_ctrl_setup(ctrlr, CTRL_TYPE_H   , type_H, 0);
        bd_si_ctrl_setup(ctrlr, CTRL_STATUS   , status, 0);
        SIM_TIME(&bd_write_time);
        _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupStatusTest: ctrlr %d:   %sCTRL_TYPE_L: %08x  CTRL_TYPE_H: %08x  CTRL_STATUS: %08x  expected_rx: %08x  bd_write_time %llu",
                                    ctrlr, no_xmit?"no_xmit:  ":"", type_L, type_H, status, expected_rx, bd_write_time));
    } else {
        expected_rx = ntohl(CONT_TYPE_NORMAL);
        _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupStatusTest: ctrlr %d:   %sexpected_rx: %08x",
                                    ctrlr, no_xmit?"no_xmit:  ":"", expected_rx));
    }

    tx_size = no_xmit ? 0 : 1;
    error   = 0;

    if(isSlaveMode && ctrlr)
        rx_size = 0; // SiStartSlaveReceive and SiSlaveTest modify jctrl 1 tx/rx size's
    else
        rx_size = 3;

    setCtrlCmdData(&dma->w.ctrlr[i], 0xFF,     0, tx_size, rx_size, CtrlQueryStatus, 0);
    setCtrlCmdData(&dma->r.ctrlr[i], 0xFF, error, tx_size, rx_size, CtrlQueryStatus, expected_rx);

    SiSetupFailureTest (ctrlr, dma, failure, fail_param, ++cmd_count);

    return ret;
}



static int
SiSetupReadTest(int ctrlr, SiDmaTestParam *dma,
                u16 addr, u8 data[32],
                ForceFail failure,  int fail_param, int no_xmit)
{
    // ctrlr is 0 for lc, 1 for j1, 2 for j2, 3 for j3
    // Set ctrlr responses via BD
    // Set dma->w data struct to get ctrlr response
    // set dma->r data struct to expected values
    // For no_xmit set tx_size to 0 and expect 0 tx_rx and
    // expect no errors

    // See comments in SiSetupFailureTest() for how to use failure and fail_param,

    // lc (i.e. ctrlr 0) does not support this command

    // Slave Mode:
    //   See comments in SiSlaveTest.

    static int cmd_count;

    int ret = 0;
    int i = ctrlr;
    int k;
    u8  expected[4] = {0,0,0,0};
    int tx_buf           = 0;
    int expected_rx      = 0;
    int tx_size, rx_size, error;
    unsigned long long bd_write_time;

    if (ctrlr) {
        if(isSlaveMode)
            no_xmit = TRUE;
        if (!no_xmit) {
            unsigned int timeout_limit = (33+3)*33000*(use_rsp_rand[ctrlr]?3:1) + 100000;
            if(timeout_limit > dma->r.timeout.limit)
                dma->r.timeout.limit = timeout_limit;
            read_cmd_xmit_data[ctrlr][0] = CtrlRead;
            read_cmd_xmit_data[ctrlr][1] = (addr>>8)&0x00FF;
            read_cmd_xmit_data[ctrlr][2] =  addr    &0x00FF;
            tx_buf = (((addr>>8)&0x00FF)<<24) | ((addr&0x00FF)<<16);
            for(k=0; k<32; k++) {
                if(k<3) expected[k] = data[k];
                expected[3] += data[k];
                read_cmd_rcv_data[ctrlr][k] = data[k];
            }
            expected_rx = expected[0]<<24 | expected[1]<<16 | expected[2]<<8 | expected[3];
        }
        bd_si_ctrl_wr_pkd(ctrlr, CTRL_READ_DATA, data, 32);
        SIM_TIME(&bd_write_time);
        _TRACE(dsi, fprintf(DBGOUT,
            "\n\tSiSetupReadTest: ctrlr %d:   %saddr: %08x  crc: : %08x  "
            "data[0]: %08x  data[1]: %08x  data[2]: %08x  expected_rx: %08x  bd_write_time %llu",
            ctrlr, no_xmit?"no_xmit:  ":"", addr, expected[3],
            data[0], data[1], data[2], expected_rx, bd_write_time));
    } else {
        expected_rx = 0;
        _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupStatusTest: ctrlr %d:   %sexpected_rx: %08x",
                                    ctrlr, no_xmit?"no_xmit:  ":"", expected_rx));
    }

    tx_size = no_xmit ? 0 : 3;
    error   = i ? 0 : (CTRL_ERR_REQUEST | CTRL_ERR_NO_RESPONSE);

    if(isSlaveMode && ctrlr)
        rx_size = 0; // SiStartSlaveReceive and SiSlaveTest modify jctrl 1 tx/rx size's
    else
        rx_size = no_xmit ? 1 : 33;

    setCtrlCmdData(&dma->w.ctrlr[i], 0xFF,     0, tx_size, rx_size, CtrlRead, tx_buf);
    setCtrlCmdData(&dma->r.ctrlr[i], 0xFF, error, tx_size, rx_size, CtrlRead, expected_rx);

    SiSetupFailureTest (ctrlr, dma, failure, fail_param, ++cmd_count);

    return ret;
}



static int
SiSetupWriteTest(int ctrlr, SiDmaTestParam *dma,
                u8 data[5],
                ForceFail failure,  int fail_param, int no_xmit)
{
    // ctrlr is 0 for lc, 1 for j1, 2 for j2, 3 for j3
    // Set ctrlr responses via BD
    // Set dma->w data struct to setup ctrlr xmit
    // set dma->r data struct to expected values
    // For no_xmit set tx_size to 0 and expect 0 tx_rx and
    // expect no errors

    // See comments in SiSetupFailureTest() for how to use failure and fail_param,

    // lc (i.e. ctrlr 0) does not support this command

    // Slave Mode:
    //   See comments in SiSlaveTest.

    static int cmd_count;

    int ret = 0;
    int i = ctrlr;
    int k;
    u8  addr;
    int crc         = 0;
    int tx_buf      = 0;
    int expected_rx = 0;
    int tx_size, rx_size, error;
    unsigned long long bd_write_time;

    if (ctrlr) {
        if(isSlaveMode)
            no_xmit = TRUE;
        if (!no_xmit) {
            unsigned int timeout_limit = (35+2)*33000*(use_rsp_rand[ctrlr]?3:1) + 100000;
            if(timeout_limit > dma->r.timeout.limit)
                dma->r.timeout.limit = timeout_limit;
            tx_buf = (data[1]<<24) | (data[2]<<16) | (data[3]<<8) | data[4];
            for(k=3; k<35; k++) {
                crc += (k<4) ? data[k] : data[4];
            }
            expected_rx = crc << 24;
            for(k=0; k<5; ++k)
                write_cmd_data[ctrlr][k] =  data[k];
        }
        SIM_TIME(&bd_write_time);
        addr = (data[1]<<8) | data[2];
        _TRACE(dsi, fprintf(DBGOUT,
            "\n\tSiSetupWriteTest: ctrlr %d:   %saddr: %08x  crc: %08x  "
            "data0: %08x  data1: %08x  expected_rx: %08x  bd_write_time %llu",
            ctrlr, no_xmit?"no_xmit:  ":"", addr, crc, data[3], data[4], expected_rx, bd_write_time));
    } else {
        expected_rx = 0;
        _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupStatusTest: ctrlr %d:   %sexpected_rx: %08x",
                                    ctrlr, no_xmit?"no_xmit:  ":"", expected_rx));
    }

    tx_size = no_xmit ? 0 : 35;
    error   = i ? 0 : (CTRL_ERR_REQUEST | CTRL_ERR_NO_RESPONSE);

    if(isSlaveMode && ctrlr)
        rx_size = 0; // SiStartSlaveReceive and SiSlaveTest modify jctrl 1 tx/rx size's
    else
        rx_size = 1;

    setCtrlCmdData(&dma->w.ctrlr[i], 0xFF,     0, tx_size, rx_size, CtrlWrite, tx_buf);
    setCtrlCmdData(&dma->r.ctrlr[i], 0xFF, error, tx_size, rx_size, CtrlWrite, expected_rx);

    SiSetupFailureTest (ctrlr, dma, failure, fail_param, ++cmd_count);

    return ret;
}



static int
SiSetupButtonTest(int ctrlr, SiDmaTestParam *dma,
                  int buttons, int x, int y,
                  ForceFail failure,   int fail_param, int no_xmit)
{
    // ctrlr is 0 for lc, 1 for j1, 2 for j2, 3 for j3
    // Set ctrlr buttons and x,y via BD
    // Set dma->w data struct to get buttons
    // set dma->r data struct to expected values
    // For no_xmit set tx_size to 0 and expect 0 tx_rx and
    // expect no errors

    // See comments in SiSetupFailureTest() for how to use failure and fail_param,

    // buttons is a 16 bit mask composed of bytes 'buttons_L' and 'buttons_H'
    // buttons  = (buttons_L << 8)  |  buttons_H
    // buttons_L = (buttons & 0xFF00) >> 8;
    // buttons_H =  buttons & 0x00FF;
    // The backdoor buttons parameter expects the bytes to be swapped.
    // bd_buttons is a 16 bit mask composed of (buttons_H << 8)  |  buttons_L
    // bit 6 and 7 of buttons_H are read only.  bit 6 is always 0, bit 7 is JSRST

    // x and y are 8 bit values for jctrls but 32 bit int for lctrl
    // lctrl really only uses 8bits, but bd allows bigger value to
    // be written, to test that only 8 bits are used.
    // jctrl x, y are absolute immediately readable values
    // lctrl x, y is relative and takes time to move.  We wait for button polling,
    // but not js, so we expect it to get closer on each read, but may not reach
    // the final expected value until lctrl.?move_timeout.

    // Slave Mode:
    //   See comments in SiSlaveTest.                        

    static int cmd_count;

    int ret = 0;
    int i = ctrlr;
    int expected_rx = 0;
    int tx_size, rx_size, error;

    int bd_buttons = ((buttons & 0xFF00) >> 8) | ((buttons & 0x00FF) << 8);
    int expect_jcrst;
    int started_xmove, started_ymove, last_x_pegged, last_y_pegged, count;
    char *bd_template = "bd_%c %4d";
    char bd_x[32] = "bd_x none";
    char bd_y[32] = "bd_y none";
    unsigned long long bd_write_time;

    if(ctrlr) {
        if(isSlaveMode)
            no_xmit = TRUE;
        if (!no_xmit)
            expected_rx = (buttons << 16) | ((x & 0xFF) << 8) | (y & 0xFF);
        bd_si_ctrl_setup(ctrlr, CTRL_BUTTON, bd_buttons, 0);
        bd_si_ctrl_setup(ctrlr, CTRL_X     , x,          0);
        bd_si_ctrl_setup(ctrlr, CTRL_Y     , y,          0);
        SIM_TIME(&bd_write_time);
        snprintf(bd_x, sizeof bd_x, bd_template, 'x', x);
        snprintf(bd_y, sizeof bd_y, bd_template, 'y', y);
    } else if (no_xmit) {
        lctrl.bd_write_time = bd_write_time;
    } else {
        expect_jcrst  = FALSE;
        last_x_pegged = FALSE;
        last_y_pegged = FALSE;
        if ( (buttons & CTRL_JSRST_BUTTONS) == CTRL_JSRST_BUTTONS) {
            expect_jcrst = TRUE;
            lctrl.target_x = lctrl.target_y = 0;
            snprintf(bd_x, sizeof bd_x, bd_template, 'x', 0);
            snprintf(bd_y, sizeof bd_y, bd_template, 'y', 0);
            started_xmove       = started_ymove    = TRUE;
            lctrl.inmotion_x    = lctrl.inmotion_y = TRUE;
            lctrl.xmove_timeout = lctrl.ymove_timeout = 0;
            lctrl.keep_x_idle   = lctrl.keep_y_idle   = 0;
            _TRACE(dsi, fprintf(LogFp, "\n\tSiSetupButtonTest: ctrlr 0:  Reset Joystick x/y"));
        } else {
            if ( x && !lctrl.inmotion_x && !lctrl.keep_x_idle) {
                lctrl.target_x = lctrl.last_x + x;
                if( lctrl.target_x > LCTRL_MAX_X ) {
                    lctrl.target_x = LCTRL_MAX_X;
                    count = LCTRL_MAX_X - lctrl.last_x;
                } else if ( lctrl.target_x < LCTRL_MIN_X ) {
                    lctrl.target_x = LCTRL_MIN_X;
                    count = lctrl.last_x - LCTRL_MIN_X;
                } else
                    count = (x >= 0) ? x : -x;
                lctrl.xmove_timeout = lctrl.ns_jsmove_1 * count;
                //bd_si_ctrl_setup(ctrlr, LCTRL_XMOVE, x, 0);
                snprintf(bd_x, sizeof bd_x, bd_template, 'x', x);
                started_xmove = lctrl.inmotion_x = TRUE;
                if( (lctrl.last_x >= LCTRL_MAX_X) || (lctrl.last_x <= LCTRL_MIN_X) )
                    last_x_pegged = TRUE;
                _TRACE(dsi, fprintf(LogFp,
                    "\n\tSiSetupButtonTest: ctrlr 0:  Started joystick X move:  \n\t\t"
                    "last_x %d  target %d  count %d  timeout %d  \n\t\t"
                    "ns_jsmove_1 %d  tPulse %d  tGlitch %d  jitter %d",
                    lctrl.last_x, lctrl.target_x, count, lctrl.xmove_timeout,
                    lctrl.ns_jsmove_1, lctrl.tPulse, lctrl.tGlitch, lctrl.jitter));
            } else {
                started_xmove = FALSE;
            }

            if ( y && !lctrl.inmotion_y && !lctrl.keep_y_idle ) {
                lctrl.target_y = lctrl.last_y + y;
                if( lctrl.target_y > LCTRL_MAX_Y ) {
                    lctrl.target_y = LCTRL_MAX_Y;
                    count = LCTRL_MAX_Y - lctrl.last_y;
                } else if ( lctrl.target_y < LCTRL_MIN_Y ) {
                    lctrl.target_y = LCTRL_MIN_Y;
                    count = lctrl.last_y - LCTRL_MIN_Y;
                } else
                    count = (y >= 0) ? y : -y;
                lctrl.ymove_timeout = lctrl.ns_jsmove_1 * count;
                //bd_si_ctrl_setup(ctrlr, LCTRL_YMOVE, y, 0);
                snprintf(bd_y, sizeof bd_y, bd_template, 'y', y);
                started_ymove = lctrl.inmotion_y = TRUE;
                if( (lctrl.last_y >= LCTRL_MAX_Y) || (lctrl.last_y <= LCTRL_MIN_Y) )
                    last_y_pegged = TRUE;
                _TRACE(dsi, fprintf(LogFp,
                    "\n\tSiSetupButtonTest: ctrlr 0:  Started joystick Y move:  \n\t\t"
                    "last_y %d  target %d  count %d  timeout %d  \n\t\t"
                    "ns_jsmove_1 %d  tPlus %d  tGlitch %d  jitter %d",
                    lctrl.last_y, lctrl.target_y, count, lctrl.ymove_timeout,
                    lctrl.ns_jsmove_1, lctrl.tPulse, lctrl.tGlitch, lctrl.jitter));
            } else {
                started_ymove = FALSE;
            }
        }
        if ( expect_jcrst || last_x_pegged || last_y_pegged ) {
            if (expect_jcrst) {   
                _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupButtonTest: lctrl:   before bd JCRST, wait for bd to sync with 0'd xmove,ymove"));
                bd_si_ctrl_setup(ctrlr, LCTRL_XMOVE, 0, 0);
                bd_si_ctrl_setup(ctrlr, LCTRL_YMOVE, 0, 0);
            } else {
                if ( last_x_pegged ) {   
                    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupButtonTest: lctrl:   Last x was pegged, stop xmove and wait for bd to sync"));
                    bd_si_ctrl_setup(ctrlr, LCTRL_XMOVE, 0, 0);
                }
                if ( last_y_pegged ) {   
                    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiSetupButtonTest: lctrl:   Last y was pegged, stop ymove and wait for bd to sync"));
                    bd_si_ctrl_setup(ctrlr, LCTRL_YMOVE, 0, 0);
                }
            }
            SiWait(lctrl.ns_jsmove_1*2);
        }
        if (started_xmove && !expect_jcrst) bd_si_ctrl_setup(ctrlr, LCTRL_XMOVE, x, 0);
        if (started_ymove && !expect_jcrst) bd_si_ctrl_setup(ctrlr, LCTRL_YMOVE, y, 0);
        bd_si_ctrl_setup(ctrlr, LCTRL_BUTTON, bd_buttons, 0);
        SIM_TIME(&bd_write_time);
        lctrl.bd_write_time = bd_write_time;
        if (started_xmove) {
            lctrl.xmove_start    = bd_write_time;
            lctrl.xmove_timeout += bd_write_time;
        }
        if (started_ymove) {
            lctrl.ymove_start    = bd_write_time;
            lctrl.ymove_timeout += bd_write_time;
        }
        expected_rx =   (((buttons & CTRL_BUTTON_MASK) | (expect_jcrst ? CTRL_JSRST_BIT:0)) << 16)
                      | ((lctrl.target_x & 0xFF) << 8) | (lctrl.target_y & 0xFF);
        _TRACE(dsi, fprintf(LogFp, "\n\tSiSetupButtonTest: ctrlr %d:   target_x %4d   last_x %4d   inmotion_x %4d   keep_x_idle %4llu",
                                     ctrlr, lctrl.target_x, lctrl.last_x, lctrl.inmotion_x, lctrl.keep_x_idle));

        _TRACE(dsi, fprintf(LogFp, "\n\tSiSetupButtonTest: ctrlr %d:   target_y %4d   last_y %4d   inmotion_y %4d   keep_y_idle %4llu",
                                     ctrlr, lctrl.target_y, lctrl.last_y, lctrl.inmotion_y, lctrl.keep_y_idle));
    }

    _TRACE(dsi, fprintf(LogFp, "\n\tSiSetupButtonTest: ctrlr %d:   %sbuttons %08x   arg_x %4d   arg_y %4d   %s   %s   expected_rx %08x   bd_write_time %llu",
                                 ctrlr, no_xmit?"no_xmit:  ":"", buttons, x, y, bd_x, bd_y, expected_rx, bd_write_time));

    tx_size = no_xmit ? 0 : 1;
    error = 0;

    if(isSlaveMode && ctrlr)
        rx_size = 0; // SiStartSlaveReceive and SiSlaveTest modify jctrl 1 tx/rx size's
    else
        rx_size = 4;

    setCtrlCmdData(&dma->w.ctrlr[i], 0xFF,     0, tx_size, rx_size, CtrlQueryButtons, 0);
    setCtrlCmdData(&dma->r.ctrlr[i], 0xFF, error, tx_size, rx_size, CtrlQueryButtons, expected_rx);

    SiSetupFailureTest (ctrlr, dma, failure, fail_param, ++cmd_count);

    // Min delay before read the result of setting the buttons via bd
    // is dependent on the LC button sampling rate.

    if (ctrlr==0 && !no_xmit) {

        // jc_clk  = sysclk/(1+jc_div)
        // jc_per  = sys_per*(1+jc_div)
        // but_per = but_rate ? (but_rate*1024)/jc_clk : 1/jc_clk
        // but_per = but_rate ? (but_rate*1024)*jc_per : jc_per
        // max but_rate is 63 and max jc_div is 127
        // max jc_per  = 16*(1+127) = 2048 (nanosec)
        // max but_per = (63*1024)*2048 = 132120576 = 0x07e00000 (nanosec)

        unsigned int jc_div, but_rate, jc_per, but_per, config, but_pers_to_delay;

        config   = IO_READ(SI_CONFIG_REG);
        jc_per   = getJcPeriod(config, &jc_div);
        but_rate = (config & SI_CONFIG_BUT_RATE_MASK)  >>  SI_CONFIG_BUT_RATE_SHIFT;
        but_per  = but_rate  ?  ((but_rate*1024)*jc_per)  :  jc_per;
        dma->min_time_till_readable = lctrl.bd_write_time + 2*but_per;
        dma->max_time_till_readable = lctrl.bd_write_time + 3*but_per;
        dma->button_period = but_per;
        but_pers_to_delay = dma->button_periods_to_delay ?
                                dma->button_periods_to_delay : 3;

        switch (dma->lc_but_wait) {
            case LcButWait_Compute:
                dma->dont_rqst_before =   lctrl.bd_write_time
                                        + but_per * but_pers_to_delay
                                        + dma->offset_from_computed_rqst_time;
                break;
            case LcButWait_UseDelayBeforeRqst:
                dma->dont_rqst_before =   lctrl.bd_write_time
                                        + dma->delay_before_rqst;
                break;
            case LcButWait_UseDontRqstBefore:
                break;
            case LcButWait_None:
                dma->dont_rqst_before = 0;
                break;
        }

        //##############################################################
        _TRACE(dsi, fprintf(LogFp, "\n\t%s: SiSetupButtonTest: test case %d: %s"
            "\n\t\tjc_div %u  but_rate %u  jc_per %u  but_per %u"
            "\n\t\tlctrl.bd_write_time     %llu"
            "\n\t\tmin_time_till_readable  %llu"
            "\n\t\tmax_time_till_readable  %llu"
            "\n\t\tlc_but_wait             %d"
            "\n\t\tdont_rqst_before        %llu"
            "\n\t\tdelay_before_rqst       %u"
            "\n\t\tbut_pers_to_delay       %u"
            "\n\t\toffset_from_computed    %d",
                dma->testname, dma->test_case_count, dma->description,
                jc_div, but_rate, jc_per, but_per, lctrl.bd_write_time,
                dma->min_time_till_readable, dma->max_time_till_readable,
                dma->lc_but_wait, dma->dont_rqst_before, dma->delay_before_rqst,
                but_pers_to_delay, dma->offset_from_computed_rqst_time
            ));

    }

    return ret;
}



static void
randomCtrlTestSetup(int             ctrlr,
                    SiDmaTestParam *dma,
                    CtrlCmdCode     cmd,
                    ForceFail        f,
                    int             fp)
{
    // sets up dma->w.ctrlr[i], dma->r.ctrlr[i], and ctrlr simulation
    // with random cmd parameters.
    // If cmd is CtrlRandomCmd, a random cmd type is selected
    // otherwise, the specified cmd type is used
    // If cmd is CtrlNoXmitRand, a random cmd with tx_size 0 is used.

    int no_xmit;

    switch ( cmd ) {
        case CtrlNoXmitStat:
            no_xmit = 1;
            cmd = CtrlQueryStatus;
            break;
        case CtrlNoXmitButt:
            no_xmit = 1;
            cmd = CtrlQueryButtons;
            break;
        case CtrlNoXmitRead:
            no_xmit = 1;
            cmd = CtrlRead;
            break;
        case CtrlNoXmitWrit:
            no_xmit = 1;
            cmd = CtrlWrite;
            break;
        case CtrlNoXmitRset:
            no_xmit = 1;
            cmd = CtrlReset;
            break;
        case CtrlNoXmitUsup:
            no_xmit = 1;
            cmd = CtrlJcUnsupCmd;
            break;
        case CtrlNoXmitRand:
            no_xmit = 1;
            cmd = CtrlRandomCmd;
            break;
        default:
        case CtrlQueryStatus:
        case CtrlQueryButtons:
        case CtrlRead:
        case CtrlWrite:
        case CtrlReset:
        case CtrlJcUnsupCmd:
            no_xmit = 0;
            break;
        case CtrlRandomCmd:
            if(isSlaveMode && ctrlr==0)
                no_xmit = 0;
            else
                no_xmit = (random() % 10) ? 0 : 1;
            break;
    }

    if (cmd == CtrlRandomCmd) {
        if (isSlaveMode && ctrlr==0)
            cmd = supportedCmd();
        else
            cmd = (random() % 10) ? supportedCmd() : CtrlJcUnsupCmd;
    }

    switch ( cmd ) {
        case CtrlQueryStatus:
            SiSetupStatusTest   (ctrlr, dma, type_L(),  type_H(), cstatus(), f, fp, no_xmit);
            break;
        case CtrlQueryButtons:
            SiSetupButtonTest   (ctrlr, dma, buttons(), jcount(),  jcount(), f, fp, no_xmit);
            break;
        case CtrlRead:
            SiSetupReadTest   (ctrlr, dma, read_addr(),  read_data(), f, fp, no_xmit);
            break;
        case CtrlWrite:
            SiSetupWriteTest   (ctrlr, dma, write_data(), f, fp, no_xmit);
            break;
        case CtrlReset:
            SiSetupCtrlResetTest(ctrlr, dma, type_L(),  type_H(), cstatus(), f, fp, no_xmit);
            break;
        case CtrlJcUnsupCmd:
            SiSetupUnsupCmdTest (ctrlr, dma, unsupportedCmd(), random(),     f, fp, no_xmit);
            break;
        default:
            if(isValidUnsupCmd(cmd)) {
                SiSetupUnsupCmdTest (ctrlr, dma, cmd, random(), f, fp, no_xmit);
                break;
            }
        case CtrlRandomCmd:
        case CtrlNoXmitStat:
        case CtrlNoXmitButt:
        case CtrlNoXmitRead:
        case CtrlNoXmitWrit:
        case CtrlNoXmitRset:
        case CtrlNoXmitUsup:
        case CtrlNoXmitRand:
            // prevent compiler warning, this shouldn't happen
            SiLogResult(-1, "randomCtrlTestSetup", "Internal error", ctrlr, cmd, f, fp);
            break;
    }
}



static int
SiJctrlSetReset(int ctrlr)
{
    // ctrlr == 0 means use JCRST in SI ctrl reg to reset all
    int ret;

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiJctrlSetReset:  Set Jctrl Reset: %d", ctrlr));

    if(ctrlr) {
        bd_si_ctrl_setup(ctrlr, CTRL_ENALE, 0, 0);
        if(ctrlr==1 && isSlaveMode)
            bd_si_ctrl_setup(MJCTRL, MJCTRL_ENALE, 0, 0);
        bd_si_ctrl_setup(ctrlr, CTRL_RESET, 1, 0);
    } else {
        bd_si_ctrl_setup(1, CTRL_ENALE, 0, 0);
        bd_si_ctrl_setup(2, CTRL_ENALE, 0, 0);
        bd_si_ctrl_setup(3, CTRL_ENALE, 0, 0);
        bd_si_ctrl_setup(MJCTRL, MJCTRL_ENALE, 0, 0);

        if ((ret = SiExtMemWrite(SI_CTRL_REG, 1, 0)) == -1)
            return SiLogResult(ret, "SiJctrlSetReset", "SiExtMemWrite", SI_CTRL_REG, 1, 0, 0);
        if ((ret = ExtMemReadMaskComp(SI_CTRL_REG, 1, 0, 1)) == -1)
            return SiLogResult(ret, "SiJctrlSetReset", "ExtMemReadMaskComp", SI_CTRL_REG, 1, 0, 1);
    }

    return 0;
}



static int
SiJctrlWaitReset(int ctrlr)
{
    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiJctrlWaitReset:  Wait for Jctrl Reset: %d", ctrlr));

    SiWait(jcrst_duration);

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiJctrlWaitReset:  Done waiting for Jctrl Reset: %d, SI_CTRL %08x", ctrlr, IO_READ(SI_CTRL_REG)));
    return 0;
}



static int
SiJctrlClearReset(int ctrlr)
{
    // ctrlr == 0 means use JCRST in SI ctrl reg to reset all
    int ret;

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiJctrlClearReset:  Clear Jctrl Reset: %d", ctrlr));

    if(ctrlr) {
        bd_si_ctrl_setup(ctrlr, CTRL_RESET, 0, 0);
        if(ctrlr==1 && isSlaveMode && isUseMJCTRL)
            bd_si_ctrl_setup(MJCTRL, MJCTRL_ENALE, 1, 0);
        else
            bd_si_ctrl_setup(ctrlr, CTRL_ENALE, 1, 0);
    } else {
        if ((ret = SiExtMemWrite(SI_CTRL_REG, 0, 0)) == -1)
            return SiLogResult(ret, "SiJctrlClearReset", "SiExtMemWrite", SI_CTRL_REG, 0, 0, 0);
        if ((ret = ExtMemReadMaskComp(SI_CTRL_REG, 0, 0, 1)) == -1)
            return SiLogResult(ret, "SiJctrlClearReset", "ExtMemReadMaskComp", SI_CTRL_REG, 0, 0, 1);
    }
    return 0;
}



static int
SiJctrlReset(int ctrlr)
{
    // ctrlr == 0 means use JCRST in SI ctrl reg to reset all
    int       ret = SiJctrlSetReset(ctrlr);
    if(!ret)  ret = SiJctrlWaitReset(ctrlr);
    return ret;
}


static int
SiJctrlResetAndClear(int ctrlr)
{
    // ctrlr == 0 means use JCRST in SI ctrl reg to reset all
    int ret           = SiJctrlReset(ctrlr);
    if(ret != -1) ret = SiJctrlClearReset(ctrlr);
    if(ret == -1)
        SiLogResult(ret, "SiJctrlResetAndClear", "", ctrlr, 0, 0, 0);
    return ret;
}



static void
SiSetJCtrlRespRand(int ctrlr_1, int ctrlr_2, int ctrlr_3)
{
    use_rsp_rand[1] = ctrlr_1;
    bd_si_ctrl_setup(1, CTRL_RSP_RAND , ctrlr_1, 0);
    use_rsp_rand[2] = ctrlr_2;
    bd_si_ctrl_setup(2, CTRL_RSP_RAND , ctrlr_2, 0);
    use_rsp_rand[3] = ctrlr_3;
    bd_si_ctrl_setup(3, CTRL_RSP_RAND , ctrlr_3, 0);
    use_rsp_rand_any = ctrlr_1 || ctrlr_2 || ctrlr_3;
    _TRACE(dsi,fprintf(DBGOUT, "\n\tSet JCtrlr response randomization:  j1 %d j2 %d j3 %d", ctrlr_1, ctrlr_2, ctrlr_3));
}

#if 0   /* not currently used */

static void
SiSetJCtrlRespEcho(int ctrlr_1, int ctrlr_2, int ctrlr_3)
{
    use_rsp_echo[1] = ctrlr_1;
    bd_si_ctrl_setup(1, CTRL_RSP_ECHO , ctrlr_1, 0);
    use_rsp_echo[2] = ctrlr_2;
    bd_si_ctrl_setup(2, CTRL_RSP_ECHO , ctrlr_2, 0);
    use_rsp_echo[3] = ctrlr_3;
    bd_si_ctrl_setup(3, CTRL_RSP_ECHO , ctrlr_3, 0);
    _TRACE(dsi,fprintf(DBGOUT, "\n\tSet JCtrlr response echo:  j1 %d j2 %d j3 %d", ctrlr_1, ctrlr_2, ctrlr_3));
}

#endif  /* not currently used */

static int
SiDefaults()
{
    int ret = 0;
    int i;
    unsigned int jc_div, jc_per, config_default, config;
    static   int not_first_time;
    unsigned int si_dma_addr64_bits = 0;
    unsigned int si_dma_mem64_bits  = 0;  // bits in size, not addr
    unsigned int si_dma_mem36_bits  = 0;

    if (!mem_size) {
        mem_info = BCP_MEM_INFO;
        mem_size = 1 << (mem_info & BCP_MEM_ADDR_MASK);
    }
    if(mem_size > SI_MAX_DMA_MEM64_SIZE)
        si_dma_mem64_size = SI_MAX_DMA_MEM64_SIZE;
    else
        si_dma_mem64_size = mem_size;

    si_dma_mem36_size = si_dma_mem64_size >> 1;

    si_dma_addr64_top = DDRRAM64_START + si_dma_mem64_size;
    si_dma_addr36_top = si_dma_mem36_size;

    if(si_dma_mem64_size < DDRRAM64_START) {
        for ( i = 31;  !((si_dma_mem64_size-1) & (1 << i));  --i )
            ; // just check each bit
        si_dma_mem64_bits = i+1;
        si_dma_addr64_mask = ((0xFFFFFFFF >> (32-si_dma_mem64_bits)) & 0xFFFFFFF8) | DDRRAM64_START;
    } else {
        for ( i = 31;  !((si_dma_addr64_top-1) & (1 << i));  --i )
            ; // just check each bit
        si_dma_addr64_bits = i+1;
        si_dma_addr64_mask = ((0xFFFFFFFF >> (32-si_dma_addr64_bits)) & 0xFFFFFFF8);
    }
    for ( i = 31;  !((si_dma_mem36_size-1) & (1 << i));  --i )
        ; // just check each bit
    si_dma_mem36_bits = i+1;
    si_dma_addr36_mask = (0xFFFFFFFF >> (32-si_dma_mem36_bits)) & 0xFFFFFFF8;

    if (!sysclk_period)
        ret = bcp_sysclk_period(&sysclk_period);

    // Set jc_div per sysclk to get 512 ns jc_clk period
    jc_div = ((512*1000)/sysclk_period) - 1; // sysclk_period is in ps
    config_default = (jc_div << SI_CONFIG_JC_DIV_SHIFT) | SI_CONFIG_SGL_ERR | SI_CONFIG_BUT_ENA;
    jc_per = getJcPeriod (config_default,0);

    if ( !not_first_time || (Dflags & (dsi)) )
        fprintf(DBGOUT,"\n\tSet SI test defaults"
                       "\n\t\tsysclk_period %u   jc_div %u   jc_per %u   config_default %08x"
                       "\n\t\tsi_ltd_mem_size   %08x   si_ltd_mem_start %08x"
                       "\n\t\tsi_dma_mem64_size %08x   %s %d   si_dma_addr64_top %08x  si_dma_addr64_mask %08x"
                       "\n\t\tsi_dma_mem36_size %08x   si_dma_mem36_bits %d   si_dma_addr36_top %08x  si_dma_addr36_mask %08x"
                       , sysclk_period, jc_div, jc_per, config_default
                       , si_ltd_mem_size, si_ltd_mem_start
                       , si_dma_mem64_size
                       , ((si_dma_mem64_size < DDRRAM64_START)?"si_dma_mem64_bits":"si_dma_addr64_bits")
                       , ((si_dma_mem64_size < DDRRAM64_START)? si_dma_mem64_bits : si_dma_addr64_bits )
                       , si_dma_addr64_top, si_dma_addr64_mask
                       , si_dma_mem36_size, si_dma_mem36_bits, si_dma_addr36_top, si_dma_addr36_mask);

    jcrst_duration = MIN_JCRST_DURATION;

    if(IO_READ(SI_STATUS_REG) & SI_STATUS_DMA_BUSY) {
        SiJctrlSetReset(0);
    }

    config = IO_READ(SI_CTRL_REG);
    if (config & 1) {
        _TRACE(dsi,fprintf(DBGOUT,"\n\tJCRST found to be set:  config/ctrl %08x", config));
        SiJctrlWaitReset(0);
        SiJctrlClearReset(0);
    }

    _TRACE(dsi,fprintf(DBGOUT,"\n\tSet but_rate to 0 to sample once per jc_clk"));
    setLctrlButRate(0);
    IO_WRITE( SI_CONFIG_REG, config_default);
    IO_WRITE( SI_CTRL_REG,   0x00000000);
    ret |= SiClearStatus();

    SiSetInterruptMask(1);

    isSmJCResetWithCmd     = FALSE;
    SmJCResetWithCmdDelay  = DEF_SmJCResetWithCmdDelay;
    isSmJCResetDurCmd      = FALSE;
    SmJCResetDurCmdDelay   = isUseMJCTRL ? DEF_SmMJCResetDurCmdDelay : DEF_SmJCResetDurCmdDelay;
    isSmJCResetBeforeRcv   = FALSE;
    isSmPollTilJCResetDone = FALSE;
    isSmCheckRcvNoRqstCmd  = FALSE;
    isSmTruncCmd           = FALSE;
    isSmRspCollision       = FALSE;
    isSmCmdFrameErr        = FALSE;
    SmCmdFrameErr          = DEF_SmCmdFrameErr;
    SmRspCollision         = DEF_SmRspCollision;


    ret |= SiInitCtrlSim(1,1,1,1);

    no_random_jsrst = FALSE;
    not_first_time  = TRUE;

    return ret;
}





static int
SiSetupDmaBuf(SiDmaParam w)
{
    int ret1 = 0, ret2 = 0, res;
    unsigned int lc_b0t3, j1_b0t3, j2_b0t3, j3_b0t3;
    unsigned int buf_addr, lgbbs, ugbbs, lgb_addr, ugb_addr, fill_value;

    // write a pattern to dma buf guard band
    buf_addr    = SiAlignedDmaBufAddr  (w.dram_addr);
    lgbbs       = SiLowerGuardBandBytes(buf_addr, w.guard_band_bytes);
    ugbbs       = SiUpperGuardBandBytes(buf_addr, w.guard_band_bytes);
    lgb_addr    = buf_addr - lgbbs;
    ugb_addr    = buf_addr + SI_DMA_XFER_BYTES;
    fill_value  = w.fill_value;

    if(lgbbs && (ret1 = SiBDMemWriteRead(lgb_addr, fill_value, 0, lgbbs, GUARD_BAND_INC_PAT)))
        SiLogResult(ret1, "SiSetupDmaBuf", "SiBDMemWriteRead", lgb_addr, w.fill_value, lgbbs, GUARD_BAND_INC_PAT);
    fill_value += (lgbbs/4 + SI_DMA_XFER_BYTES/4) * GUARD_BAND_INC_PAT;
    if(ugbbs && (ret2 = SiBDMemWriteRead(ugb_addr, fill_value, 0, ugbbs, GUARD_BAND_INC_PAT)))
        SiLogResult(ret2, "SiSetupDmaBuf", "SiBDMemWriteRead", ugb_addr, w.fill_value, ugbbs, GUARD_BAND_INC_PAT);

    // fill dma buf per info in SiDmaParam b

    lc_b0t3 = (w.LC.block_code << 24) | (w.LC.tx_size << 16) |  (((w.LC.error << 3) | w.LC.rx_size) << 8) | (w.LC.cmd);
    j1_b0t3 = (w.J1.block_code << 24) | (w.J1.tx_size << 16) |  (((w.J1.error << 3) | w.J1.rx_size) << 8) | (w.J1.cmd);
    j2_b0t3 = (w.J2.block_code << 24) | (w.J2.tx_size << 16) |  (((w.J2.error << 3) | w.J2.rx_size) << 8) | (w.J2.cmd);
    j3_b0t3 = (w.J3.block_code << 24) | (w.J3.tx_size << 16) |  (((w.J3.error << 3) | w.J3.rx_size) << 8) | (w.J3.cmd);

    if ((res = SiBDMemWrite(buf_addr,    lc_b0t3, 0)) == -1)
        return SiLogResult(res, "SiSetupDmaBuf", "SiBDMemWrite", buf_addr, lc_b0t3, 0, 0);
    if ((res = SiBDMemWrite(buf_addr+=4, w.LC.tx_rx_buf, 0)) == -1)
        return SiLogResult(res, "SiSetupDmaBuf", "SiBDMemWrite", buf_addr, w.LC.tx_rx_buf, 0, 0);

    if ((res = SiBDMemWrite(buf_addr+=4, j1_b0t3, 0)) == -1)
        return SiLogResult(res, "SiSetupDmaBuf", "SiBDMemWrite", buf_addr, j1_b0t3, 0, 0);
    if ((res = SiBDMemWrite(buf_addr+=4, w.J1.tx_rx_buf, 0)) == -1)
        return SiLogResult(res, "SiSetupDmaBuf", "SiBDMemWrite", buf_addr, w.J1.tx_rx_buf, 0, 0);

    if ((res = SiBDMemWrite(buf_addr+=4, j2_b0t3, 0)) == -1)
        return SiLogResult(res, "SiSetupDmaBuf", "SiBDMemWrite", buf_addr, j2_b0t3, 0, 0);
    if ((res = SiBDMemWrite(buf_addr+=4, w.J2.tx_rx_buf, 0)) == -1)
        return SiLogResult(res, "SiSetupDmaBuf", "SiBDMemWrite", buf_addr, w.J2.tx_rx_buf, 0, 0);

    if ((res = SiBDMemWrite(buf_addr+=4, j3_b0t3, 0)) == -1)
        return SiLogResult(res, "SiSetupDmaBuf", "SiBDMemWrite", buf_addr, j3_b0t3, 0, 0);
    if ((res = SiBDMemWrite(buf_addr+=4, w.J3.tx_rx_buf, 0)) == -1)
        return SiLogResult(res, "SiSetupDmaBuf", "SiBDMemWrite", buf_addr, w.J3.tx_rx_buf, 0, 0);

    return ((ret1||ret2) ?  -1 : 0);
}




static int
SiExtractDmaBufFields(int buf_dram_addr, SiCtrlBufParams ctrlr[4])
{
    // The results are returned in ctrlr[4]
    int ret;
    int buf_addr = SiAlignedDmaBufAddr(buf_dram_addr);
    int tmp;
    char bd_msg[] = "SiExtractDmaBufFields: Compare BD_IO_READ to IO_READ";

    int lc_b0t3 = IO_READ(buf_addr +  0);
    int lc_b4t7 = IO_READ(buf_addr +  4);
    int j1_b0t3 = IO_READ(buf_addr +  8);
    int j1_b4t7 = IO_READ(buf_addr + 12);
    int j2_b0t3 = IO_READ(buf_addr + 16);
    int j2_b4t7 = IO_READ(buf_addr + 20);
    int j3_b0t3 = IO_READ(buf_addr + 24);
    int j3_b4t7 = IO_READ(buf_addr + 28);

    if ((tmp=BD_IO_READ(buf_addr +  0)) != lc_b0t3) {ret=-1;SiLogResult(-1, bd_msg, "lc_b0t3", buf_addr, buf_addr+ 0, lc_b0t3, tmp);}
    if ((tmp=BD_IO_READ(buf_addr +  4)) != lc_b4t7) {ret=-1;SiLogResult(-1, bd_msg, "lc_b4t7", buf_addr, buf_addr+ 4, lc_b4t7, tmp);}
    if ((tmp=BD_IO_READ(buf_addr +  8)) != j1_b0t3) {ret=-1;SiLogResult(-1, bd_msg, "j1_b0t3", buf_addr, buf_addr+ 8, j1_b0t3, tmp);}
    if ((tmp=BD_IO_READ(buf_addr + 12)) != j1_b4t7) {ret=-1;SiLogResult(-1, bd_msg, "j1_b4t7", buf_addr, buf_addr+12, j1_b4t7, tmp);}
    if ((tmp=BD_IO_READ(buf_addr + 16)) != j2_b0t3) {ret=-1;SiLogResult(-1, bd_msg, "j2_b0t3", buf_addr, buf_addr+16, j2_b0t3, tmp);}
    if ((tmp=BD_IO_READ(buf_addr + 20)) != j2_b4t7) {ret=-1;SiLogResult(-1, bd_msg, "j2_b4t7", buf_addr, buf_addr+20, j2_b4t7, tmp);}
    if ((tmp=BD_IO_READ(buf_addr + 24)) != j3_b0t3) {ret=-1;SiLogResult(-1, bd_msg, "j3_b0t3", buf_addr, buf_addr+24, j3_b0t3, tmp);}
    if ((tmp=BD_IO_READ(buf_addr + 28)) != j3_b4t7) {ret=-1;SiLogResult(-1, bd_msg, "j3_b4t7", buf_addr, buf_addr+28, j3_b4t7, tmp);}

    LC.block_code = (lc_b0t3 >> 24) & 0x000000ff;
    LC.tx_size    = (lc_b0t3 >> 16) & 0x000000ff;  // really only 6 lsbs, but upper bits should not be set.
    LC.error      = (lc_b0t3 >> 11) & 0x0000001f;
    LC.rx_size    = (lc_b0t3 >>  8) & 0x00000007;
    LC.cmd        =  lc_b0t3        & 0x000000ff;
    LC.tx_rx_buf  =  lc_b4t7;

    J1.block_code = (j1_b0t3 >> 24) & 0x000000ff;
    J1.tx_size    = (j1_b0t3 >> 16) & 0x000000ff;
    J1.error      = (j1_b0t3 >> 11) & 0x0000001f;
    J1.rx_size    = (j1_b0t3 >>  8) & 0x00000007;
    J1.cmd        =  j1_b0t3        & 0x000000ff;
    J1.tx_rx_buf  =  j1_b4t7;

    J2.block_code = (j2_b0t3 >> 24) & 0x000000ff;
    J2.tx_size    = (j2_b0t3 >> 16) & 0x000000ff;
    J2.error      = (j2_b0t3 >> 11) & 0x0000001f;
    J2.rx_size    = (j2_b0t3 >>  8) & 0x00000007;
    J2.cmd        =  j2_b0t3        & 0x000000ff;
    J2.tx_rx_buf  =  j2_b4t7;

    J3.block_code = (j3_b0t3 >> 24) & 0x000000ff;
    J3.tx_size    = (j3_b0t3 >> 16) & 0x000000ff;
    J3.error      = (j3_b0t3 >> 11) & 0x0000001f;
    J3.rx_size    = (j3_b0t3 >>  8) & 0x00000007;
    J3.cmd        =  j3_b0t3        & 0x000000ff;
    J3.tx_rx_buf  =  j3_b4t7;

    _TRACE(dsi,
        fprintf(DBGOUT, "\n\tSiExtractDmaBufFields:\n\t  dram_addr %08x  "
                        "\n\t\tlc_b0t3 %08x  lc_b4t7 %08x  "
                        "\n\t\tj1_b0t3 %08x  j1_b4t7 %08x  "
                        "\n\t\tj2_b0t3 %08x  j2_b4t7 %08x  "
                        "\n\t\tj3_b0t3 %08x  j3_b4t7 %08x  ",
            buf_dram_addr, lc_b0t3, lc_b4t7, j1_b0t3, j1_b4t7, j2_b0t3, j2_b4t7, j3_b0t3, j3_b4t7));

    _TRACE(dsi,
        fprintf(DBGOUT, "\n\tlc:  block_code: %08x   error: %08x   tx_size: %08x   rx_size: %08x   "
                                                    "cmd: %08x   tx_rx_buf: %08x",
            LC.block_code, LC.error, LC.tx_size, LC.rx_size, LC.cmd, LC.tx_rx_buf));

    _TRACE(dsi,
        fprintf(DBGOUT, "\n\tj1:  block_code: %08x   error: %08x   tx_size: %08x   rx_size: %08x   "
                                                    "cmd: %08x   tx_rx_buf: %08x",
            J1.block_code, J1.error, J1.tx_size, J1.rx_size, J1.cmd, J1.tx_rx_buf));

    _TRACE(dsi,
        fprintf(DBGOUT, "\n\tj2:  block_code: %08x   error: %08x   tx_size: %08x   rx_size: %08x   "
                                                    "cmd: %08x   tx_rx_buf: %08x",
            J2.block_code, J2.error, J2.tx_size, J2.rx_size, J2.cmd, J2.tx_rx_buf));

    _TRACE(dsi,
        fprintf(DBGOUT, "\n\tj3:  block_code: %08x   error: %08x   tx_size: %08x   rx_size: %08x   "
                                                    "cmd: %08x   tx_rx_buf: %08x",
            J3.block_code, J3.error, J3.tx_size, J3.rx_size, J3.cmd, J3.tx_rx_buf));

    return ret;
}


static int
SiProcessLctrlJmove( SiDmaTestParam *dma, unsigned int *rxbuf_mask )
{
    int ret = 0;
    int cur_x, cur_y;
    unsigned int rx_buf = dma->result[0].tx_rx_buf;


    //#####  X  ######//
    if ( dma->w.timeout.start > lctrl.xmove_timeout )
        *rxbuf_mask |= 0x0000FF00;

    cur_x = (rx_buf & 0x0000FF00) >> 8;
    if ( cur_x & 0x80 ) cur_x |= 0xFFFFFF00;

    if (!lctrl.inmotion_x) {
        if ( lctrl.last_x_known && cur_x != lctrl.last_x )
            ret = SiLogResult(-1, "SiProcessLctrlJmove", "lctrl x not supposed to be in motion but it changed ! ",
                                  lctrl.target_x, lctrl.last_x, cur_x, rx_buf);
        else if ( lctrl.keep_x_idle  &&  dma->w.timeout.start > lctrl.keep_x_idle ) {
                lctrl.keep_x_idle = 0;
                _TRACE(dsi,fprintf(DBGOUT, "\n\tSiProcessLctrlJmove:  lctrl x stopped moving as expected:   target %4d   prev %4d   cur %4d",
                            lctrl.target_x, lctrl.last_x, cur_x));
        }
    } else if (cur_x == lctrl.target_x) {
        lctrl.inmotion_x = FALSE;
        lctrl.keep_x_idle = dma->r.timeout.end + lctrl.ns_jsmove_1;
        _TRACE(dsi,fprintf(DBGOUT, "\n\tSiProcessLctrlJmove:  lctrl x reached:   target %4d   prev %4d   cur %4d   keep_x_idle %llu",
                    lctrl.target_x, lctrl.last_x, cur_x, lctrl.keep_x_idle));
    } else if ( lctrl.last_x_known ) {
        if ( cur_x == lctrl.last_x ) {
            _TRACE(dsi,fprintf(DBGOUT, "\n\tSiProcessLctrlJmove:  lctrl x not getting any closer:   target %4d   prev %4d   cur %4d",
                        lctrl.target_x, lctrl.last_x, cur_x ));
            ret = SiLogResult(-1, "SiProcessLctrlJmove", "lctrl x not getting any closer ! ",
                                lctrl.target_x, lctrl.last_x, cur_x, rx_buf);
        } else  if( (lctrl.target_x >= lctrl.last_x && cur_x < lctrl.last_x) ||
                    (lctrl.target_x <= lctrl.last_x && cur_x > lctrl.last_x)    ) {
            _TRACE(dsi,fprintf(DBGOUT, "\n\tSiProcessLctrlJmove:  lctrl x going wrong way:   target %4d   prev %4d   cur %4d",
                        lctrl.target_x, lctrl.last_x, cur_x     ));
            ret = SiLogResult(-1, "SiProcessLctrlJmove", "lctrl x going wrong way ! ",
                                lctrl.target_x, lctrl.last_x, cur_x, rx_buf);
        } else  if( (lctrl.target_x >= lctrl.last_x && cur_x > lctrl.target_x) ||
                    (lctrl.target_x <= lctrl.last_x && cur_x < lctrl.target_x)    ) {
            _TRACE(dsi,fprintf(DBGOUT, "\n\tSiProcessLctrlJmove:  lctrl x went past:   target %4d   prev %4d   cur %4d",
                        lctrl.target_x, lctrl.last_x, cur_x ));
            ret = SiLogResult(-1, "SiProcessLctrlJmove", "lctrl x went past target ! ",
                                lctrl.target_x, lctrl.last_x, cur_x, rx_buf);
        }
    }
    lctrl.last_x = cur_x;
    lctrl.last_x_known = TRUE;

    //#####  Y  ######//
    if ( dma->w.timeout.start > lctrl.ymove_timeout )
        *rxbuf_mask |= 0x000000FF;

    cur_y = (rx_buf & 0x000000FF);
    if ( cur_y & 0x80 ) cur_y |= 0xFFFFFF00;

    if (!lctrl.inmotion_y) {
        if ( lctrl.last_y_known && cur_y != lctrl.last_y )
            ret = SiLogResult(-1, "SiProcessLctrlJmove", "lctrl y not supposed to be in motion but it changed ! ",
                                  lctrl.target_y, lctrl.last_y, cur_y, rx_buf);
        else if ( lctrl.keep_y_idle  &&  dma->w.timeout.start > lctrl.keep_y_idle ) {
                lctrl.keep_y_idle = 0;
                _TRACE(dsi,fprintf(DBGOUT, "\n\tSiProcessLctrlJmove:  lctrl y stopped moving as expected:   target %4d   prev %4d   cur %4d",
                            lctrl.target_y, lctrl.last_y, cur_y));
        }
    } else if (cur_y == lctrl.target_y) {
        lctrl.inmotion_y = FALSE;
        lctrl.keep_y_idle = dma->r.timeout.end + lctrl.ns_jsmove_1;
        _TRACE(dsi,fprintf(DBGOUT, "\n\tSiProcessLctrlJmove:  lctrl y reached:   target %4d   prev %4d   cur %4d   keep_y_idle %llu",
                    lctrl.target_y, lctrl.last_y, cur_y, lctrl.keep_y_idle));
    } else if (lctrl.last_y_known) {
        if ( cur_y == lctrl.last_y ) {
            _TRACE(dsi,fprintf(DBGOUT, "\n\tSiProcessLctrlJmove:  lctrl y not getting any closer:   target %4d   prev %4d   cur %4d",
                        lctrl.target_y, lctrl.last_y, cur_y ));
            ret = SiLogResult(-1, "SiProcessLctrlJmove", "lctrl y not getting any closer ! ",
                                lctrl.target_y, lctrl.last_y, cur_y, rx_buf);
        } else  if( (lctrl.target_y >= lctrl.last_y && cur_y < lctrl.last_y) ||
                    (lctrl.target_y <= lctrl.last_y && cur_y > lctrl.last_y)    ) {
            _TRACE(dsi,fprintf(DBGOUT, "\n\tSiProcessLctrlJmove:  lctrl y going wrong way:   target %4d   prev %4d   cur %4d",
                        lctrl.target_y, lctrl.last_y, cur_y ));
            ret = SiLogResult(-1, "SiProcessLctrlJmove", "lctrl y going wrong way ! ",
                                lctrl.target_y, lctrl.last_y, cur_y, rx_buf);
        } else  if( (lctrl.target_y >= lctrl.last_y && cur_y > lctrl.target_y) ||
                    (lctrl.target_y <= lctrl.last_y && cur_y < lctrl.target_y)    ) {
            _TRACE(dsi,fprintf(DBGOUT, "\n\tSiProcessLctrlJmove:  lctrl y went past:   target %4d   prev %4d   cur %4d",
                        lctrl.target_y, lctrl.last_y, cur_y ));
            ret = SiLogResult(-1, "SiProcessLctrlJmove", "lctrl y went past target ! ",
                                lctrl.target_y, lctrl.last_y, cur_y, rx_buf);
        }
    }
    lctrl.last_y = cur_y;
    lctrl.last_y_known = TRUE;

    if (ret && !doing_ctrl_sim_init) {
        if(!dma->delayAfterDone)
            SiWait(JCTRL_DELAY_AFTER_DONE);
        SiInitCtrlSim(1,0,0,0);
    }

    return ret;
}



static int
SiCmpCtrlBufParams(SiDmaTestParam *dma)
{
    // Compare the expected SI buff values in ctrlr[4] with the values in result[4]
    // result[4] is filled in from the raw buffer by SiExtractDmaBufFields()
    int i, ret = 0;
    int ctrl_fail = 0;
    int ctrl_fail_expected = 0;
    unsigned int rxbuf_mask;
    SiCtrlBufParams *ctrlr         = dma->r.ctrlr;
    SiCtrlBufParams *result        = dma->result;
    ExpectedFailure  expected_fail = dma->r.expected_failure;

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams:  expected values:"));

    _TRACE(dsi, fprintf(DBGOUT, "\n\tlc:  block_code: %08x   error: %08x   tx_size: %08x   rx_size: %08x   "
                                                    "cmd: %08x   tx_rx_buf: %08x",
                        LC.block_code, LC.error, LC.tx_size, LC.rx_size, LC.cmd, LC.tx_rx_buf));

    _TRACE(dsi, fprintf(DBGOUT, "\n\tj1:  block_code: %08x   error: %08x   tx_size: %08x   rx_size: %08x   "
                                                    "cmd: %08x   tx_rx_buf: %08x",
                        J1.block_code, J1.error, J1.tx_size, J1.rx_size, J1.cmd, J1.tx_rx_buf));

    _TRACE(dsi, fprintf(DBGOUT, "\n\tj2:  block_code: %08x   error: %08x   tx_size: %08x   rx_size: %08x   "
                                                    "cmd: %08x   tx_rx_buf: %08x",
                        J2.block_code, J2.error, J2.tx_size, J2.rx_size, J2.cmd, J2.tx_rx_buf));

    _TRACE(dsi, fprintf(DBGOUT, "\n\tj3:  block_code: %08x   error: %08x   tx_size: %08x   rx_size: %08x   "
                                                    "cmd: %08x   tx_rx_buf: %08x",
                        J3.block_code, J3.error, J3.tx_size, J3.rx_size, J3.cmd, J3.tx_rx_buf));

    for (i = 0;  i < 4;  i++) {
        int ctrl_mask =  1 << i;
        if ( result[i].block_code != ctrlr[i].block_code ) {
            fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams:  Error:  %s block code (%08x) doesn't match expected (%08x)",
                            ctrlr_name[i], result[i].block_code, ctrlr[i].block_code);
            ctrl_fail |= ctrl_mask;
        }
        if ( result[i].error != ctrlr[i].error
                && !(isSmPollTilJCResetDone && (result[1].error & CTRL_ERR_CTLR_RESET)) ) {
            fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams:  Error:  %s error bits (%08x) doesn't match expected (%08x)",
                            ctrlr_name[i], result[i].error, ctrlr[i].error);
            if(i && result[i].tx_size && !isSlaveMode) {
                int rx_size = cmdRxSize(ctrlr[i].cmd);
                int tx_size = cmdTxSize(ctrlr[i].cmd);
                if (   ctrlr[i].rx_size != rx_size
                    || (ctrlr[i].tx_size && ctrlr[i].tx_size != tx_size) ) {
                    fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams:  Ok that %s error bits don't match if there is a different error", ctrlr_name[i]);
                    if ( !result[i].error )
                        expected_fail |= ExpectedFail_ctrl_0_any_fail  << i;
                } else
                    ctrl_fail |= ctrl_mask;
            } else
                ctrl_fail |= ctrl_mask;
        }
        if ( result[i].tx_size != (ctrlr[i].tx_size & 0x3F) ) {
            fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams:  Error:  %s tx size (%08x) doesn't match expected (%08x)",
                            ctrlr_name[i], result[i].tx_size, ctrlr[i].tx_size);
            ctrl_fail |= ctrl_mask;
        }
        if ( result[i].rx_size != (ctrlr[i].rx_size & 7)
             && !(i==1 && isSlaveMode && result[1].error)) {
            fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams:  Error:  %s rx size (%08x) doesn't match expected (%08x)",
                            ctrlr_name[i], result[i].rx_size, ctrlr[i].rx_size);
            ctrl_fail |= ctrl_mask;
        }
        if ( result[i].cmd != ctrlr[i].cmd
             && !(i==1 && isSlaveMode && result[1].error)) {
            fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams:  Error:  %s command (%08x) doesn't match expected (%08x)",
                            ctrlr_name[i], result[i].cmd, ctrlr[i].cmd);
            ctrl_fail |= ctrl_mask;
        }

        rxbuf_mask = 0;
        if (i || result[i].cmd != CtrlQueryButtons)
            rxbuf_mask = 0xFFFFFFFF;
        else if (    !result[0].error
                  && !ctrlr[0].tx_size==0
                  && !(isSlaveMode && (result[1].error & CTRL_ERR_CTLR_RESET))) {
            rxbuf_mask = 0xFFFF0000;
            ret = SiProcessLctrlJmove( dma, &rxbuf_mask );
        }

        if (    !result[i].error
             && !(expected_fail & (ExpectedFail_ctrl_0_tx_rx_buf_or_not << i))
             && !(i==0 && ctrlr[0].tx_size==0)
             && !(isSlaveMode && i==1)
             && !(isSlaveMode && (result[1].error & CTRL_ERR_CTLR_RESET))
             && (result[i].tx_rx_buf & rxbuf_mask) != (ctrlr[i].tx_rx_buf & rxbuf_mask) ) {
            fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams:  Error:  %s tx/rx buf (%08x) doesn't match expected (%08x)",
                            ctrlr_name[i], result[i].tx_rx_buf & rxbuf_mask, ctrlr[i].tx_rx_buf & rxbuf_mask);
            if (expected_fail & (ExpectedFail_ctrl_0_tx_rx_buf << i)) {
                _TRACE(dsi, fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams: ctrlr %d:  failure was expected", i));
            } else
                ctrl_fail |= ctrl_mask;
        }

        if ( (expected_fail & (ExpectedFail_ctrl_0_any_fail  << i)) ) {
            if ( ctrl_fail | ctrl_fail_expected) {
                _TRACE(dsi, fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams: ctrlr %d:  got expected failure", i));
                ctrl_fail &= ~ctrl_mask; ctrl_fail_expected |= ctrl_mask;
            } else {
                fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams: ctrlr %d:  did not get expected failure %#x", i, expected_fail);
                ret = -1;
            }
        }

        if(!isSlaveMode && i && !result[i].error && ctrlr[i].tx_size &&
                (ctrlr[i].cmd == CtrlWrite || ctrlr[i].cmd == CtrlRead) ) {
            u8 rb[36];
            int j;
            if( bd_si_ctrl_rd_pkd( i, CTRL_RX_DATA_0_7, rb, 8 ) ||
                    bd_si_ctrl_rd_pkd( i, CTRL_RX_DATA_8_35, &rb[8], 28 ))     {
                fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams: ctrlr %d: error getting data received by model via jctrl bd", i);
                ret = -1;
            }
            if (ctrlr[i].cmd == CtrlWrite) {
                _TRACE(dsi, fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams: ctrlr %d: write cmd data xmitted to/received by model\n\t\t", i));
                for(j=1; j<34; ++j) {
                    u8 wd = (j<4) ? write_cmd_data[i][j] : write_cmd_data[i][4];
                    _TRACE(dsi, fprintf(DBGOUT, "%s%02x:%02x", j%16 ? " ":"\n\t\t", wd, rb[j]));
                }
                for(j=1; j<34; ++j) {
                    u8 wd = (j<4) ? write_cmd_data[i][j] : write_cmd_data[i][4];
                    if(rb[j] != wd) {
                        fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams: ctrlr %d: miscompare between write cmd data[%d] xmitted to /received by model", i, j);
                        ret = -1;
                        break;
                    }
                }
            } else if (ctrlr[i].cmd == CtrlRead) {
                _TRACE(dsi, fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams: ctrlr %d: read cmd data xmitted to/received by model\n\t\t", i));
                for(j=0; j<3; ++j) {
                    u8 wd = read_cmd_xmit_data[i][j];
                    _TRACE(dsi, fprintf(DBGOUT, "%s%02x:%02x", j%16 ? " ":"\n\t\t", wd, rb[j]));
                }
                for(j=0; j<3; ++j) {
                    u8 wd = read_cmd_xmit_data[i][j];
                    if(rb[j] != wd) {
                        fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams: ctrlr %d: miscompare between read cmd data[%d] xmitted to/received by model", i, j);
                        ret = -1;
                        break;
                    }
                }
            }
        }
    }

    if (expected_fail & ExpectedFail_any_ctrl_fail) {
        if ( ctrl_fail | ctrl_fail_expected) {
            _TRACE(dsi, fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams:  got expected \"any ctrlr failure\" %#x  ctrl_fail %04x  ctrl_fail_expected %04x", expected_fail, ctrl_fail, ctrl_fail_expected));
        } else {
            fprintf(DBGOUT, "\n\tSiCmpCtrlBufParams:  did not get expected \"any ctrlr failure\"");
            ret = -1;
        }
    } else if (ctrl_fail)
        ret = -1;

    return ret;
}



static int
SiCheckGuardBand(SiDmaParam *b)
{
    int ret = 0;
    unsigned int r, a, buf_addr, lgbbs, ugbbs, lgb_addr, ugb_addr, fill_value;

    buf_addr    = SiAlignedDmaBufAddr  (b->dram_addr);
    lgbbs       = SiLowerGuardBandBytes(buf_addr, b->guard_band_bytes);
    ugbbs       = SiUpperGuardBandBytes(buf_addr, b->guard_band_bytes);
    lgb_addr    = buf_addr - lgbbs;
    ugb_addr    = buf_addr + SI_DMA_XFER_BYTES;
    fill_value  = b->fill_value;

    for (a = lgb_addr;
         ret == 0 && a < buf_addr;
         a += 4, fill_value += GUARD_BAND_INC_PAT) {
        if ( (r=IO_READ(a)) != fill_value ) {
            fprintf(DBGOUT, "\n\tSiCheckGuardBand:  Error:  lower guard band content (%0x8) doesn't match expected (%08x)",
                            r, fill_value);
            ret = -1;
        }
    }

    for (a = ugb_addr, fill_value += (SI_DMA_XFER_BYTES/4) * GUARD_BAND_INC_PAT;
         ret == 0 && a < ugb_addr + ugbbs;
         a += 4, fill_value += GUARD_BAND_INC_PAT) {
        if ( (r=IO_READ(a)) != fill_value ) {
            fprintf(DBGOUT, "\n\tSiCheckGuardBand:  Error:  upper guard band content (%0x8) doesn't match expected (%08x)",
                            r, fill_value);
            ret = -1;
        }
    }

    return ret;
}



static int
SiDmaCheckRead(SiDmaTestParam *dma)
{
    // waits for DMA to complete
    // cmp to the expected data per info in dma->r
    // returs 0 for no fail, 1 for expected fail, or -1 for unexpected fail
    // dma->result[i] will be updated per the fields in the returned buffer

    int ret, ret2, ret3 = 0;
    int i, init[4];
    SiDmaParam *r = &dma->r;

    if ((ret = SiDmaWait( Dir_To, r->dram_addr, &r->timeout, r->expected_failure)))
        return SiLogResult(ret, "SiDmaCheckRead", "SiDmaWait",
                  Dir_To, r->dram_addr, DEFAULT_DMA_TIMEOUT, r->expected_failure);

    if ((ret = SiCheckGuardBand(&dma->r)))
        SiLogResult(ret, "SiDmaCheckRead", "SiCheckGuardBand", r->dram_addr, 0, 0, 0);

    bcp_check_9th(1, 0, 0, 0);
    SiExtractDmaBufFields(r->dram_addr, dma->result);

    if(dma->delayAfterDone)
        SiWait(dma->delayAfterDone);

    ret2 = SiCmpCtrlBufParams(dma);
    bcp_check_9th(0, 0, 0, 0);

    for (i=1; i<4; ++i) {
        int rx_size = cmdRxSize(dma->w.ctrlr[i].cmd);
        int tx_size = cmdTxSize(dma->w.ctrlr[i].cmd);
        init[i] = 0;
        if(isSlaveMode) continue;
        if (    dma->w.ctrlr[i].rx_size != rx_size
             || (dma->w.ctrlr[i].tx_size && dma->w.ctrlr[i].tx_size != tx_size) ) {
            init[i] = 1;
        }
    }

    if ( dma->result[0].error & (CTRL_ERR_CTLR_RESET || dma->result[0].cmd==CtrlReset) )
        init[0] = 1;
    else
        init[0] = 0;

    if ( init[0] || init[1] || init[2] || init[3] ) {
        if(!dma->delayAfterDone)
            SiWait(JCTRL_DELAY_AFTER_DONE);
        if(!doing_ctrl_sim_init)
            ret3 = SiInitCtrlSim (init[0], init[1], init[2], init[3]);
    }

    return (ret == -1) ? ret : (ret3 == -1) ? ret3 : ret2;
}



static int
SiDmaStartRead(SiDmaTestParam *dma)
{
    int ret;
    SiDmaParam *r   = &dma->r;

    // write a pattern to buffer (with guard band),
    if ((ret = SiFillDmaBuf(r->dram_addr, r->guard_band_bytes, r->fill_value)))
        return SiLogResult(ret, "SiDmaStartRead", "SiFillDmaBuf", r->dram_addr, r->guard_band_bytes, r->fill_value, 0);

    // start a dma read of the si buf,
    if ((ret = SiDmaStart( Dir_To, r->dram_addr, r->reg_data, r->reg_xz, ExpectedFail_None )))
        return SiLogResult(ret, "SiDmaStartRead", "SiDmaStart", Dir_To, r->dram_addr, r->reg_data, r->reg_xz);

    return ret;
}


static int
SiDmaRead(SiDmaTestParam *dma)
{
    // write a pattern to buffer (with guard band),
    // read the si buf via dma and check guard band
    // This is like SiDmaReadAndCmp, but it doesn't compare the
    // returned buffer to expected values

    int         ret = SiDmaStartRead(dma);
    SiDmaParam *r   = &dma->r;

    if(!ret) ret = SiDmaWait( Dir_To, r->dram_addr, &r->timeout, r->expected_failure);
    if(!ret) ret = SiCheckGuardBand(r);

    if(ret)
        SiLogResult(ret, "SiDmaRead", "", r->dram_addr, 0, 0, 0);


    return ret;
}




static int
SiDmaReadAndCmp(SiDmaTestParam *dma)
{
    // write a pattern to read buffer (with guard band),
    // read the si buf via dma,
    // cmp to the expected data per info in dma->r

    int ret      = SiDmaStartRead(dma);
    if(!ret) ret = SiDmaCheckRead(dma);

    return ret;
}




static int
SiDmaCheckWrite(SiDmaTestParam *dma)
{
    // returns 0 for no fail, 1 for expected fail, or -1 for unexpected fail
    int ret;
    SiDmaParam *w = &dma->w;

    if ((ret = SiDmaWait( Dir_From, w->dram_addr, &w->timeout, w->expected_failure)))
        return SiLogResult(ret, "SiDmaCheckWrite", "SiDmaWait", Dir_From, w->dram_addr, w->timeout.limit, w->expected_failure);

    return ret;
}


static int
SiDmaStartWrite(SiDmaTestParam *dma)
{
    int ret;
    SiDmaParam *w = &dma->w;

    if ((ret = SiSetupDmaBuf(dma->w)))
        return SiLogResult(ret, "DmaStartWrite", "SiSetupDmaBuf", w->dram_addr, w->guard_band_bytes, w->fill_value, 0);

    SiWaitTill(dma->dont_rqst_before);
    // Write the SI buffer via DMA
    if ((ret = SiDmaStart( Dir_From, w->dram_addr, w->reg_data, w->reg_xz, ExpectedFail_None)))
        return SiLogResult(ret, "DmaStartWrite", "SiDmaStart", Dir_From, w->dram_addr, w->reg_data, w->reg_xz);

    return ret;
}


static int
SiDmaWrite(SiDmaTestParam *dma)
{
    int ret      = SiDmaStartWrite(dma);
    if(!ret) ret = SiDmaCheckWrite(dma);
    return ret;
}


static int
SiDmaTest (SiDmaTestParam *dma)
{
    // Write the Si buffer indicated by dma->w and read the Si buffer per the info in dma->r
    // Check the content of the buffer read per the info in dma-r

    int ret;

    if ((ret = SiDmaWrite(dma)))
        return SiLogResult(ret, "SiDmaTest", "SiDmaWrite", dma->w.dram_addr, dma->w.guard_band_bytes, dma->w.fill_value, 0);

    ret = SiDmaReadAndCmp(dma);

    return ret;
}


static int
SiDmaWriteRead (SiDmaTestParam *dma)
{
    // Write the Si buffer indicated by dma->w and read the Si buffer per the info in dma->r
    // This is like SiDmaTest, except no check is done on the content of buffer returned by the read

    int ret;

    if ((ret = SiDmaWrite(dma)))
        return SiLogResult(ret, "SiDmaWriteRead", "SiDmaWrite", dma->w.dram_addr, dma->w.guard_band_bytes, dma->w.fill_value, 0);

    ret = SiDmaRead(dma);
    SiLogResult(ret, "SiDmaWriteRead", "SiDmaRead", dma->w.dram_addr, dma->r.dram_addr, dma->w.reg_data, dma->w.reg_xz);

    return ret;
}




static int
SiStartSlaveReceive()
{
    // See SiSlaveTest for extensive comments on slave mode.

    int ret = 0;
    SiDmaTestParam *dmas = &dma_slave_transactions;
    static char rn[] = "SiStartSlaveReceive";
    char reg_info[128];
    unsigned int status, config, mi_intr, si_intr, ints;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:"
        "\n\t\tSetup dma params and start a slave mode master cmd receive on jctrl 1", rn));

    dmas->description = "SiStartSlaveReceive: start slave receive master cmd on jctrl 1";
    dmas->test_case_count ++;
    logMsg(rn);
    SiSetupDmaTestParam(dmas);

    if(isCoQuerySlaveButtons)
        SiSetupButtonTest(0, dmas, 0, 0,  0, ForceFail_None, 0, 0);
    else
        randomCtrlTestSetup(0, dmas, CtrlNoXmitRand, ForceFail_None, 0);

//  SiSetupStatusTest  (1, dmas,  type_L(), type_H(), cstatus(), ForceFail_None, 0, 0);
    randomCtrlTestSetup(1, dmas, CtrlNoXmitRand,                 ForceFail_None, 0);
    randomCtrlTestSetup(2, dmas, CtrlNoXmitRand,                 ForceFail_None, 0);
    randomCtrlTestSetup(3, dmas, CtrlNoXmitRand,                 ForceFail_None, 0);

    dmas->w.ctrlr[1].tx_size = 1;   // Needed to start jctrl 1 execution.
    dmas->r.ctrlr[1].tx_size = 1;   // See comments in SiSlaveTest
    dmas->w.ctrlr[1].rx_size = 1;   // Receive master transaction doesn't work if either tx or rx is 0.
                                    // read rx size is modifyed by SI recieve master transaction
                                    // SiSlaveTest also modifies dmas parameters

    ret = SiDmaWrite(dmas);

    if(isSmJCResetBeforeRcv) {
        SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
        logMsg(rn);
        _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: reset jchan before start slave rcv:  %s", rn, reg_info));
        SiWait(100);
        if(isUseMJCTRL)
            bd_si_ctrl_setup(MJCTRL, MJCTRL_CTL, MJCTRL_JCRESET, 0);
        else
            SiJctrlSetReset(1);
        isSmJCResetBeforeRcv = FALSE; // Only do it once
    }

    if(!ret) ret= SiDmaStartRead(dmas);
    return ret;
}




static int
SiSlaveTest (SiDmaTestParam *dma)
{
    // When you run the normal SI dma tests in slave mode, all jctrl
    // cmds are changed to no_xmit cmds.

    // Instead, the cmds that are setup for lctrl are fed to the master model
    // so they are received over jctrl 1 and an lctrl transaction is
    // used to get the response.

    // In slave mode, only lctrl is a normal master mode controller.
    // jctrl 2 and 3 are not avaialble at all.
    // jctrl 1 is not available when doing normal lctrl cmd transactions.
    // The routines SiSetSlaveMode, SiStartSlaveReceive, and SiSlaveTest
    // manipulate lctrl and jctrl 1 dma parameters in a non-standard way  
    // to retrieve cmds and send back responses to the master.
    // Therefore, in slave mode; SiSetup(Button|Reset|Rtatus|UnsupCmd)Test
    // routines do not do anything special for lctrl but they always set
    // jctrl 1,2,3 tx/rx sizes to zero.
    // SiStartSlaveReceive and SiSlaveTest modify lctrl and jctrl 1
    // dma parmeters (e.g tx/rx size's, tx_rx_buf, cmd)
    // for the non-standard transactions.

    // There are 2 methods for retrieving lctrl responses for master cmds.
    // One method is to do the requested lctrl transaction after the master
    // cmd has indicated what cmd to do.
    // The other method is to do an lctrl button query when retrieving the
    // master cmd from jctrl 1.  If the master cmd is a button querry, a
    // second transction doesn't need to be done.
    // The second method is indicated by isCoQuerySlaveButtons==TRUE

    // You could also pre-query type/status and save it since it doesn't
    // change. That doesn't add anything to test coverage, so I don't do it.

    // A DMA read to receive a master cmd is already active on entry to SiSlaveTest.

    // dmas = dma_slave_transactions.
    // Wait till dma->dont_rqst_before
    // Request the master model backdoor to send the cmd indicated
    // in dma->w.ctrlr[0].
    // Adjust expected jctrl 1 read parameters in dmas->r.ctrlr[1]
    // to correspond to the values expected when receiving the master
    // cmd on jctrl 1.
    // Wait for DMA read completion per info in dmas.
    // Since we adjusted the dmas read parameters, the master cmd received
    // will automatically be compared with the expected cmd.
    // If isCoQuerySlaveButtons==TRUE,
    //   the response will already be in dmas->result[0].
    //   move it to dma->result[0]
    // else,
    //   since we used the write info in "dma" to setup the
    //   master model cmd, "dma" already contains the appropriate info
    //   to do the lctrl cmd to get the resonse for the master.
    //   Do a DMA write/read passing "dma" to get the lctrl cmd response.
    // Setup a dma with lctrl response in the jctrl position
    // Do a DMA write to put the response in the SI buffer
    // Write config slave XMIT bit
    // wait for slave busy to clear
    // wait for int indicated in SI status
    // SI will have DMA'd the SI buffer back to the write buffer
    // Do a DMA write/read to wait for next cmd

    int ret, ret2, i;
    PollInfo  timeout;
    SiDmaTestParam *dmas = &dma_slave_transactions;
    int isCoQuery = isCoQuerySlaveButtons && dma->w.ctrlr[0].cmd == CtrlQueryButtons;
    int error;
    unsigned int lctrl_cmd_result, rsp_size, rcvd_by_master;
    int got_jchan_reset = FALSE;
    int dont_send_response = FALSE;
    const char *master_cmd_str = "unknown";
    static char rn[] = "SiSlaveTest";
    char *rsp_status;
    u8 rsp[4];
    char reg_info[128];
    unsigned int status, config, mi_intr, si_intr, ints;

    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: wait till dma->dont_rqst_before, then request cmd from master model:  %s", rn, reg_info));
    SiWaitTill(dma->dont_rqst_before);

    dmas->r.ctrlr[1].cmd       = dma->w.ctrlr[0].cmd;
    dmas->r.ctrlr[1].tx_rx_buf = dma->w.ctrlr[0].tx_rx_buf;

    if(isUseMJCTRL)
        dmas->r.ctrlr[1].rx_size = 1; //MJCTRL master model always sends only 1 byte
    else
        dmas->r.ctrlr[1].rx_size = dma->w.ctrlr[0].tx_size;

    if(isSmCheckRcvNoRqstCmd) {
        _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: master cmd not requested because isSmCheckRcvNoRqstCmd", rn));
    } else {
        if(isUseMJCTRL) {
            bd_si_ctrl_setup(MJCTRL, MJCTRL_CMD, mjctrl_cmd(dma->w.ctrlr[0].cmd), 0);
            if(isSmJCResetWithCmd) {
                dmas->r.ctrlr[1].error = CTRL_ERR_CTLR_RESET|CTRL_ERR_NO_RESPONSE;
                bd_si_ctrl_setup(MJCTRL, MJCTRL_CTL, MJCTRL_JCRESET|MJCTRL_START_CMD, 0);
                SiWait(SmJCResetWithCmdDelay);
                SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
                logMsg(rn);
                _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: requested reset jchan and %s (i.e. %#x) from master model:  %s", rn, cmdName(dma->w.ctrlr[0].cmd), dma->w.ctrlr[0].cmd, reg_info));
            } else {
                bd_si_ctrl_setup(MJCTRL, MJCTRL_CTL, MJCTRL_START_CMD, 0);
                SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
                _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: requested %s (i.e. %#x) from MJCTRL:  %s", rn, cmdName(dma->w.ctrlr[0].cmd), dma->w.ctrlr[0].cmd, reg_info));
            }
        } else {
            char data[SI_MM_TX_DATA_SIZE];
            int  rx_size   = dmas->r.ctrlr[1].rx_size;
            int  tx_rx_buf = dma->w.ctrlr[0].tx_rx_buf;
            int  i;
            if(!rx_size) rx_size = 1;
            SiWait(64000);
            if(isSmCmdFrameErr) {
                dmas->r.ctrlr[1].error = CTRL_ERR_FRAME;
                bd_si_ctrl_setup(JCTRL_1, CTRL_FRAMEERR, SmCmdFrameErr, 0);
            }
            data[0] = dma->w.ctrlr[0].cmd;
            data[1] = (tx_rx_buf >> 24) & 0xFF;
            data[2] = (tx_rx_buf >> 16) & 0xFF;
            data[3] = (tx_rx_buf >>  8) & 0xFF;
            data[4] = (tx_rx_buf >>  0) & 0xFF;
            for(i=5; i<SI_MM_TX_DATA_SIZE; ++i) // only rx_size is actually sent by master
                data[i] = data[4];
            bd_si_ctrl_set_mm_tx_data(data);
            bd_si_ctrl_setup(JCTRL_1, CTRL_TX_SIZE, rx_size, 0);
            bd_si_ctrl_setup(JCTRL_1, CTRL_TX_ON, 1, 0);
            dmas->r.timeout.limit = (rx_size+2)*33000*(use_rsp_rand[1]?3:1) + 100000;
            SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
            _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: requested %d byte %s (i.e. %#x) from jctrl master model:  %s", rn, rx_size, cmdName(dma->w.ctrlr[0].cmd), dma->w.ctrlr[0].cmd, reg_info));
        }
    }

    if(isSmTruncCmd) { // isSmTruncCmd should not be true if isUseMJCTRL
        SiWait(SmJCResetDurCmdDelay);
        SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
        logMsg(rn);
       _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: disable master mode jctrl 1 during %s (i.e. %#x):  %s", rn, cmdName(dma->w.ctrlr[0].cmd), dma->w.ctrlr[0].cmd, reg_info));
        dmas->r.ctrlr[1].error = CTRL_ERR_NO_RESPONSE;
        bd_si_ctrl_setup(JCTRL_1, CTRL_ENALE, 0, 0);
    }

    if(isSmJCResetDurCmd) {
        dmas->r.ctrlr[1].error = CTRL_ERR_CTLR_RESET|CTRL_ERR_NO_RESPONSE;
        SiWait(SmJCResetDurCmdDelay);
        // mjctrl master model doesn't currently support reset during cmds or responses
        //   bd_si_ctrl_setup(MJCTRL, MJCTRL_CTL, MJCTRL_JCRESET, 0);
        // but jctrl model does even if jctrl is not enabled
        jcrst_duration = 805000; // at least 800 microsec
        ret = SiJctrlResetAndClear(1);
        SiWait(64000);
        jcrst_duration = MIN_JCRST_DURATION;
        SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
        logMsg(rn);
       _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: reset slave mode jchan 1 during %s (i.e. %#x):  %s", rn, cmdName(dma->w.ctrlr[0].cmd), dma->w.ctrlr[0].cmd, reg_info));
    }

    if(isCoQuery)
        dmas->r.ctrlr[0].tx_rx_buf = dma->r.ctrlr[0].tx_rx_buf;

    if(dmas->r.ctrlr[1].error & CTRL_ERR_CTLR_RESET)
        dmas->r.ctrlr[1].cmd   = dmas->w.ctrlr[0].cmd;

    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: wait for cmd from master:  %s", rn, reg_info));
    ret = SiDmaCheckRead(dmas);                   // get cmd from master and compare against expected
    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);

    if(dmas->result[1].error & CTRL_ERR_CTLR_RESET) {
        got_jchan_reset = TRUE;
        /* do ltrl reset */
        logMsg(rn);
        _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: reset lctrl in response to jchan 1 reset:  %s", rn, reg_info));
        SiSetupCtrlResetTest(0, dma, 0, 0,0, ForceFail_None, 0, 0);
        ret2= SiDmaTest(dma);
        if(ret2) {
            ret = ret2;
            goto end;
        }
        if(!isSmPollTilJCResetDone)
            goto end;
    }

    if (isSmPollTilJCResetDone) {
        if(got_jchan_reset) {
            ret = 0;
            logMsg(rn);
            _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: poll til jchan reset done found jchan reset still active:  %s", rn, reg_info));
            goto end;
        } else {
            isSmPollTilJCResetDone = FALSE;
            SiLogRes(0, rn, "JC reset finished", "");
        }
    }

    if(isSmTruncCmd) {
        logMsg(rn);
        _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: truncate slave mode cmd from master %ssuccessful:  %s", rn, (ret?"not ":""), reg_info));
        goto end;
    }

    if(isSmCmdFrameErr) {
        logMsg(rn);
        _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: frame err on slave mode cmd %ssuccessful:  %s", rn, (ret?"not ":""), reg_info));
        if(!isUseMJCTRL) // never is because it doesn't support Frame Err
            cycle_ctrl_enable(JCTRL_1); // model doesn't clear automatically
        goto end;
    }

    if(!dmas->result[1].rx_size) {
        // if a reserved cmd has bits 2-0 == 0, rx_size will be 0 and there will be no request bit
        logMsg(rn);
        _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: unsupported cmd with bits 2-0 == 0 received:  %s", rn, reg_info));
        if(!isUseMJCTRL) // never is because it doesn't support reserved cmds
            cycle_ctrl_enable(JCTRL_1); // model doesn't clear automatically
        goto end;
    }

    master_cmd_str = cmdName(dmas->r.ctrlr[1].cmd);
    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    if (!ret && !(config & SI_CTRL_SM_REQ)) {
        ret = SiLogResult(-1, rn, "slave xmit req did not come on", config,0,0,0);
    }

    if(!ret && !isSupportedCmd(dmas->result[1].cmd) && random() & 1) {
        // sometimes dont send anything back, sometimes do send info back
        logMsg(rn);
        _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: got unsupported cmd %#x from master.  No response will be made:  %s"
                                 , rn, dmas->result[1].cmd, reg_info));
        if(!isUseMJCTRL) // never is because it doesn't support reserved cmds
            cycle_ctrl_enable(JCTRL_1); // model doesn't clear automatically
        SiWait(64000);
       dont_send_response = TRUE;
    } else if(!ret && isCoQuery) {
        _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: master cmd response from lctrl CtrlQueryButtons done simultaneously:  %s", rn, reg_info));
        dma->result[0] = dmas->result[0];
    } else if(!ret) {
        logMsg(rn);
        _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: get cmd response from lctrl:  %s", rn, reg_info));
        ret= SiDmaTest(dma);                     // get cmd response from lctrl
    }
    if(!ret) {
        // Setup a dma with lctrl response in the jctrl position
        dmas->w.ctrlr[0].tx_size   =
        dmas->r.ctrlr[0].tx_size   = 0;
        dmas->w.ctrlr[1].cmd       =
        dmas->r.ctrlr[1].cmd       = dma->result[0].cmd;
        dmas->w.ctrlr[1].tx_size   =
        dmas->r.ctrlr[1].tx_size   =
                        rsp_size   = dont_send_response ? 0 : dma->r.ctrlr[0].rx_size; // dma->result[i].rx_size is limited to 3 bits
        dmas->w.ctrlr[1].rx_size   =
        dmas->r.ctrlr[1].rx_size   = CTRL_SLAVE_RX_FOR_XMIT;
        dmas->w.ctrlr[1].tx_rx_buf =
        dmas->r.ctrlr[1].tx_rx_buf =
        lctrl_cmd_result           = dma->result[0].tx_rx_buf;
        if(!isUseMJCTRL) {
            bd_si_ctrl_setup(JCTRL_1, CTRL_RX_LAST, rsp_size, 0);
            rsp[0] = (lctrl_cmd_result>>24)&0xFF;
            rsp[1] = (lctrl_cmd_result>>16)&0xFF;
            rsp[2] = (lctrl_cmd_result>> 8)&0xFF;
            rsp[3] = (lctrl_cmd_result>> 0)&0xFF;
        }
        if(isSmRspCollision) {
            dmas->r.ctrlr[1].error = CTRL_ERR_COLLISION;
            // Unlike other dma opserations, the buffer is automaticallly
            // written back to the write buffer after the rsp has been xmitted.
            // The only thing of interest is the jctrl 1 error bits.
            // Therefore must explicitly check dma buffer jctrl 1 error bits
            bd_si_ctrl_setup(JCTRL_1, CTRL_COLLISION, SmRspCollision, 0);
        }
    }



    if(!ret) SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    if(!ret) _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: put response in si buffer:  %s", rn, reg_info));
    if(!ret) ret= SiDmaWrite(dmas);                  // Do a DMA write to put the response in the SI buffer

    if(ret) goto end;

    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s:  before start slave xmit:  %s", rn, reg_info));
    if (!(config & SI_CTRL_SM_REQ)) {
        ret = SiLogResult(-1, rn, "slave xmit req is not on", config,0,0,0);
        goto end;
    }

    IO_WRITE(SI_CTRL_REG,SI_CTRL_SM_XMIT | config);     // Write si ctrl reg slave XMIT bit
    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s:  after start slave xmit:   %s", rn, reg_info));
    if (!dont_send_response && !(config & SI_CTRL_SM_XMIT_BUSY)) {
        ret = SiLogResult(-1, rn, "slave xmit busy did not come on", config,0,0,0);
        goto end;
    }

    if (config & SI_CTRL_SM_REQ) {
        ret = SiLogResult(-1, rn, "slave xmit req did not clear", config,0,0,0);
        goto end;
    }

    // wait for slave busy to clear
    timeout.limit = (rsp_size+2)*33000*(use_rsp_rand[1]?3:1) + 100000; // Max time for a CtrlWrite
    ret = poll_timeout_info(SI_CTRL_REG, SI_CTRL_SM_XMIT_BUSY, CLEARED, AllPolls, &timeout);
    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    if (ret) fprintf(DBGOUT, "\n\t%s: Timeout waiting for slave xmit not busy:  duration %u\n\t\t%s",
                             rn, timeout.duration, reg_info);
    else _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: Wait for slave xmit complete succeeded:  duration %u\n\t\t%s",
                             rn, timeout.duration, reg_info));

    // Wait for SI status int bit. It doesn't get set till DMA finishes but busy bit was already cleared
    if(!ret) {
        if (random_env) timeout.limit = 5000;
        else            timeout.limit = 1000;
        ret = poll_timeout_info(SI_STATUS_REG, SI_STATUS_INTERRUPT, SET, AllPolls, &timeout);
        SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
        if (ret) fprintf(DBGOUT, "\n\t%s: Timeout waiting for SI Status interrupt bit after slave cmd xmit completion:  duration %u\n\t\t%s",
                                rn, timeout.duration, reg_info);
        else _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: Wait for SI Status interrupt bit after slave cmd xmit completion succeeded:  duration %u\n\t\t%s",
                                rn, timeout.duration, reg_info));

    }
    _TRACE(dsi, dump(rn, ": slave cmd xmit completion buffer", dmas->w.dram_addr, SI_DMA_XFER_BYTES));

    if (!si_intr) {
        fprintf(DBGOUT, "\n\t%s: MI SI interrupt bit not set after slave cmd xmit completion:\n\t\t%s", rn, reg_info);
        ret = -1;
    }

    if (dedicated_env && !(ints & 1)) {
        fprintf(DBGOUT, "\n\t%s: lsb of int_l  not set after slave cmd xmit completion:\n\t\t%s", rn, reg_info);
        ret = -1;
    }

    // check completion code in data SI wrote back to dma write buffer

    error = (IO_READ(dmas->w.dram_addr+8) >> 11) & 0x0000001f;

    if(isSmRspCollision) {
        if(!(error & CTRL_ERR_COLLISION))
            ret = -1;
        logMsg(rn);
        _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: collision err during slave mode response %ssuccessful:  %s", rn, (ret?"not ":""), reg_info));
        if(!isUseMJCTRL) // never is because it doesn't support collisions
            cycle_ctrl_enable(JCTRL_1); // model doesn't clear automatically
        goto end;
    }

    if (error) {
        fprintf(DBGOUT, "\n\t%s: error bit set after slave cmd xmit completion: error %05x:\n\t\t%s", rn, error, reg_info);
        ret = -1;
    }
    if(ret) goto end;

    // Check response rececived by master

    if(isUseMJCTRL) {
      #if 1
        u8 rbm[4];
        int ctrlcode = (rsp_size == 4) ? MJCTRL_RX_DATA_4 : MJCTRL_RX_DATA_3;

        if( bd_si_ctrl_rd_pkd(MJCTRL, ctrlcode, rbm, sizeof rbm) ) {
            fprintf(DBGOUT, "\n\t%s: error getting data received by master via mjctrl bd:\n\t\t%s", rn, reg_info);
            ret = -1;
            goto end;
        }

        rcvd_by_master = rbm[0]<<24 | rbm[1]<<16 | rbm[2]<<8 | rbm[3];
      #else
        if(bd_si_ctrl_rd( &rcvd_by_master, rsp_size )) {
            fprintf(DBGOUT, "\n\t%s: error getting data received by master via mjctrl bd:\n\t\t%s", rn, reg_info);
            ret = -1;
        } else
      #endif
        if(rcvd_by_master != lctrl_cmd_result ) {
            fprintf(DBGOUT, "\n\t%s:   miscompare:   expected: %08x   received by mjctrl %08x  rsp_size %d\n\t\t%s",
                            rn, lctrl_cmd_result, rcvd_by_master, rsp_size, reg_info);
            ret = -1;
        } else {
            SiLogRes(0, rn, "mjctrl got expected response data for ", master_cmd_str);
            fprintf(DBGOUT, "\n\t%s:   expected: %08x   received by mjctrl %08x  rsp_size %d\n\t\t%s",
                            rn, lctrl_cmd_result, rcvd_by_master, rsp_size, reg_info);
        }
    } else if (!dont_send_response) {

        u8 rbm[36];
        u8 size_rcvd_by_master;

        if( bd_si_ctrl_rd_pkd( JCTRL_1, CTRL_RX_SIZE, &size_rcvd_by_master, 1 ) ||
              bd_si_ctrl_rd_pkd( JCTRL_1, CTRL_RX_DATA_0_7, rbm, 8 ) ||
                bd_si_ctrl_rd_pkd( JCTRL_1, CTRL_RX_DATA_8_35, &rbm[8], 28 ))     {
            fprintf(DBGOUT, "\n\t%s: error getting data received by master via jctrl bd:\n\t\t%s", rn, reg_info);
            ret = -1;
            goto end;
        }

        rsp_status = "successful";
        if (size_rcvd_by_master != (rsp_size + 1)) {
            rsp_status = "size err";
            ret = -1;
        } else {
            for(i=0; i<rsp_size; ++i) {
                if( (i<4 && rbm[i+1] != rsp[i]) ||
                    (i>3 && rbm[i+1] != rsp[3])   ) {
                    rsp_status = "miscompare";
                    ret = -1;
                    break;
                }
            }
        }

        fprintf(DBGOUT, "\n\t%s:   response %s:  rsp_size %u  size_rcvd_by_master %u\n\t\t%s"
                        "\n\tsent by slave:\n\t\t"
                        , rn, rsp_status, rsp_size, (unsigned)size_rcvd_by_master, reg_info);
        for(i=0; i<NUM_ELEMENTS(rsp);    ++i) fprintf(DBGOUT, " %02x", rsp[i]);
                                              fprintf(DBGOUT, "\n\t\treceived by master:");
        for(i=1; i<NUM_ELEMENTS(rbm); ++i) fprintf(DBGOUT, "%s%02x", i%16 ? " ":"\n\t\t", rbm[i]);

        if(!ret) SiLogRes(0, rn, "master got expected response data for ", master_cmd_str);
    }


end:
    if(ret)
        SiLogRes(ret, rn, "error during master/slave transaction for ", master_cmd_str);

    logMsg(rn);
    ret2=SiClearStatus();
    ret = ret ? ret : ret2;

    logMsg(rn);
    if(ret) {
        if(!dma->delayAfterDone)
            SiWait(JCTRL_DELAY_AFTER_DONE);
        ret2=SiInitCtrlSim(1,1,1,1);
    } else
        ret2=SiStartSlaveReceive(); // Do a DMA write/read to receive next master cmd

    logMsg(rn);
    return ret ? ret : ret2;
}




static void
SiSetupDmaParam(SiDmaParam *b)
{
    // *b can be memset to zero before this
    // is called the first time for a b. That will
    // result in init to all default values.
    // It is ok to call with b subsequently without
    // modifying the values from the previous test.
    // Some members (described below) will be preserved.
    // Default is to use a random dma buffer addr,
    // random initial mem fill value, default timeout
    // limit, random write value to start the dma,
    // To preserve specified values,
    //   set dram_addr, fill_value, timeout.limit,
    //   reg_data/reg_xz, and use_dram_addr,
    //   use_fill_value, use_timeout, start_option
    //   and expected_failure as appropriate
    //   before calling this function.
    // Since the default value of expected_failure,
    // is 0 and no common function modifies it by
    // default, it is preserved by this function
    // with no use_blah type variable required.

    SiDmaParam s = *b;  // save values to be preserved

    memset(b, 0, sizeof(SiDmaParam));

    b->use_dram_addr    = s.use_dram_addr;
    b->use_fill_value   = s.use_fill_value;
    b->use_timeout      = s.use_timeout;
    b->expected_failure = s.expected_failure;
    b->start_option     = s.start_option;

    b->dram_addr     = b->use_dram_addr  ? s.dram_addr     : bufAddr();
    b->fill_value    = b->use_fill_value ? s.fill_value    : (unsigned int) random();
    b->timeout.limit = b->use_timeout    ? s.timeout.limit :
                       (use_rsp_rand_any     ? RSP_RND_DMA_TIMEOUT : DEFAULT_DMA_TIMEOUT);

    switch (b->start_option) {
        case ToStartDmaUse_Random_IO_WRITE:
            b->reg_data = random();
            break;
        case ToStartDmaUse_AllBitsX:
            b->reg_data = 0xFFFFFFFF;
            b->reg_xz   = 0xFFFFFFFF;
            break;
        case ToStartDmaUse_reg_value:
            b->reg_data = s.reg_data;
            b->reg_xz   = s.reg_xz;
            break;
        default:
            b->reg_data = 0xABadDeed;
            break;
    }

    b->guard_band_bytes = STD_GUARD_BAND_BYTES;
}

static void
SiSetupDmaTestParam(SiDmaTestParam *dma)
{
    // Default is to use random dma buffer addr's,
    // random initial mem fill value's, and
    // random write values to start the dma.
    // To use specified values,
    //   set dram_addr, fill_value, reg_data/reg_xz,
    //   and use_dram_addr, use_fill_value, start_option
    //   as appropriate.
    // See comments after definition of SiDmaTestParam
    // for detailed info on lc_but_wait and
    // associated parameters.

    SiSetupDmaParam(&dma->w);
    SiSetupDmaParam(&dma->r);

    switch (dma->lc_but_wait) {
        case LcButWait_UseDontRqstBefore:
            dma->delay_before_rqst = 0;
            break;
        case LcButWait_UseDelayBeforeRqst:
            dma->dont_rqst_before  = 0;
            break;
        default:
            dma->delay_before_rqst = 0;
            dma->dont_rqst_before  = 0;
    }

    dma->delayAfterDone = 0;

    dma->min_time_till_readable = 0;
    dma->max_time_till_readable = 0;
    dma->button_period = 0;
    memset(dma->result, 0, sizeof dma->result);
}



static int
SiSetupRandomTestCase ( SiDmaTestParam *dma,
    CtrlCmdCode lc_cmd,  ForceFail lc_f,  int lc_f_param,
    CtrlCmdCode j1_cmd,  ForceFail j1_f,  int j1_f_param,
    CtrlCmdCode j2_cmd,  ForceFail j2_f,  int j2_f_param,
    CtrlCmdCode j3_cmd,  ForceFail j3_f,  int j3_f_param)
{
    // Setup to do a random ctrlr DMA write/read test
    // with random buffer addresses and random responses.
    // Init buffer addr's randomly but with values
    // that should work (i.e. eight bit alligned,
    // within legal memory space.
    // Tests created by this routine should pass

    SiSetupDmaTestParam (dma);

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiSetupRandomTestCase %d: %s:"
        "\n\t\tWrite buf %08x  Read buf %-8x"
        "\n\t\tlc_cmd %08x  lc_f %08x  lc_f_param %08x"
        "\n\t\tj1_cmd %08x  j1_f %08x  j1_f_param %08x"
        "\n\t\tj2_cmd %08x  j2_f %08x  j2_f_param %08x"
        "\n\t\tj3_cmd %08x  j3_f %08x  j3_f_param %08x",
            dma->testname, dma->test_case_count, dma->description,
            dma->w.dram_addr, dma->r.dram_addr,
            lc_cmd, lc_f, lc_f_param,
            j1_cmd, j1_f, j1_f_param,
            j2_cmd, j2_f, j2_f_param,
            j3_cmd, j3_f, j3_f_param
        ));

    randomCtrlTestSetup (0, dma, lc_cmd, lc_f, lc_f_param);
    randomCtrlTestSetup (1, dma, j1_cmd, j1_f, j1_f_param);
    randomCtrlTestSetup (2, dma, j2_cmd, j2_f, j2_f_param);
    randomCtrlTestSetup (3, dma, j3_cmd, j3_f, j3_f_param);

    return 0;
}




static int
SiStartTestCase (SiDmaTestParam *dma)
{
    // Starts a DMA write/read test case and logs result

    int ret;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiStartTestCase %d: %s:"
        "\n\t\tWrite buf %08x  Read buf %-8x",
            dma->testname, dma->test_case_count, dma->description,
            dma->w.dram_addr, dma->r.dram_addr
        ));

    if(isSlaveMode && !doing_ctrl_sim_init)
        ret = SiSlaveTest(dma);
    else
        ret = SiDmaTest(dma);

    SiLogResult(ret, dma->testname, dma->description,
                dma->test_case_count,
                dma->w.dram_addr, dma->r.dram_addr, dma->w.reg_data);

    return ret;
}





static int
SiRunTestCase ( SiDmaTestParam *dma, char *description,
                CtrlCmdCode lc_cmd,  ForceFail lc_f,  int lc_f_param,
                CtrlCmdCode j1_cmd,  ForceFail j1_f,  int j1_f_param,
                CtrlCmdCode j2_cmd,  ForceFail j2_f,  int j2_f_param,
                CtrlCmdCode j3_cmd,  ForceFail j3_f,  int j3_f_param)
{
    // Sets up a random DMA write/read test runs, Runs it and logs result.
    // Uses random buffer addresses and random ctrl responses.
    // If *_cmd is CtrlRandomCmd,
    //     random cmd type is selected for that ctrlr,
    // otherwise,
    //     the specified cmd type is used
    // Init buffer addr's randomly but with values that should
    // work (i.e. eight bit alligned, within legal memory space)
    // Tests created and run by this routine do not setup error cases
    // See comments in SiSetupFailureTest() for how to use the
    // ForceFail parameters and the associated *_f_param args,

    int ret;

    dma->test_case_count ++;
    dma->description = description ? description : "";


    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiRunTestCase %d: %s",
           dma->testname, dma->test_case_count, dma->description));

    ret = SiSetupRandomTestCase ( dma,
                lc_cmd, lc_f, lc_f_param,
                j1_cmd, j1_f, j1_f_param,
                j2_cmd, j2_f, j2_f_param,
                j3_cmd, j3_f, j3_f_param );

    if(!ret) ret = SiStartTestCase (dma);

    return ret;
}

static void
SiInitDmaTestParm(SiDmaTestParam *dma)
{
    // init buffer addr's randomly but with values
    // that should work (i.e. eight bit alligned,
    // within legal memory space.
    // Sets up for a button query test

    SiSetupDmaTestParam(dma);

    SiSetupButtonTest(0, dma, buttons(),  jcount(), jcount(), ForceFail_None, 0, 0);
    SiSetupButtonTest(1, dma, buttons(),  jcount(), jcount(), ForceFail_None, 0, 0);
    SiSetupButtonTest(2, dma, buttons(),  jcount(), jcount(), ForceFail_None, 0, 0);
    SiSetupButtonTest(3, dma, buttons(),  jcount(), jcount(), ForceFail_None, 0, 0);
}


static int
plant( int seed )
{
    int ret;

    if(seed) {
        srandom(seed);
        fprintf(DBGOUT, "\n\t\t\tseed initialized using %#x", seed);
        ret = 1;
    } else {
        ret = 0;
    }

    return ret;
}



static int
SiSetAsSlave()
{
    int ret = 0;
    u32 config1, config2;
    static char rn[] = "SiSetAsSlave";
    SiDmaTestParam *dmas = &dma_slave_transactions;

    memset(dmas, 0, sizeof(SiDmaTestParam));

    dmas->testname = "SiTestSlave";
    dmas->r.timeout.limit = W4MC_DMA_TIMEOUT;
    dmas->r.use_timeout   = TRUE;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:"
        "\n\t\tInitalize slave mode"
        , rn));

    //##############################################################
    // SiTestSlave sets isSlaveMode before running tests.
    // SiDefaults calls SiInitCtrlSim which calls this routine
    // if isSlaveMode is true.

    // See SiSlaveTest for extensive comments on slave mode.

    isSlaveMode = TRUE;

    logMsg(rn);
    if(isUseMJCTRL)
        bd_si_ctrl_setup(MJCTRL, MJCTRL_ENALE, 1, 0);
    else {
        bd_si_ctrl_setup(JCTRL_1, CTRL_MASTER, 1, 0);
        bd_si_ctrl_setup(JCTRL_1, CTRL_ENALE,  1, 0);
    }

    config1 = IO_READ(SI_CONFIG_REG);
    IO_WRITE(SI_CONFIG_REG,SI_CONFIG_JC_SLAVE | config1);
    config2 = IO_READ(SI_CONFIG_REG);
    if (config2 & SI_CONFIG_JC_SLAVE) {
        _TRACE(dsi,fprintf(DBGOUT, "\n\t%s:  config:  before %08lx  after %08lx", rn, config1, config2));
    } else {
        return SiLogResult(-1, rn, "slave bit did not set", config1,config2,0,0);
    }

    ret = SiStartSlaveReceive();

    return SiLogRes(ret, rn, "Initalize slave mode", "");
}



static int
SiLctrlJsxyMoveAndVerify (SiDmaTestParam *dma, int first_buttons, int count_x, int count_y, int jc_no_xmit)
{
    // The check for reach target, timeout on reach target,
    // and check for no motion after reach target is
    // done by SiProcessLctrlJmove() as part of each
    // read dma completion check.  An error is returned
    // if appropriate.  So here we just do button requests
    // untill the low level routine confirms the move
    // or returns an error.
    // Regardless of what is passed for lctrl jcount, a
    // new lctrl x or y movement will not be commanded via
    // bd until the previous one has completed and
    // no motion after reaching the target has been verified.
    // An lctrl bd x,y cmd is not issued if 0 jcount is passed.

    // SiDefaults(), SiInitCtrlSim() calls this routine to
    // do a JSRST and wait for lctrl x,y to become 0.
    // This routine can be used to wait for JSRST or other movement
    // to complete before testing specific x,y moves.
    
    // When testing explicit targets, make sure there is no
    // movement in progress before calling this routine. 

    int ret = 0, i = 0;

    CtrlCmdCode jc_cmd = jc_no_xmit ? CtrlNoXmitRand : CtrlRandomCmd;

    int old_no_random_jsrst = no_random_jsrst;

    no_random_jsrst = TRUE;

    do {
        SiSetupButtonTest   (0, dma, i ? buttons():first_buttons, count_x, count_y, ForceFail_None, 0, 0);
        randomCtrlTestSetup (1, dma, jc_cmd, ForceFail_None, 0);
        randomCtrlTestSetup (2, dma, jc_cmd, ForceFail_None, 0);
        randomCtrlTestSetup (3, dma, jc_cmd, ForceFail_None, 0);

        ret = SiStartTestCase (dma);
        count_x = count_y = 0;
        ++i;
    } while ( !ret && ( lctrl.inmotion_x || lctrl.keep_x_idle ||
                        lctrl.inmotion_y || lctrl.keep_y_idle    ));

    no_random_jsrst = old_no_random_jsrst;
    return ret;
}




int
SiLCtrlButDeglitchVerify(SiDmaTestParam *dma, int levels, int button_rate, int periods, int div )
{
    int ret = 0;
    int errCount = 0;

    int   i, buttpat;
    char *des_template  = "Test lctrl button sampling glitch: %s";
    char  buf[128];

    unsigned long long  max_time_till_readable;

    //##############################################################
    // Assume buttons already set to 0
    // Assume button rate already set
    // Set buttons on via bd for (periods + 1/div)  sample periods
    // verify no change in button state
    // Set buttons off via bd, verify no change in button state
    // Verify buttons don't show up in dma button query within 
    // the max time they would have shown up if we didn't turn them off.

    buttpat = 0xEF3F;
    if (div == 0) div = INT_MAX;

    dma->test_case_count ++;
    snprintf(buf, sizeof buf, "Set buttons on for %d + 1/%d sample periods", periods, div);
    snprintf(dma->description, MAX_DESCRIPTION_SIZE, des_template, buf);
    SiSetupDmaTestParam(dma);

    // These are all preserved, but not used if lc_but_wait is changed to LcButWait_None
    dma->lc_but_wait = LcButWait_Compute;
    dma->button_periods_to_delay = periods;
    dma->offset_from_computed_rqst_time = dma->button_period/div;
    dma->r.expected_failure = ExpectedFail_ctrl_0_tx_rx_buf_or_not;

    SiSetupButtonTest(0, dma,  buttpat,        0,         0, ForceFail_None, 0, 0);
    SiSetupStatusTest(1, dma, type_L(), type_H(), cstatus(), ForceFail_None, 0, 1);
    SiSetupStatusTest(2, dma, type_L(), type_H(), cstatus(), ForceFail_None, 0, 1);
    SiSetupStatusTest(3, dma, type_L(), type_H(), cstatus(), ForceFail_None, 0, 1);

    ret = SiStartTestCase (dma);
    INC_ON_ERR (ret, errCount);
    if(ret) goto end;

    if ( dma->result[0].tx_rx_buf & 0xFFFF0000 ) {
        ret = SiLogRes(-1, dma->testname, dma->description, "Error: change seen");
        INC_ON_ERR (ret, errCount);
        goto end;
    }

    // Get time till buttton sampling would be guaranteed
    // to show bottons on if we left the bd buttons on
    max_time_till_readable = dma->max_time_till_readable;

    // Other button wait values set above will be preserved, but not used
    dma->lc_but_wait = LcButWait_None;

    dma->test_case_count ++;
    snprintf(buf, sizeof buf, "Turn buttons off after  %d + 1/%d sample periods", periods, div);
    snprintf(dma->description, MAX_DESCRIPTION_SIZE, des_template, buf);
    SiSetupDmaTestParam(dma);

    SiSetupButtonTest(0, dma,        0,        0,         0, ForceFail_None, 0, 0);
    SiSetupStatusTest(1, dma, type_L(), type_H(), cstatus(), ForceFail_None, 0, 1);
    SiSetupStatusTest(2, dma, type_L(), type_H(), cstatus(), ForceFail_None, 0, 1);
    SiSetupStatusTest(3, dma, type_L(), type_H(), cstatus(), ForceFail_None, 0, 1);

    ret = SiStartTestCase (dma);
    INC_ON_ERR (ret, errCount);
    if(ret) goto end;

    if ( dma->result [0].tx_rx_buf & 0xFFFF0000 ) {
        ret = SiLogRes(-1, dma->testname, dma->description, "Error: change seen when buttons turned off");
        INC_ON_ERR (ret, errCount);
        goto end;
    }

    // poll lctrl buttons at max rate until past max_time_till_readable
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:    max_time_till_readable %llu",
           dma->testname, max_time_till_readable));

    dsi = 0;
    i   = 0;
    do {
        dma->test_case_count ++;
        snprintf(dma->description, MAX_DESCRIPTION_SIZE, "%d Making sure buttons don't come on til %llu:  %d + 1/%d sample periods", i, max_time_till_readable, periods, div);
        ret = SiStartTestCase (dma);
        INC_ON_ERR (ret, errCount);
        if(ret) goto end;

        if ( dma->result [0].tx_rx_buf & 0xFFFF0000 ) {
            ret = SiLogRes(-1, dma->testname, dma->description, "Error: change seen on check");
            INC_ON_ERR (ret, errCount);
            goto end;
        }

    } while ( dma->r.timeout.start < max_time_till_readable );

    dsi = DSI;

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:    max_time_till_readable %llu    dma->r.timeout.start %llu",
           dma->testname, max_time_till_readable, dma->r.timeout.start));

    SiLogRes(0, dma->testname, dma->description, "Completed Successfully");

end:

    return ((errCount == 0) ? 0 : -1);
}









int
SiTestValidCtrlCmds(int levels, int extra2, int extra3, int seed)
{
    int ret;
    int errCount = 0;
    int i;

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestValidCtrlCmds";

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tTest non-error cases for Local and JCtrl cmds"
        "\n\t\tThis tests most aspects of SI ctrlr cmd/response "
        "\n\t\tthat are expected to complete without errors."
        , dma.testname));

    plant(seed);

    SiDefaults();

    // ###  Write/Read tests 8 byte aligned that should work

#if RestrictDump
    logMsg("SiTestValidCtrlCmds: dump on");
    verilog_dump(1);
#endif /*DLE*/

    ret = SiRunTestCase( &dma, "Valid type/status requests",
                         CtrlQueryStatus, ForceFail_None, 0,
                         CtrlQueryStatus, ForceFail_None, 0,
                         CtrlQueryStatus, ForceFail_None, 0,
                         CtrlQueryStatus, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);

#if RestrictDump
    logMsg("SiTestValidCtrlCmds: dump off");
    verilog_dump(0);
    goto end;
#endif /*DLE*/

    if(levels == 1)
        goto end;

    // Try all other cmd types


    ret = SiRunTestCase( &dma, "Valid button requests",
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);


    if(!(isSlaveMode && isUseMJCTRL)) {

        ret = SiRunTestCase( &dma, "Valid read requests",
                            CtrlRead, ForceFail_None, 0,
                            CtrlRead, ForceFail_None, 0,
                            CtrlRead, ForceFail_None, 0,
                            CtrlRead, ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);


        ret = SiRunTestCase( &dma, "Valid write requests",
                            CtrlWrite, ForceFail_None, 0,
                            CtrlWrite, ForceFail_None, 0,
                            CtrlWrite, ForceFail_None, 0,
                            CtrlWrite, ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);

    }


    ret = SiRunTestCase( &dma, "Start an lctrl x,y move for reset test",
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);


    ret = SiRunTestCase( &dma, "Valid ctrlr reset requests",
                         CtrlReset, ForceFail_None, 0,
                         CtrlReset, ForceFail_None, 0,
                         CtrlReset, ForceFail_None, 0,
                         CtrlReset, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);

    dma.description = "Wait for no x,y motion after reset cmd";

    ret = SiLctrlJsxyMoveAndVerify(&dma, buttons(), 0, 0, 1);

    INC_ON_ERR (ret, errCount);

    ret = SiRunTestCase( &dma, "Start an lctrl x,y move for no xmit reset test",
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);

    if(!isSlaveMode) {

        ret = SiRunTestCase( &dma, "Valid no xmit reset requests",
                             CtrlNoXmitRset, ForceFail_None, 0,
                             CtrlNoXmitRset, ForceFail_None, 0,
                             CtrlNoXmitRset, ForceFail_None, 0,
                             CtrlNoXmitRset, ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);


        dma.description = "Wait for no x,y motion after no xmit reset";

        ret = SiLctrlJsxyMoveAndVerify(&dma, buttons(), 0, 0, 1);

        INC_ON_ERR (ret, errCount);

        ret = SiRunTestCase( &dma, "More valid no xmit button requests",
                             CtrlNoXmitButt, ForceFail_None, 0,
                             CtrlNoXmitButt, ForceFail_None, 0,
                             CtrlNoXmitButt, ForceFail_None, 0,
                             CtrlNoXmitButt, ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);


        ret = SiRunTestCase( &dma, "Valid no xmit status requests",
                             CtrlNoXmitStat, ForceFail_None, 0,
                             CtrlNoXmitStat, ForceFail_None, 0,
                             CtrlNoXmitStat, ForceFail_None, 0,
                             CtrlNoXmitStat, ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);


        ret = SiRunTestCase( &dma, "Valid no xmit read requests",
                             CtrlNoXmitRead, ForceFail_None, 0,
                             CtrlNoXmitRead, ForceFail_None, 0,
                             CtrlNoXmitRead, ForceFail_None, 0,
                             CtrlNoXmitRead, ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);


        ret = SiRunTestCase( &dma, "Valid no xmit write requests",
                             CtrlNoXmitWrit, ForceFail_None, 0,
                             CtrlNoXmitWrit, ForceFail_None, 0,
                             CtrlNoXmitWrit, ForceFail_None, 0,
                             CtrlNoXmitWrit, ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);


        dma.description = "Wait for no x,y motion after no xmit button and status requests";

        ret = SiLctrlJsxyMoveAndVerify(&dma, buttons(), 0, 0, 1);

        INC_ON_ERR (ret, errCount);
    }


    for (i = 0;  i < 5;  ++i) {
        ret = SiRunTestCase( &dma, "Valid jc unsupported (i.e. pass through) cmds",
                             CtrlQueryButtons, ForceFail_None, 0,
                             CtrlJcUnsupCmd,   ForceFail_None, 0,
                             CtrlJcUnsupCmd,   ForceFail_None, 0,
                             CtrlJcUnsupCmd,   ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);
    }


    //##############################################################
    // try some cmd mixes, the random tests will do more of this


    ret = SiRunTestCase( &dma, "Valid mixed ctrlr cmds",
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryStatus,  ForceFail_None, 0,
                         CtrlReset,        ForceFail_None, 0,
                         CtrlNoXmitRand,   ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);



    ret = SiRunTestCase( &dma, "Valid mixed ctrlr cmds",
                         CtrlQueryStatus,  ForceFail_None, 0,
                         CtrlReset,        ForceFail_None, 0,
                         CtrlNoXmitRand,   ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);


    ret = SiRunTestCase( &dma, "Valid mixed ctrlr cmds",
                         CtrlReset,        ForceFail_None, 0,
                         CtrlNoXmitRand,   ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryStatus,  ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);

    if(!isSlaveMode) {

        ret = SiRunTestCase( &dma, "Valid mixed ctrlr cmds",
                             CtrlNoXmitRand,   ForceFail_None, 0,
                             CtrlQueryButtons, ForceFail_None, 0,
                             CtrlQueryStatus,  ForceFail_None, 0,
                             CtrlReset,        ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);
    }


    if(!(isSlaveMode && isUseMJCTRL)) {

        ret = SiRunTestCase( &dma, "Valid mixed ctrlr cmds",
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlRead,         ForceFail_None, 0,
                            CtrlWrite,        ForceFail_None, 0,
                            CtrlQueryStatus,  ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);

        ret = SiRunTestCase( &dma, "Valid mixed ctrlr cmds",
                            CtrlQueryStatus,  ForceFail_None, 0,
                            CtrlWrite,        ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlRead,         ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);

        ret = SiRunTestCase( &dma, "Valid mixed ctrlr cmds",
                            CtrlReset,  ForceFail_None, 0,
                            CtrlReset,  ForceFail_None, 0,
                            CtrlRead,   ForceFail_None, 0,
                            CtrlWrite,  ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);

    }

end:
    errorTotal += errCount;

    return ((errCount == 0) ? 0 : -1);
}



int
SiTestDmaWalkBits(int levels, int test_read_addrs, int walk_zeros, int seed)
{
    // test_read_addrs is 1 for Read and 0 for Write

    int ret;
    int errCount = 0;
    unsigned int i;

    char  buf[128];
    char *pattern;
    char *direction;
    SiDmaParam *tst;
    SiDmaParam *oth;

    SiDmaTestParam  dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    if (test_read_addrs) {
        // Test Read addresses
        tst = &dma.r;
        oth = &dma.w;
        direction = "Read";
        dma.testname = "SiTestDmaWalkBits: Read";
    } else {
        // Test Write addresses
        tst = &dma.w;
        oth = &dma.r;
        direction = "Write";
        dma.testname = "SiTestDmaWalkBits: Write";
    }

    if (!walk_zeros)
        pattern =
            "\n\t\t   00000000000000000000000000000000"
            "\n\t\t   00000000000000000000000000001000"
            "\n\t\t   0000000000000000000000000001r000"
            "\n\t\t   000000000000000000000000001rr000"
            "\n\t\t   00000000000000000000000001rrr000"
            "\n\t\t   0000000000000000000000001rrrr000"
            "\n\t\t       :                           "
            "\n\t\t   0000000001rrrrrrrrrrrrrrrrrrr000"
            "\n\t\t   000000001rrrrrrrrrrrrrrrrrrrr000"
            "\n\t\t   00000001rrrrrrrrrrrrrrrrrrrrr000"
            "\n\t\t   00000010rrrrrrrrrrrrrrrrrrrrr000";
    else
        pattern =
            "\n\t\t   00000010111111111111111111100000"
            "\n\t\t   000000101111111111111111110rr000"
            "\n\t\t   00000010111111111111111110rrr000"
            "\n\t\t   0000001011111111111111110rrrr000"
            "\n\t\t       :                           "
            "\n\t\t   0000001010rrrrrrrrrrrrrrrrrrr000"
            "\n\t\t   000000100rrrrrrrrrrrrrrrrrrrr000"
            "\n\t\t   00000010rrrrrrrrrrrrrrrrrrrrr000"
            "\n\t\t   0000000rrrrrrrrrrrrrrrrrrrrrr000";


    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\t Test SI DMA %s starting at addresses defined"
        "\n\t\t by bit sequence below (r stands for random)%s"
        , dma.testname, direction, pattern));

    plant(seed);

    SiDefaults();

    // set so the specified addr will be used instead of a random addr

    tst->use_dram_addr = TRUE;

    if(!walk_zeros) for (i=2;  i < 32;  i++) { /* x36 addresses */
        if(i==2)
            tst->dram_addr = 0x00000000;
        else if( !((1<<i) & si_dma_addr36_mask) )
            break;
        else
            tst->dram_addr = (1<<i) | ranbits(3, i-3);
        tst->dram_addr &= si_dma_addr36_mask;
        if ( tst->dram_addr >= si_dma_addr36_top )
            tst->dram_addr &= ~((1<<i)-1);
        if ( tst->dram_addr >= si_dma_addr36_top )
            break;
        fprintf(DBGOUT, "\n\t%s:  1's  x36  i: %d   dram_addr: %08x", dma.testname, i, tst->dram_addr);
        snprintf(buf, sizeof buf, "  walk ones  x36,  %08x", (i==2 ? 0 : (1<<i)) );
        ret = SiRunTestCase( &dma, buf,
                             CtrlRandomCmd, ForceFail_None, 0,
                             CtrlRandomCmd, ForceFail_None, 0,
                             CtrlRandomCmd, ForceFail_None, 0,
                             CtrlRandomCmd, ForceFail_None, 0);
        INC_ON_ERR (ret, errCount);
        if(ret) SiClearStatus();
    }

    if(!walk_zeros) for (i=3;  i < 32;  i++) {  /* x64 addreses */
        if( !((1<<i) & si_dma_addr64_mask) )
            break;
        if( (1<<i) == DDRRAM64_START )
            continue;
        tst->dram_addr = (1<<i) | ranbits(3, i-3);
        if(tst->dram_addr < DDRRAM64_START)
            tst->dram_addr |= DDRRAM64_START;
        tst->dram_addr &= si_dma_addr64_mask;
        if ( tst->dram_addr >= si_dma_addr64_top )
            tst->dram_addr &= ~((1<<i)-1);
        if ( tst->dram_addr >= si_dma_addr64_top )
            break;
        fprintf(DBGOUT, "\n\t%s:  1's  x64  i: %d   dram_addr: %08x", dma.testname, i, tst->dram_addr);
        snprintf(buf, sizeof buf, "  walk ones  x64,  %08x", (i==2 ? 0 : (1<<i)) );
        ret = SiRunTestCase( &dma, buf,
                             CtrlRandomCmd, ForceFail_None, 0,
                             CtrlRandomCmd, ForceFail_None, 0,
                             CtrlRandomCmd, ForceFail_None, 0,
                             CtrlRandomCmd, ForceFail_None, 0);
        INC_ON_ERR (ret, errCount);
        if(ret) SiClearStatus();
    }

    if(walk_zeros) for (i=4;  i < 32;  i++) {  /* x36 addresses */
        if( !((1<<i) & si_dma_addr36_mask) )
            break;
        if(i==4) /* must have at least 32 bytes for dma buffer */
            tst->dram_addr = si_dma_addr64_top-32;
        else
            tst->dram_addr = (si_dma_addr64_top-8) & ~((1 << i) | ranbits(3,i-3));
        tst->dram_addr &= si_dma_addr36_mask;
        fprintf(DBGOUT, "\n\t%s:  0's  x36  i: %d   dram_addr: %08x", dma.testname, i, tst->dram_addr);
        snprintf(buf, sizeof buf, "  walk zeros  x36, %08x", (i==4 ? 0 : (1<<i)) );
        ret = SiRunTestCase( &dma, buf,
                             CtrlRandomCmd, ForceFail_None, 0,
                             CtrlRandomCmd, ForceFail_None, 0,
                             CtrlRandomCmd, ForceFail_None, 0,
                             CtrlRandomCmd, ForceFail_None, 0);
        INC_ON_ERR (ret, errCount);
        if(ret) SiClearStatus();
    }

    if(walk_zeros) for (i=4;  i < 32;  i++) {   /* x64 addreses */
        if( !((1<<i) & si_dma_addr64_mask) )
            break;
        if(i==4) /* must have at least 32 bytes for dma buffer */
            tst->dram_addr = si_dma_addr64_top-32;
        else
            tst->dram_addr = (si_dma_addr64_top-8) & ~((1 << i) | ranbits(3,i-3));
        tst->dram_addr &= si_dma_addr64_mask;
        if((si_dma_mem64_size < DDRRAM64_START))
            tst->dram_addr |= DDRRAM64_START;
        if(tst->dram_addr < DDRRAM64_START)
            continue;
        fprintf(DBGOUT, "\n\t%s:  0's  x64  i: %d   dram_addr: %08x", dma.testname, i, tst->dram_addr);
        snprintf(buf, sizeof buf, "  walk zeros  x64, %08x", (i==4 ? 0 : (1<<i)) );
        ret = SiRunTestCase( &dma, buf,
                             CtrlRandomCmd, ForceFail_None, 0,
                             CtrlRandomCmd, ForceFail_None, 0,
                             CtrlRandomCmd, ForceFail_None, 0,
                             CtrlRandomCmd, ForceFail_None, 0);
        INC_ON_ERR (ret, errCount);
        if(ret) SiClearStatus();
    }

    errorTotal += errCount;

    return ((errCount == 0) ? 0 : -1);
}



int
SiTestDmaSpecificAddrs(int levels, int test_read_addrs, int extra3, int seed)
{
    // test_read_addrs is 1 for Read and 0 for Write

    int ret;
    int errCount = 0;
    int a, m, buttons, i;

    char  buf[128];
    char *direction;
    SiDmaParam *tst;
    SiDmaParam *oth;

    SiDmaTestParam  dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    if (test_read_addrs) {
        // Test Read addresses
        tst = &dma.r;
        oth = &dma.w;
        direction = "Read";
        dma.testname = "SiTestDmaSpecificAddrs: Read";
    } else {
        // Test Write addresses
        tst = &dma.w;
        oth = &dma.r;
        direction = "Write";
        dma.testname = "SiTestDmaSpecificAddrs: Write";
    }

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tTest SI DMA %s to interesting addresses."
        "\n\t\tThis also tests aspects of SI ctrlr cmd/response "
        "\n\t\tthat are expected to complete without errors."
        , dma.testname, direction));

    plant(seed);

    SiDefaults();

    // set so the specified addr will be used instead of a random addr

    tst->use_dram_addr = TRUE;



    // not 8 byte aligned
    // addr written to SI_DRAM_ADDR is not 8 bit aligned,
    // but the buffer data is.  That way the dma will
    // be successful if the DMA ignores the 3lsb of the addr.

    for (i=1;  levels < 1 && i < 8;  i++) {
        tst->dram_addr = bufAddr() + i;
        snprintf(buf, sizeof buf, "Not 8 byte aligned, addr mod 8: %08x", tst->dram_addr % 8 );
        ret = SiRunTestCase( &dma, buf,
                             CtrlQueryButtons, ForceFail_None, 0,
                             CtrlQueryButtons, ForceFail_None, 0,
                             CtrlQueryButtons, ForceFail_None, 0,
                             CtrlQueryButtons, ForceFail_None, 0);
        INC_ON_ERR (ret, errCount);
        if(ret) SiClearStatus();
    }


    // cross boundaries: 16bytes, 32bytes, 64bytes, 128bytes, 256bytes , 512bytes, 1K, 2K, 4K, 8K, 16K, 32K, 64K, 128K, 256K, 512K, 1M
    // includes jctrl and lctrl cmds/response check
    //     walks through bit set for each jctrl/lctrl  button
    //     random x/y's
    // includes random write values to start write/read DMAs

    buttons=0x0001;

    // In this for loop we set things up and then use SiStartTestCase()
    // instead of SiRunTestCase().  This is to allow setting the buttons
    // to a rotating bit pattern to piggback a button test on this addr test.
    for (m = 1;  m < 3; ++m) {
        for (a = 16;  a <= 4*1024*1024*m;   a *= 2) {
            tst->dram_addr = a - 8 + (m == 2 ? DDRRAM64_START : 0);
            if ((tst->dram_addr + SI_DMA_XFER_BYTES)
                     >= (m == 2 ? si_dma_addr64_top : si_dma_addr36_top)) {
                break;
            }
            if (a % (1024*1024 * m) == 0) {
                dma.r.expected_failure = ExpectedFail_any_ctrl_fail; // DMAs can't cross 1M * n  boundary (2M *n for x64)
                dma.r.timeout.limit = 5000000;
                dma.r.use_timeout = TRUE;
                // Make sure addr 0 - 32*4 has been written so it isn't all Xs
                // Otherwise the SI hangs up.
                for ( i = 0;  i < 4;  ++i )
                    SiBDMemWriteRead(i*1024*1024, 0, 0, SI_DMA_XFER_BYTES, 0);
            } else if ( levels > 1 ) {
                dma.r.use_timeout = FALSE;
                continue;
            }

            snprintf(buf, sizeof buf, "cross boundaries: %d %s", (a < 1024 ? a: a/1024), (a < 1024 ? "bytes" : "k" ));
            dma.test_case_count ++;
            dma.description = buf;

            _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: %d:  %s  dram_addr %08x", dma.testname, dma.test_case_count, buf, tst->dram_addr));
            SiSetupDmaTestParam(&dma);  // to get random values for parameters not explicitly set

            SiSetupButtonTest(0, &dma, buttons, jcount(), jcount(), ForceFail_None, 0, 0);
            SiSetupButtonTest(1, &dma, buttons, jcount(), jcount(), ForceFail_None, 0, 0);
            SiSetupButtonTest(2, &dma, buttons, jcount(), jcount(), ForceFail_None, 0, 0);
            SiSetupButtonTest(3, &dma, buttons, jcount(), jcount(), ForceFail_None, 0, 0);

            buttons = shiftButtons(buttons);

            ret = SiStartTestCase (&dma);
            INC_ON_ERR (ret, errCount);
            if(ret) SiClearStatus();
        }
        dma.r.expected_failure = ExpectedFail_None;
    }


    // do x64 mode, bank crossing, and any other interesting address cases
    // check crossing bank 0/1 (already done above) and  2/3
    // bank 0/1 crossed when bit 6 goes from 0->1 for address under 1M (i.e. starting at 64-8 == 0x00000040 - 8 above)
    // bank 2/3 crossed when bit 6 goes from 0->1 for address over 1M  (i.e. starting at 0x00101040 - 16 below)

    {
        unsigned int addr[] = { 0x00101040 - 16,
                                0x01201080 - 16  };

        char *desc[] = { "bank 2/3 crossed x36",
                         "x64 mode" };

        for (i=0;    i < NUM_ELEMENTS(addr);  ++i) {

            if(  (addr[i] >= si_dma_addr64_top) ||
                ((addr[i] >= si_dma_addr36_top) && (addr[i] <  DDRRAM64_START)) ){
                continue;
            }
            tst->dram_addr = addr[i];

            ret = SiRunTestCase( &dma, desc[i],
                                 CtrlQueryButtons, ForceFail_None, 0,
                                 CtrlQueryButtons, ForceFail_None, 0,
                                 CtrlQueryButtons, ForceFail_None, 0,
                                 CtrlQueryButtons, ForceFail_None, 0  );

            INC_ON_ERR (ret, errCount);
            if(ret) SiClearStatus();
        }
    }


    errorTotal += errCount;

    return ((errCount == 0) ? 0 : -1);
}












static int
SiInvalidCtrlrCmdFields (SiDmaTestParam *dma, CtrlCmdCode cmd_type)
{
    int ret;
    int errCount = 0;
    char buf[128];


    //##########################################
    // try tx_size too big for any supported cmd (i.e. > 63)

    snprintf(buf, sizeof buf, "%s:  tx size > 63", cmdName(cmd_type));
    ret = SiRunTestCase(dma, buf,
                cmd_type, ForceFail_tx_TooBigForAnyCmdType, 0,
                cmd_type, ForceFail_tx_TooBigForAnyCmdType, 0,
                cmd_type, ForceFail_tx_TooBigForAnyCmdType, 0,
                cmd_type, ForceFail_tx_TooBigForAnyCmdType, 0 );

    INC_ON_ERR (ret, errCount);

    //##########################################
    // try invalid tx_size for the cmd

    snprintf(buf, sizeof buf, "%s:  invalid tx size", cmdName(cmd_type));
    ret = SiRunTestCase(dma, buf,
                cmd_type, ForceFail_tx_InvalidForCmdType, 0,
                cmd_type, ForceFail_tx_InvalidForCmdType, 0,
                cmd_type, ForceFail_tx_InvalidForCmdType, 0,
                cmd_type, ForceFail_tx_InvalidForCmdType, 0 );

    INC_ON_ERR (ret, errCount);

    //##########################################
    // try rx_size too big for any supported cmd (i.e. > 63)

    snprintf(buf, sizeof buf, "%s:  rx size > 63", cmdName(cmd_type));
    ret = SiRunTestCase(dma, buf,
                cmd_type, ForceFail_rx_TooBigForAnyCmdType, 0,
                cmd_type, ForceFail_rx_TooBigForAnyCmdType, 0,
                cmd_type, ForceFail_rx_TooBigForAnyCmdType, 0,
                cmd_type, ForceFail_rx_TooBigForAnyCmdType, 0);

    INC_ON_ERR (ret, errCount);

    //##########################################
    // try rx_size 0

    snprintf(buf, sizeof buf, "%s:  rx size 0", cmdName(cmd_type));
    ret = SiRunTestCase(dma, buf,
                cmd_type, ForceFail_rx_Zero, 0,
                cmd_type, ForceFail_rx_Zero, 0,
                cmd_type, ForceFail_rx_Zero, 0,
                cmd_type, ForceFail_rx_Zero, 0 );

    INC_ON_ERR (ret, errCount);

    //##########################################
    // try invalid rx_size for the cmd

    snprintf(buf, sizeof buf, "%s:  invalid rx size", cmdName(cmd_type));
    ret = SiRunTestCase(dma, buf,
                cmd_type, ForceFail_rx_InvalidForCmdType, 0,
                cmd_type, ForceFail_rx_InvalidForCmdType, 0,
                cmd_type, ForceFail_rx_InvalidForCmdType, 0,
                cmd_type, ForceFail_rx_InvalidForCmdType, 0 );

    INC_ON_ERR (ret, errCount);


    errorTotal += errCount;

    return ((errCount == 0) ? 0 : -1);
}



int
SiTestInvalidCtrlrCmds(int levels, int extra2, int extra3, int seed)
{
    int ret;
    int errCount = 0;
    int i, num_cmd_types;

    CtrlCmdCode cmd_type[] = { CtrlQueryStatus,
                               CtrlQueryButtons,
                               CtrlRead,
                               CtrlWrite,
                               CtrlReset,
                               CtrlJcUnsupCmd,
                               CtrlNoXmitStat,
                               CtrlNoXmitButt,
                               CtrlNoXmitRset,
                               CtrlNoXmitUsup };

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestInvalidCtrlrCmds";

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tTest ctrlr cmds with errors in the cmd fields"
        , dma.testname));

    plant(seed);

    SiDefaults();

    num_cmd_types = levels==1 ? 1 : NUM_ELEMENTS(cmd_type);

#if RestrictDump
    logMsg("SiTestInvalidCtrlrCmds: dump on");
    verilog_dump(1);
    for (i = 0;  i < 1;  ++i) {
        ret = SiInvalidCtrlrCmdFields( &dma, cmd_type[i] );
        INC_ON_ERR (ret, errCount);
    }
    logMsg("SiTestInvalidCtrlrCmds: dump off");
    verilog_dump(0);
    goto end;
#else /*DLE RestrictDump*/
    for (i = 0;  i < num_cmd_types;  ++i) {
        ret = SiInvalidCtrlrCmdFields( &dma, cmd_type[i] );
        INC_ON_ERR (ret, errCount);
    }
#endif /*DLE RestrictDump*/

    if (levels == 1)
        goto end;

    //##############################################################
    //  Test some cases missed by SiInvalidCtrlrCmdFields()
    //  Tests fix for bug 1461 - No error bits with SI lctl Status
    //  or Reset cmds with rx_size 4"

    ret = SiRunTestCase(&dma, "CtrlQueryStatus:  invalid rx size == 4",
                CtrlQueryStatus, ForceFail_rx_InvalidForCmdType, 4,
                CtrlQueryStatus, ForceFail_rx_InvalidForCmdType, 4,
                CtrlQueryStatus, ForceFail_rx_InvalidForCmdType, 4,
                CtrlQueryStatus, ForceFail_rx_InvalidForCmdType, 4 );

    INC_ON_ERR (ret, errCount);

    ret = SiRunTestCase(&dma, "CtrlReset:  invalid rx size == 4",
                CtrlReset, ForceFail_rx_InvalidForCmdType, 4,
                CtrlReset, ForceFail_rx_InvalidForCmdType, 4,
                CtrlReset, ForceFail_rx_InvalidForCmdType, 4,
                CtrlReset, ForceFail_rx_InvalidForCmdType, 4 );

    INC_ON_ERR (ret, errCount);

    //##########################################
    // test fix for bug 1500
    //  - No lctrl error with invalid rx size on button request

    ret = SiRunTestCase(&dma, "lctrl button request with invalid rx size === 3 (bug 1500)",
                CtrlQueryButtons, ForceFail_rx_InvalidForCmdType, 3,
                CtrlQueryButtons, ForceFail_rx_InvalidForCmdType, 3,
                CtrlQueryButtons, ForceFail_rx_InvalidForCmdType, 3,
                CtrlQueryButtons, ForceFail_rx_InvalidForCmdType, 3);

    INC_ON_ERR (ret, errCount);




    //##############################################################
    //  Test unsupported lctrl cmd types (only 0, 1, or 255 are supported)
    //  without other cmd errors and use the opportunity to test
    //  random failures with unsupported (i.e. passthrough) jc cmds.
    //  All cmd types (i.e. 0-255) are valid for jc's
    //  Unsupported cmd's with specific failures are also
    //  tested in the prev loop.

    for (i = 0;  i < 5;  ++i) {
        ret = SiRunTestCase(&dma, "Unsupported command types",
                     CtrlJcUnsupCmd, ForceFail_None,   0,
                     CtrlJcUnsupCmd, ForceFail_Random, 0,
                     CtrlJcUnsupCmd, ForceFail_Random, 0,
                     CtrlJcUnsupCmd, ForceFail_Random, 0 );
        INC_ON_ERR (ret, errCount);
    }

end:

    errorTotal += errCount;

    return ((errCount == 0) ? 0 : -1);
}



int
SiTestCtrlrErrViaBD(int levels, int cmd_arg, int extra3, int seed)
{
    int ret;
    int errCount = 0;
    CtrlCmdCode cmd = cmd_arg;  // must be a CtrlCmdCode

    char description[MAX_DESCRIPTION_SIZE];

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    snprintf(description, sizeof description, "%s: %s: ", "SiTestCtrlrErrViaBD", cmdName(cmd));

    dma.testname = description;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tTest no response from disabled ctrlr"
        "\n\t\tTest collision err set via bd ctrlr"
        "\n\t\tTest frame err set via bd ctrlr", description));

    plant(seed);

    SiDefaults();

    ret = SiRunTestCase( &dma, "None, NoResponse, Collision, Frame",
                         cmd, ForceFail_None, 0,
                         cmd, ForceFail_NoResponse, 0,
                         cmd, ForceFail_Collision, 0,
                         cmd, ForceFail_Frame, 0  );

    INC_ON_ERR (ret, errCount);

    if (levels == 1)
        goto end;

    ret = SiRunTestCase( &dma, "None, Collision, Frame, NoResponse",
                         cmd, ForceFail_None, 0,
                         cmd, ForceFail_Collision, 0,
                         cmd, ForceFail_Frame, 0,
                         cmd, ForceFail_NoResponse, 0  );

    INC_ON_ERR (ret, errCount);


    ret = SiRunTestCase( &dma, "None, Frame, NoResponse, Collision",
                         cmd, ForceFail_None, 0,
                         cmd, ForceFail_Frame, 0,
                         cmd, ForceFail_NoResponse, 0,
                         cmd, ForceFail_Collision, 0  );

    INC_ON_ERR (ret, errCount);

end:
    ret = (errCount == 0) ? 0 : -1;

    SiLogResult(ret, description, "no response, collision, and frame errs set via BD", cmd, 0, 0, 0);

    errorTotal += errCount;

    return ret ;
}





int
SiTestJChannelReset(int levels, int extra2, int extra3, int seed)
{
    int ret;
    int errCount = 0;

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestJChannelReset";

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tSI JChannel Reset test", dma.testname));

    plant(seed);

    SiDefaults();

    dma.test_case_count ++;
    dma.description = "";

    SiInitDmaTestParm(&dma);

    setCtrlCmdData (&dma.r.LC, 0xFF, CTRL_ERR_CTLR_RESET, 1, 4, CtrlQueryButtons, 0);
    setCtrlCmdData (&dma.r.J1, 0xFF, CTRL_ERR_CTLR_RESET, 1, 4, CtrlQueryButtons, 0);
    setCtrlCmdData (&dma.r.J2, 0xFF, CTRL_ERR_CTLR_RESET, 1, 4, CtrlQueryButtons, 0);
    setCtrlCmdData (&dma.r.J3, 0xFF, CTRL_ERR_CTLR_RESET, 1, 4, CtrlQueryButtons, 0);

    dma.description = "write before JCRST";
    ret = SiDmaWrite(&dma);
    dma.description = "start read before JCRST";
    if(!ret) ret = SiDmaStartRead(&dma);
    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  Set JCRST during the DMA Read", dma.testname));

    jcrst_duration = 805000; // at least 800 microsec
    if(!ret) ret = SiJctrlResetAndClear(0);
    if(!ret) ret = SiDmaCheckRead(&dma);

    if(ret) goto end;


    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  Got Expected controller reset error", dma.testname));

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  After JCRST cleared, expect a good DMA read", dma.testname));

    ret = SiRunTestCase( &dma, "write/read after JCRST cleared",
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);


    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  %s after clear the JCRST", dma.testname, (ret ? "Still got fail" : "Got Successful DMA ")));

/* while the test below works, it doesn't make sense to do it as behavior with JCRST on is undefined.*/
#if 0

    if(ret) goto end;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  Try a reset before trying a write/read", dma.testname));

    ret = SiJctrlReset(0);

    dma.r.expected_failure = ExpectedFail_DmaTimeout;

    ret = SiRunTestCase( &dma, "write/read after JCRST",
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0,
                         CtrlQueryButtons, ForceFail_None, 0  );

    if (ret != 1) {
        ret = -1;
        _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  Expected DMA Timeout error did not occur", dma.testname));
    } else
        _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  Got Expected DMA Timeout error", dma.testname));

    INC_ON_ERR (ret, errCount);

#endif

end:

    INC_ON_ERR (ret, errCount);

    ret = (errCount == 0) ? 0 : -1;

    return SiLogResult(ret, dma.testname, "", 0, 0, 0, 0);
}



int
SiTestDmaBusyError(int levels, int reg_to_write, int data, int xz_part)
{
    int    ret;

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestDmaBusyError";

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
            "\n\t\tTest ability to create and clear DMA busy errors"
            "\n\t\tWrite to %08x while DMA busy to cause error."
            , dma.testname, reg_to_write));

    SiDefaults();

    dma.test_case_count ++;
    dma.description = "";

    SiInitDmaTestParm(&dma);

    if ( (ret = SiDmaWrite(&dma)) || (ret = SiDmaStartRead(&dma)) )
        return SiLogResult(ret, dma.testname, "", reg_to_write, 0, 0, 0);

    if ( xz_part ) {
        if ((ret = SiExtMemWrite(reg_to_write, data, xz_part)))
            return SiLogResult(ret, dma.testname, "SiExtMemWrite", reg_to_write, 0, 0, 0);
    } else
        IO_WRITE(reg_to_write, data);

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  Wrote  data_part %08x  xz_part %08x  to  reg %08x  during SI DMA Read to cause SI DMA error:"
                                , dma.testname, data, xz_part, reg_to_write));

    dma.r.expected_failure = ExpectedFail_DmaError;

    ret = SiDmaCheckRead(&dma);
    if (ret != 1)
        return SiLogResult(ret, dma.testname, "expected failure didn't occur: SiDmaCheckRead", reg_to_write, 0, 0, 0);

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:  Got expected DMA error: "
                                "reg %08x  data_part %08x  xz_part %08x"
                                , dma.testname, reg_to_write, data, xz_part));

    // check that can clear error bit and successfully do a DMA
    ret = SiClearStatus();
    if(!ret) ret = SiDmaWrite(&dma);

    SiLogResult(ret, dma.testname, "", 0, 0, 0, 0);

    return ret;
}


int
SiTestSingleCmdDetection(int levels, int sgl_err_bit, int extra3, int seed)
{
    int ret;
    int errCount = 0;

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestSingleCmdDetection";

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tTest single cmd indicated by block byte == 0"
        "\n\t\tTry with SI_CONFIG bit 23: %s"
        , dma.testname, (sgl_err_bit ? "1":"0")));

    plant(seed);

    SiDefaults();

    dma.test_case_count ++;
    dma.description = "";

    SiInitDmaTestParm(&dma);

    if (sgl_err_bit)
        IO_WRITE(SI_CONFIG_REG, (IO_READ(SI_CONFIG_REG) | SI_CONFIG_SGL_ERR));
    else
        IO_WRITE(SI_CONFIG_REG,(IO_READ(SI_CONFIG_REG) & ~SI_CONFIG_SGL_ERR));


    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SI_CONFIG is now: %08x", dma.testname, IO_READ(SI_CONFIG_REG)));
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:"
        "\n\t\tTry with LCtrl block byte 0x00 and JCtrls 0xFF", dma.testname));

    setCtrlCmdData(&dma.w.LC,  0, 0, 1, 4, CtrlQueryButtons, 0);

    if (sgl_err_bit) {
        if ((ret = SiDmaWriteRead(&dma))) {
            SiClearStatus();
        }
        if(!ret) ret = SiCmpBlock(dma.r.dram_addr, 0xFFFFFFFF, SI_DMA_XFER_BYTES);
    } else {
        // With no single command detection the cmds should work normally
        if ((ret = SiDmaTest(&dma))) {
            SiClearStatus();
        }
    }

    if(ret) ++ errCount;

    SiLogResult(ret, dma.testname, "", 0, 0, 0, 0);

    if (levels == 1)
        goto end;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:"
        "\n\t\tTry with LCtrl and JCtrls block byte 0x00", dma.testname));

    setCtrlCmdData(&dma.w.LC, 0, 0, 1, 4, CtrlQueryButtons, 0);
    setCtrlCmdData(&dma.w.J1, 0, 0, 1, 4, CtrlQueryButtons, 0);
    setCtrlCmdData(&dma.w.J2, 0, 0, 1, 4, CtrlQueryButtons, 0);
    setCtrlCmdData(&dma.w.J3, 0, 0, 1, 4, CtrlQueryButtons, 0);

    if (sgl_err_bit) {
        if ((ret = SiDmaWriteRead(&dma))) {
            SiClearStatus();
        }
        if(!ret) ret = SiCmpBlock(dma.r.dram_addr, 0xFFFFFFFF, SI_DMA_XFER_BYTES);
    } else {
        // With no single command detection the cmds should work normally
        if ((ret = SiDmaTest(&dma))) {
            SiClearStatus();
        }
    }

    if(ret) ++ errCount;

    SiLogResult(ret, dma.testname, "", 0, 0, 0, 0);

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s:"
        "\n\t\tTry with LCtrl 0xFF and JCtrls block byte 0x00", dma.testname));

    setCtrlCmdData(&dma.w.LC, 0xFF, 0, 1, 4, CtrlQueryButtons, 0);
    setCtrlCmdData(&dma.w.J1,    0, 0, 1, 4, CtrlQueryButtons, 0);
    setCtrlCmdData(&dma.w.J2,    0, 0, 1, 4, CtrlQueryButtons, 0);
    setCtrlCmdData(&dma.w.J3,    0, 0, 1, 4, CtrlQueryButtons, 0);

    // This should work the same as if 0xFF was passed in byte 0 of all ctrlrs
    if ((ret = SiDmaTest(&dma))) {
        SiClearStatus();
        errCount++;
    }

    SiLogResult(ret, dma.testname, "", 0, 0, 0, 0);

end:
    if (!sgl_err_bit)
        IO_WRITE(SI_CONFIG_REG, (IO_READ(SI_CONFIG_REG) | SI_CONFIG_SGL_ERR));

    errorTotal += errCount;

    return((errCount == 0) ? 0 : -1);
}


int
SiTestLCtrlButRate(int levels, int num_samples_arg, int random_rates, int seed)
{
    int ret = 0;
    int errCount = 0;

    int  i, next, test_num, num_tests, meas_num, config;
    char buf[128];

    int  but_rate[] = { 1, 2, 10 };
    int  button_rate;

    // num_samples refers to the num times we collect info
    // on how long it takes for a button change to be seen
    // for each button_rate.
    int  num_samples = num_samples_arg ? num_samples_arg : 2;
    unsigned int change_period[num_samples];
    unsigned int sync_offset  [num_samples];  // offset of bd write from sample sync time

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestLCtrlButRate";

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tTest but rate cntrl on LCtrl cmds (i.e. SI_CONFIG BUT_RATE)"
        , dma.testname));

    plant(seed);

    SiDefaults();

    //##############################################################
    // Determine change time by setting button value via backdoor,
    // writing si button request and reading si buf until see the change,

    // do n tests, keeping track of bd write time, detect time
    // then process, variation in detect period.  The detect times
    // should be separated by the 3 to 4 times the button sample period

    if (!num_samples)  num_samples = 2;

    if (random_rates) num_tests = random_rates;
    else              num_tests = NUM_ELEMENTS(but_rate);

    no_random_jsrst = TRUE;

    for (test_num = 0;  test_num < num_tests;  ++test_num) {
        button_rate = random_rates ? buttonRate() : but_rate[test_num];
        dma.r.expected_failure = ExpectedFail_ctrl_0_tx_rx_buf_or_not;
        config = IO_READ(SI_CONFIG_REG);

        _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: New Rate: %d   SI_CONFIG is now: %08x", dma.testname, button_rate, config));

        for (i = 0, next = TRUE, meas_num = 0, dsi = DSI;
             !ret && i < num_samples;
             i = next ? ++i : i) {

            snprintf(buf, sizeof buf, "but_rate: %06x  sample num %d  meas num %d  ", button_rate, i+1, ++meas_num);
            if (next) {
                next = FALSE;
                // setLctrlButRate syncs the samples to start at approx now
                // and sets lctrl_but_sam_sync_time
                // By doing it here instead of once for each rate
                // we guarantee that sync_offset will be a small number.
                setLctrlButRate(button_rate);
                SiWait(500); // We don't want sync_offset to be exactly zero
                dma.lc_but_wait = LcButWait_Compute;
                dma.button_periods_to_delay = 3;
                dma.offset_from_computed_rqst_time = - 100000;
                ret = SiRunTestCase( &dma, buf,
                                     CtrlQueryButtons, ForceFail_None, 0,
                                     CtrlNoXmitStat,   ForceFail_None, 0,
                                     CtrlNoXmitStat,   ForceFail_None, 0,
                                     CtrlNoXmitStat,   ForceFail_None, 0  );
                dma.lc_but_wait = LcButWait_None;
                dsi = 0;
            } else {
                ret = SiStartTestCase (&dma);
            }
            INC_ON_ERR (ret, errCount);
            if (    (dma.result [0].tx_rx_buf & 0xFFFF0000)
                 == (dma.r.ctrlr[0].tx_rx_buf & 0xFFFF0000) ) {
                change_period[i] = dma.w.timeout.start - lctrl.bd_write_time;
                sync_offset[i]   = (lctrl.bd_write_time - lctrl_but_sam_sync_time) % dma.button_period;
                next = TRUE;
                meas_num = 0;
                dsi = DSI;
                _TRACE(dsi,
                    fprintf(DBGOUT, "\n\t%s: Button change detected:\n\t\t"
                                    "sample: %d   but_rate %d   SI_CONFIG %08x\n\t\t"
                                    "button_period:\t\t\t%u\n\t\t"
                                    "dma.w.timeout.start:\t\t%llu\n\t\t"
                                    "dma.min_time_till_readable:\t%llu\n\t\t"
                                    "dma.max_time_till_readable:\t%llu\n\t\t"
                                    "change_period:\t\t\t%u\n\t\t"
                                    "diff from 3 sample periods:\t%i\n\t\t"
                                    "sync_offset:\t\t\t%u\n\t\t"
                                    , dma.testname, i+1, button_rate, IO_READ(SI_CONFIG_REG),
                                      dma.button_period, dma.w.timeout.start,
                                      dma.min_time_till_readable, dma.max_time_till_readable,
                                      change_period[i],
                                      (int)(dma.w.timeout.start - dma.max_time_till_readable),
                                      sync_offset[i]));
            } else if (
                    dma.w.timeout.start > dma.max_time_till_readable
                && (dma.w.timeout.start - dma.max_time_till_readable) > 10000000 ) {
                    fprintf(DBGOUT, "\n\t%s: Button change timed out:\n\t\t"
                                    "sample: %d   but_rate %d   SI_CONFIG %08x\n\t\t"
                                    "button_period:\t\t\t%u\n\t\t"
                                    "dma.w.timeout.start:\t\t%llu\n\t\t"
                                    "dma.min_time_till_readable:\t%llu\n\t\t"
                                    "dma.max_time_till_readable:\t%llu\n\t\t"
                                    , dma.testname, i+1, button_rate, IO_READ(SI_CONFIG_REG),
                                      dma.button_period, dma.w.timeout.start,
                                      dma.min_time_till_readable, dma.max_time_till_readable);
                    SiDefaults();
                    return SiLogResult(-1, dma.testname, "Button change timed out",
                                    button_rate, IO_READ(SI_CONFIG_REG), dma.button_period, i);
            }
        }

        dsi    = DSI;
        config = IO_READ(SI_CONFIG_REG);

        for (i = 0;  !ret && i < num_samples;  ++i) {
            unsigned int min_change_period = 3*dma.button_period - sync_offset[i] - 25000;
            unsigned int max_change_period = 3*dma.button_period - sync_offset[i] + 25000;

            _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: Sample info:  "
                    "\n\t\tsample %d   but_rate %d   SI_CONFIG %08x   button_period %u"
                    "\n\t\tmin_change_period %u   3*button_period %u   max_change_period %u"
                    "\n\t\tchange_period %u"
                    "\n\t\tdiff from 3 sample periods %d"
                    "\n\t\tsync_offset %u",
                    dma.testname, i+1, button_rate, config, dma.button_period,
                    min_change_period, 3*dma.button_period, max_change_period,
                    change_period[i], change_period[i] - 3*dma.button_period,  sync_offset[i] ));

            if ( change_period[i] <  min_change_period  ) {
                fprintf(DBGOUT, "\n\t%s: Button change detected earlier than 3 button sampling periods - 25us:  "
                                "but_rate %d   SI_CONFIG %08x  button_period %u  sync_offset %u  min_change_period %u  change_period: %u",
                                dma.testname, button_rate, config, dma.button_period, sync_offset[i], min_change_period, change_period[i]);
                SiDefaults();
                return SiLogResult(-1, dma.testname, "Button change detected earlier than 3 button sampling periods - 25us",
                                       button_rate, sync_offset[i], min_change_period, change_period[i]);
            } else if ( change_period[i] > max_change_period ) {
                fprintf(DBGOUT, "\n\t%s: Button sampling period variation too large:  "
                                "but_rate %d   SI_CONFIG %08x  button_period %u  sync_offset %u  min_change_period %u  change_period: %u",
                                dma.testname, button_rate, config, dma.button_period, sync_offset[i], min_change_period, change_period[i]);
                SiDefaults();
                return SiLogResult(-1, dma.testname, "Button sampling period variation too large",
                                       button_rate, sync_offset[i], min_change_period, change_period[i]);
            } else {
                 SiLogResult(0, dma.testname, "Button sampling period variation test ",
                               button_rate, sync_offset[i], min_change_period, change_period[i]);
            }
        }
    }

    errorTotal += errCount;

    return ((errCount == 0) ? 0 : -1);
}




int
SiTestLCtrlButDeglitch(int levels, int button_rate_arg, int extra3, int seed)
{
    int  ret = 0;
    int  errCount = 0;

    char description[MAX_DESCRIPTION_SIZE];
    char *des_template       = "Test lctrl button sample deglitch: %s";

    int  button_rate         = button_rate_arg ? button_rate_arg : 1;
    int  old_no_random_jsrst = no_random_jsrst;

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestLCtrlButDeglitch";
    dma.description = description;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tTest lctrl button sample deglitch"
        , dma.testname));

    plant(seed);

    SiDefaults();

    //##############################################################
    // Set buttons to 0
    // Set button rate to 1 unless specified otherwise
    // Use default jc_div = 31, tXfer = tHigh = tLow = 2000,
    //             jitter = 0
    // button samples should be every 1048576/2 ns (i.e. about 1/2 ms)
    // Set buttons on via bd for 1.25 sample period, verify no
    // change in button state
    // Set buttons off via bd, verify no change in button state
    // Verify buttons don't show up in dma button query within
    // the max time they would have shown up if we didn't turn them off.
    // Set buttons on for 2.25 sample period, verify they don't show as on
    // set buttons off, verify they don't show as on
    // Verify buttons don't show up in dma button query within
    // the max time they would have shown up if we didn't turn them off.

    no_random_jsrst = TRUE;

    dma.test_case_count ++;
    snprintf(description, sizeof description, des_template, "Set buttons to all off");
    SiSetupDmaTestParam(&dma);

    SiSetupButtonTest(0, &dma,        0,        0,         0, ForceFail_None, 0, 0);
    SiSetupStatusTest(1, &dma, type_L(), type_H(), cstatus(), ForceFail_None, 0, 1);
    SiSetupStatusTest(2, &dma, type_L(), type_H(), cstatus(), ForceFail_None, 0, 1);
    SiSetupStatusTest(3, &dma, type_L(), type_H(), cstatus(), ForceFail_None, 0, 1);

    ret = SiStartTestCase (&dma);
    INC_ON_ERR (ret, errCount);
    if(ret) goto end;

    setLctrlButRate(button_rate);

    ret = SiLCtrlButDeglitchVerify(&dma, levels, button_rate, 1, 4);
    INC_ON_ERR (ret, errCount);
    if(ret) goto end;

    ret = SiLCtrlButDeglitchVerify(&dma, levels, button_rate, 2, 4);
    INC_ON_ERR (ret, errCount);
    if(ret) goto end;


    SiLogResult(0, dma.testname, "lctrl button deglitch test completely successful",
                    button_rate, dma.button_period, IO_READ(SI_CONFIG_REG), 0);

      /* Reset Local controller after glicth test to make Frank's new module happy*/
    bd_si_ctrl_setup(0, LCTRL_XGLITCH, 0, 0);
    bd_si_ctrl_setup(0, LCTRL_YGLITCH, 0, 0);
    bd_si_ctrl_setup(0, CTRL_GLITCH_DETECT, 0, 0);
    bd_si_ctrl_setup(0, LCTRL_XMOVE, 0, 0);
    bd_si_ctrl_setup(0, LCTRL_YMOVE, 0, 0);
    SiResetLctrlJsXyStateData();

end:

    no_random_jsrst = old_no_random_jsrst;

    errorTotal += errCount;

    return ((errCount == 0) ? 0 : -1);
}




int
SiTestLCtrlJsxyDeglitch(int levels, int extra2, int extra3, int seed)
{
    int  ret = 0;
    int  errCount = 0;

    char  buf[128];
    char  description[MAX_DESCRIPTION_SIZE];
    char *des_template = "Test lctrl x,y sample deglitch: %s";
    int   i;
    int   old_no_random_jsrst = no_random_jsrst;

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestLCtrlJsxyDeglitch";
    dma.description = description;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tTest lctrl x,y sample deglitch"
        , dma.testname));

    plant(seed);

    SiDefaults();

    //##############################################################
    // Set x,y to 0
    //      A JSRST is done in SiInitCtrlSim() during SiDefaults()
    //      so x,y is at zero on entry.
    // Use default jc_div = 31, tXfer = tHigh = tLow = 2000,
    //             jitter = 0
    // Cause xglitch=0x01 via bd, verify no
    // change in x,y state
    // Cause xglitch=0x10 via bd, verify no
    // change in x,y state
    // Cause yglitch=0x01 via bd, verify no
    // change in x,y state
    // Cause yglitch=0x10 via bd, verify no
    // change in x,y state

    no_random_jsrst = TRUE;

    for (i = 0; !ret && i < 4;  i++)
    {
        int gbit  = (i % 2) + 1;
        int bdcmd = i < 2 ? LCTRL_XGLITCH : LCTRL_YGLITCH;
        char xory = i < 2 ? 'x' : 'y';

        _TRACE(dsi, fprintf(DBGOUT, "\n********* Glitch Test %d ********", i));
        dma.test_case_count ++;
        snprintf(buf, sizeof buf, "Verify %cglitch=%#x doesn't change x,y state", xory, gbit );
        snprintf(description, sizeof description, des_template, buf);
        SiSetupDmaTestParam(&dma);

        if (i == 2) {  /* Turn off XGlITCH */
             lctrl.last_x_known =FALSE;
	     lctrl.target_x = 0;
	     lctrl.xmove_start = 0;
             lctrl.inmotion_x    = TRUE;
             lctrl.keep_x_idle = 0;
             bd_si_ctrl_setup(0, LCTRL_XGLITCH, 0, 0);
             bd_si_ctrl_setup(0, LCTRL_XMOVE, 0, 0);
        }
        bd_si_ctrl_setup(0, bdcmd, gbit, 0);

        // Every DMA completion verifies that x,y didn't change if not expected
        // Passing 0,0 for x,y results in no additional x,y bd cmd
        SiSetupButtonTest(0, &dma, buttons(),        0,        0, ForceFail_None, 0, 0);
        SiSetupButtonTest(1, &dma, buttons(), jcount(), jcount(), ForceFail_None, 0, 0);
        SiSetupButtonTest(2, &dma, buttons(), jcount(), jcount(), ForceFail_None, 0, 0);
        SiSetupButtonTest(3, &dma, buttons(), jcount(), jcount(), ForceFail_None, 0, 0);

        ret = SiStartTestCase (&dma);

        INC_ON_ERR (ret, errCount);
    }

    if(ret) goto end;


    SiLogResult(0, dma.testname, "lctrl x,y deglitch test completely successful",
                    0, 0, 0, 0);

      /* Reset Local controller after glicth test to make Frank's new module happy*/
    bd_si_ctrl_setup(0, LCTRL_XGLITCH, 0, 0);
    bd_si_ctrl_setup(0, LCTRL_YGLITCH, 0, 0);
    bd_si_ctrl_setup(0, CTRL_GLITCH_DETECT, 0, 0);
    bd_si_ctrl_setup(0, LCTRL_XMOVE, 0, 0);
    bd_si_ctrl_setup(0, LCTRL_YMOVE, 0, 0);
    SiResetLctrlJsXyStateData();

end:

    no_random_jsrst = old_no_random_jsrst;

    errorTotal += errCount;

    return ((errCount == 0) ? 0 : -1);
}




int
SiTestLCtrlJsxy(int levels, int jitter, int extra3, int seed)
{
    //##############################################################
    // For (+x, -y), (+x, +y), (-x, -y), and (-x, +y)  counts:
    //   Cmd x,y to move part way to limit via bd and see that
    //   lctrl DMA button/xy query indicates they get there.
    //   Do an lctrl button test without changing x,y input and
    //   verify that x,y in lctrl DMA button/xy query doesn't change
    //   Cmd x and y beyond x,y limits and see that the querried
    //   value pegs at the limits.  Verify that subsequent movement
    //   behaves normally.
    //
    // Use the jitter value specified as an argument.

    int ret = 0;
    int errCount = 0;

    int  i, dx, dy, count_x, count_y;

    char  description[MAX_DESCRIPTION_SIZE] = "Clear lctrl JSRST";
    char *des_template     = "Test lctrl joystick %sx, %sy %s";
    char *sign[2]          = { "-", "+" };

    typedef struct { int x, y; } Pos1Neg0;

    Pos1Neg0  direction[] = { {1,0}, {1, 1}, {0,0}, {0,1} };

    int limit_x[] = { LCTRL_MIN_X, LCTRL_MAX_X };
    int limit_y[] = { LCTRL_MIN_Y, LCTRL_MAX_Y };

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestLCtrlJsxy";

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tTest lctrl joystick x,y movement"
        , dma.testname));

    plant(seed);

    lctrl.jitter = jitter;

    SiDefaults();

    dma.test_case_count ++;
    dma.description = description;
    SiSetupDmaTestParam(&dma);

    // A JSRST is done in SiInitCtrlSim() during SiDefaults().

    for ( i = 0;   !ret && i < NUM_ELEMENTS(direction);  ++i ) {
        // cmd via bd to move part way to limit,
        //      do button request until dest reached
        //      and no movement verified after reached
        // cmd via bd to move past the limit,
        //      do button request until dest reached
        //      and no movement verified after reached
        // cmd via bd to move part way away from limit
        //      do button request until dest reached
        //      and no movement verified after reached

        dx = direction[i].x;
        dy = direction[i].y;

        dma.test_case_count ++;
        snprintf(description, sizeof description, des_template, sign[dx], sign[dy], "movement");
        SiSetupDmaTestParam(&dma);
        count_x = (limit_x[dx] - lctrl.last_x)/(2 + (random() % 7));
        count_y = (limit_y[dy] - lctrl.last_y)/(2 + (random() % 7));
        ret = SiLctrlJsxyMoveAndVerify(&dma, buttons(), count_x, count_y, 0);
        if(ret) break;

        dma.test_case_count ++;
        snprintf(description, sizeof description, des_template, sign[dx], sign[dy], "limits");
        SiSetupDmaTestParam(&dma);
        count_x = 5 * limit_x[dx];
        count_y = 5 * limit_y[dy];
        ret = SiLctrlJsxyMoveAndVerify(&dma, buttons(), count_x, count_y, 0);
        if(ret) break;

        dma.test_case_count ++;
        snprintf(description, sizeof description, des_template, sign[dx?0:1], sign[dy?0:1], "after peg to limit");
        SiSetupDmaTestParam(&dma);
        count_x = -(limit_x[dx] / (2 + (random() % 7)));
        count_y = -(limit_y[dy] / (2 + (random() % 7)));
        ret = SiLctrlJsxyMoveAndVerify(&dma, buttons(), count_x, count_y, 0);
        if(ret) break;
    }

    errorTotal += errCount;

    return((errCount == 0) ? 0 : -1);
}





int
SiTestRandom(int num_random_tests, int forced_fail, int fail_param, int seed)
{
    int ret = 0;
    int errCount = 0;
    ForceFail force_fail = forced_fail;
    int i;
    char buf[128];
    int rsp_rand[4] = { 0, use_rsp_rand[1], use_rsp_rand[2], use_rsp_rand[3] };

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestRandom";

    if (force_fail != ForceFail_None) {
       snprintf(buf, sizeof buf,  "Random SI DMA Test:  forced failure %d:  %s:   fail_param %d",
            force_fail, force_fail_name[forced_fail], fail_param);
    } else  {
        char *resp_rand = "";
        char *use_xs = "";

        if ( fail_param & JChannel_Resp_Rand ) {
            SiSetJCtrlRespRand(1,1,1);
            resp_rand = ",  response randomization";
        }
        if (fail_param & StartWithXs) {
            dma.w.start_option = dma.r.start_option = ToStartDmaUse_AllBitsX;
            use_xs = ",  write Xs to start regs";
        }
        snprintf(buf, sizeof buf, "Random SI DMA Test:  no forced failures%s%s", resp_rand, use_xs);
    }


    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tDo SI DMA tests with random values for addresses"
        "\n\t\tctrlr buttons, x, y, type, and status."
        "\n\t\t%s"
        "\n\t\tnum_random_tests: %d"
        "\n\t\tforce_fail: %d"
        "\n\t\tfail_param: %d"
        "\n\t\tseed argument: %#x"
        , dma.testname, buf, num_random_tests, force_fail, fail_param, seed));

    plant(seed);

    SiDefaults();

    for (i = 0; !ret && i < num_random_tests;  i++)
    {
        ret = SiRunTestCase( &dma, buf,
                             CtrlRandomCmd, force_fail, fail_param,
                             CtrlRandomCmd, force_fail, fail_param,
                             CtrlRandomCmd, force_fail, fail_param,
                             CtrlRandomCmd, force_fail, fail_param);

        INC_ON_ERR (ret, errCount);
    }

    if ( fail_param & JChannel_Resp_Rand )
        SiSetJCtrlRespRand(rsp_rand[1], rsp_rand[2], rsp_rand[3]);

    if ( errCount == 0 )
        SiLogResult(0, dma.testname, buf, num_random_tests, force_fail, fail_param, seed);

    errorTotal += errCount;

    return((errCount == 0) ? 0 : -1);
}




int
SiTestLCtrlJSRST(int levels, int extra2, int extra3, int seed)
{
    int ret = 0;
    int errCount = 0;

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestLCtrlJSRST";

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tSet local ctrlr L, R, and START at same time to reset stick reference"
        "\n\t\tVerify that button status H[7] (i.e. JSRST) gets set."
        , dma.testname));

    plant(seed);

    SiDefaults();

    dma.test_case_count ++;
    dma.description = "Check reset stick reference";

    SiSetupDmaTestParam(&dma);

    // A JSRST is done in SiInitCtrlSim() during SiDefaults().
    // Make sure lctrl x/y isn't 0

    ret = SiLctrlJsxyMoveAndVerify(&dma, buttons(), jcount(), jcount(), 0);

    if(ret) goto end;


    SiSetupButtonTest(0, &dma, CTRL_JSRST_BUTTONS,
                                         jcount(),  jcount(), ForceFail_None, 0, 0);
    SiSetupStatusTest(1, &dma, type_L(), type_H(), cstatus(), ForceFail_None, 0, 1);
    SiSetupStatusTest(2, &dma, type_L(), type_H(), cstatus(), ForceFail_None, 0, 1);
    SiSetupStatusTest(3, &dma, type_L(), type_H(), cstatus(), ForceFail_None, 0, 1);

    ret = SiStartTestCase (&dma);
    INC_ON_ERR (ret, errCount);

end:
    errorTotal += errCount;

    return((errCount == 0) ? 0 : -1);
}




int
SiTestRegisters(int levels, int extra2, int extra3, int seed)
{
    int ret;
    int errCount = 0;

    unsigned int r, addr, rw, ro;
    char buf[512];
    char msg1[] = "check %s after reset:  %08x";
    char msg2[] = "extended check %s after reset";
    char msg3[] = "In secure mode after pin reset: MI_SEC_MODE_REG=%08x";
    unsigned long long now;
    u32 mi_sec_mode_reg;

    plant(seed);

   // Don't do SiDefaults() because we want to check registers after reset

    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin: SiTestRegisters:\n"));

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiTestRegisters:"
        "\n\t\tVerify reset state of SI status, dram addr, config and ctrl regs."));

    /* Do a pin reset for reset state test */
    /* enter secure mode */
    SIM_TIME(&now);
    IO_READ(MI_SEC_MODE_REG);
    IO_READ(BOOT_RAM_LO_START);
    _TRACE(dsi, fprintf(DBGOUT,"\n\tSiTestRegisters: Doing a pin reset at: %llu\n", now));
    pin_reset();
    SIM_TIME(&now);
    _TRACE(dsi, fprintf(DBGOUT,"\n\tSiTestRegisters: Pin reset done at: %llu\n", now));

    mi_sec_mode_reg = IO_READ(MI_SEC_MODE_REG);
    fprintf(DBGOUT,"\n\tSiTestRegisters: After pin reset: MI_SEC_MODE_REG %08lx   MI_CTRL_REG %08x\n"
                  , mi_sec_mode_reg, IO_READ(MI_CTRL_REG));
    if(mi_sec_mode_reg) {
        ret = -1;
        snprintf(buf, sizeof buf, msg3, mi_sec_mode_reg);
        SiLogRes(ret, "SiTestRegisters", buf, "");
        /* enter non-secure mode */
        mi_sec_mode_reg = mi_sec_mode_reg & 0x42;
        IO_WRITE(MI_SEC_MODE_REG, mi_sec_mode_reg);
    }

    ret = ((r=IO_READ(SI_STATUS_REG)) != 0) ? -1 : 0;
    INC_ON_ERR (ret, errCount);
    snprintf(buf, sizeof buf, msg1, "SI_STATUS_REG", r);
    SiLogRes(ret, "SiTestRegisters", buf, "");

    #if 0 // doesn't get initialized on reset
    ret = ((r=IO_READ(SI_DRAM_ADDR_REG)) != 0) ? -1 : 0;
    INC_ON_ERR (ret, errCount);
    snprintf(buf, sizeof buf, msg1, "SI_DRAM_ADDR_REG", r);
    SiLogRes(ret, "SiTestRegisters", buf, "");
    #endif

    ret = ((r=IO_READ(SI_CONFIG_REG)) != 0x1F820001) ? -1 : 0;
    INC_ON_ERR (ret, errCount);
    snprintf(buf, sizeof buf, msg1, "SI_CONFIG_REG", r);
    SiLogRes(ret, "SiTestRegisters", buf, "");

    ret = ((r=IO_READ(SI_CTRL_REG)) != 0x1F820001) ? -1 : 0;
    INC_ON_ERR (ret, errCount);
    snprintf(buf, sizeof buf, msg1, "SI_CTRL_REG", r);
    SiLogRes(ret, "SiTestRegisters", buf, "");

    ret = ext_mem_read_comp(SI_STATUS_REG, 0, 0);
    INC_ON_ERR (ret, errCount);
    snprintf(buf, sizeof buf, msg2, "SI_STATUS_REG");
    SiLogRes(ret, "SiTestRegisters", buf, "");

    #if 0 // doesn't get initialized on reset
    ret = ext_mem_read_comp(SI_DRAM_ADDR_REG, 0x03fffff8, 0x03fffff8);
    INC_ON_ERR (ret, errCount);
    snprintf(buf, sizeof buf, msg2, "SI_DRAM_ADDR_REG");
    SiLogRes(ret, "SiTestRegisters", buf, "");
    #endif

    ret = ext_mem_read_comp(SI_CONFIG_REG, 0x1F820001, 0x00000000);
    INC_ON_ERR (ret, errCount);
    snprintf(buf, sizeof buf, msg2, "SI_CONFIG_REG");
    SiLogRes(ret, "SiTestRegisters", buf, "");

    ret = ext_mem_read_comp(SI_CTRL_REG, 0x1F820001, 0x00000000);
    INC_ON_ERR (ret, errCount);
    snprintf(buf, sizeof buf, msg2, "SI_CTRL_REG");
    SiLogRes(ret, "SiTestRegisters", buf, "");


    //##############################################################
    // W/R data into SI STATUS reg
    // set unimplented bits to x
    // write data should be ignored
    // any write to bits 0-13 clears bit 12

    // bits  31-13 12  11-4  3  2     1  0
    //       rsvd  r   undoc r  undoc r  r

    // Always 0: 31-13 11-4  2-1
    // In this test we expect all bits to always read as 0

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiTestRegisters:  Test SI_STATUS_REG"));
    ret = ext_reg_test(SI_STATUS_REG, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFEFF4, 0x00000000);
    INC_ON_ERR (ret, errCount);
    SiLogRes(ret, "SiTestRegisters", "SI_STATUS_REG: ", "ext_reg_test");
    rw = 0; ro = 0xFFFFFFFF;
    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiTestRegisters: SI_STATUS_REG:\t rw: %08x  ro: %08x:  ",rw,ro));
    ret = register_test(SI_STATUS_REG, rw, ro, 0);
    INC_ON_ERR (ret, errCount);
    SiLogRes(ret, "SiTestRegisters", "SI_STATUS_REG: ", "register_test");

    //##############################################################
    // W/R data into SI DRAM address reg
    // bits  31-26     25-3  2-0
    //       ignored   rw    ignored

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiTestRegisters:  Test SI_DRAM_ADDR_REG"));
    ret = ext_reg_test(SI_DRAM_ADDR_REG, 0x03FFFFF8, 0x00000000, 0xFC000007, 0xFC000007, 0x00000000);
    INC_ON_ERR (ret, errCount);
    SiLogRes(ret, "SiTestRegisters", "SI_DRAM_ADDR_REG: ", "ext_reg_test");
    rw = 0x03FFFFF8; ro = 0xFC000007;
    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiTestRegisters: SI_DRAM_ADDR_REG:\t rw: %08x  ro: %08x:  ",rw,ro));
    ret = register_test(SI_DRAM_ADDR_REG, rw, ro, 0);
    INC_ON_ERR (ret, errCount);
    SiLogRes(ret, "SiTestRegisters", "SI_DRAM_ADDR_REG: ", "register_test");

    //##############################################################
    // W/R data to SI config reg addr
    // verify bits are rw or ro
    // bits  31-16  15-3  2-0
    //        rw    rsvd  ro
    // bits 0-7 are ro control reg bits
    // bits 1 & 2 are used for slave mode
    // bit 2 is "start xmit on write" and "xmit busy" on read
    // It is not clear what bit 1 & 2 should be on any specific read
    // Expect 0 in this test
    // Bits 1 and 2 will be tested in slave mode tests

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiTestRegisters:  Test SI_CONFIG_REG"));
    ret = ext_reg_test(SI_CONFIG_REG, 0xFFFF0000, 0x00000001, 0x0000FFFE, 0x0000FFF8, 0x00000000);
    INC_ON_ERR (ret, errCount);
    SiLogRes(ret, "SiTestRegisters", "SI_CONFIG_REG: ", "ext_reg_test");
    rw = 0xFFFF0000; ro = 0x0000FFFF;
    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiTestRegisters: SI_CONFIG_REG:\t rw: %08x  ro: %08x:  ",rw,ro));
    ret = register_test(SI_CONFIG_REG, rw, ro, 0);
    INC_ON_ERR (ret, errCount);
    SiLogRes(ret, "SiTestRegisters", "SI_CONFIG_REG: ", "register_test");

    //##############################################################
    // W/R data to SI ctrl reg addr
    // verify bits are rw or ro
    // bits  31-16  15-3  2   1   0
    //        r0    rsvd  rw  ro  rw
    // bits 8-31 are ro config reg bits
    // bits 1 & 2 are used for slave mode
    // bit 2 is "start xmit on write" and "xmit busy" on read
    // It is not clear what bit 1 & 2 should be on any specific read
    // Expect 0 in this test.
    // Bits 1 and 2 will be tested in slave mode tests

    // Need to write to config and ctrl first to set to known state,
    // since writing to ctrl should'nt change config bits,
    // but reading ctrl will read whatever is in the config bits.

    IO_WRITE(SI_CONFIG_REG, 0);
    if((r=IO_READ(SI_CONFIG_REG)) != 0x00000001) {
        fprintf(DBGOUT, "\n\tSiTestRegisters: SI_CONFIG_REG expected 0x00000001 after write 0, got %08x", r);
        ret = -1;
        INC_ON_ERR (ret, errCount);
    }
    IO_WRITE(SI_CTRL_REG, 0);
    if((r=IO_READ(SI_CTRL_REG)) != 0x00000000) {
        fprintf(DBGOUT, "\n\tSiTestRegisters: Error: SI_CTRL_REG expected 0 after write 0, got %08x", r);
        ret = -1;
        INC_ON_ERR (ret, errCount);
    }

    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiTestRegisters:  Test SI_CTRL_REG"));
    ret = ext_reg_test(SI_CTRL_REG, 0x00000001, 0x00000000, 0xFFFFFFFE, 0x0000FFF8, 0x00000000);
    INC_ON_ERR (ret, errCount);
    SiLogRes(ret, "SiTestRegisters", "SI_CTRL_REG: ", "ext_reg_test");
    rw = 0x00000001; ro = 0xFFFFFFFE;
    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiTestRegisters: SI_CTRL_REG:\t rw: %08x  ro: %08x:  ",rw,ro));
    ret = register_test(SI_CTRL_REG, rw, ro, 0);
    INC_ON_ERR (ret, errCount);
    SiLogRes(ret, "SiTestRegisters", "SI_CTRL_REG: ", "register_test");

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tSiTestRegisters:  read/write/read to old PIF addressses"));

    ret = 0;
    for (addr=PIF_RAM_START; addr < PIF_RAM_END; addr+=4) {
        if (ext_mem_read_comp(addr, 0, 0) != 0) {
            fprintf(DBGOUT, "\n\tSiTestRegisters: Error: PIF RAM read returned non-zero");
            ret = -1;
            INC_ON_ERR (ret, errCount);
            break;
        }
        IO_WRITE(addr, 0xFFFFFFFF);
        if (ext_mem_read_comp(addr, 0, 0) != 0) {
            fprintf(DBGOUT, "\n\tSiTestRegisters: Error: PIF RAM read returned non-zero after write all ones");
            ret = -1;
            INC_ON_ERR (ret, errCount);
            break;
        }
    }

    ret |= SiMemWriteRead(PIF_RAM_START, 0, 0xFFFFFFFF, (PIF_RAM_END+1) - PIF_RAM_START);
    SiLogRes(ret, "SiTestRegisters", "check PIF Ram after reset", "");

    SiJctrlSetReset(0); // SiDefaults of next test will wait for reset

    if (errCount) {
        errorTotal += errCount;
        SiLogRes(-1, "SiTestRegisters", "", "");
    }

    SIM_TIME(&now);
    _TRACE(dsi, fprintf(DBGOUT,"\n\tSiTestRegisters: InitDDR at: %llu\n", now));
    InitDDR(0x0, 0x0, 0x0, 0x0);
    SIM_TIME(&now);
    _TRACE(dsi, fprintf(DBGOUT,"\n\tSiTestRegisters: InitDDR done at: %llu\n", now));

    return ((errCount == 0) ? 0 : -1);

}






int
SiTestBugFixes(int extra1, int extra2, int extra3, int seed)
{
    int ret;
    int errCount = 0;

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestBugFixes";

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tThis test is for testing specific miscellaneous bug fixes."
        "\n\t\tIt can be used to test fixes for bugs that show up for"
        "\n\t\trandom values that may or may not occur in other tests."
        , dma.testname));

    plant(seed);

    SiDefaults();

    {//####################### Start bug 1481 #########################

        dma.description = "Test fix for bug 1481 - SI lctrl error bits anomaly for unsupported cmd with invalid tx size";
        dma.test_case_count ++;
        SiSetupDmaTestParam(&dma);

        //##########################################
        // try invalid tx_size for the cmd

        SiSetupUnsupCmdTest (0, &dma, 0x76, 0x0c230000, ForceFail_tx_InvalidForCmdType, 1, 0);
        SiSetupUnsupCmdTest (1, &dma, 0x61, 0xd1c83c61, ForceFail_tx_InvalidForCmdType, 1, 0);
        SiSetupUnsupCmdTest (2, &dma, 0x9e, 0xa84dc09e, ForceFail_tx_InvalidForCmdType, 1, 0);
        SiSetupUnsupCmdTest (3, &dma, 0x6d, 0x131c7e6d, ForceFail_tx_InvalidForCmdType, 1, 0);

        _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiRunTestCase %d: %s",
           dma.testname, dma.test_case_count, dma.description));

        ret = SiStartTestCase (&dma);

        INC_ON_ERR (ret, errCount);

        errorTotal += errCount;

        return ((errCount == 0) ? 0 : -1);

    }//####################### End bug 1481 ##########################


    errorTotal += errCount;

    return((errCount == 0) ? 0 : -1);
}



#if 0

int
SiTestForDebug(int extra1, int extra2, int extra3, int seed)
{
    int ret;
    int errCount = 0;

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = "SiTestForDebug";

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tThis test is for debugging."
        , dma.testname));

    plant(seed);

    SiDefaults();

    dma.description = "read with rx_size < will be received";
    dma.test_case_count ++;
    SiSetupDmaTestParam(&dma);

    SiSetupReadTest   (0, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 17, 0);
    SiSetupReadTest   (1, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 17, 0);
    SiSetupReadTest   (2, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 17, 0);
    SiSetupReadTest   (3, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 17, 0);

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiRunTestCase %d: %s",
    dma.testname, dma.test_case_count, dma.description));

    ret = SiStartTestCase (&dma);

    INC_ON_ERR (ret, errCount);


    dma.description = "read with rx_size < will be received";
    dma.test_case_count ++;
    SiSetupDmaTestParam(&dma);

    SiSetupReadTest   (0, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 5, 0);
    SiSetupReadTest   (1, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 5, 0);
    SiSetupReadTest   (2, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 5, 0);
    SiSetupReadTest   (3, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 5, 0);

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiRunTestCase %d: %s",
    dma.testname, dma.test_case_count, dma.description));

    ret = SiStartTestCase (&dma);

    INC_ON_ERR (ret, errCount);


    dma.description = "read with rx_size < will be received";
    dma.test_case_count ++;
    SiSetupDmaTestParam(&dma);

    SiSetupReadTest   (0, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 4, 0);
    SiSetupReadTest   (1, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 4, 0);
    SiSetupReadTest   (2, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 4, 0);
    SiSetupReadTest   (3, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 4, 0);

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiRunTestCase %d: %s",
    dma.testname, dma.test_case_count, dma.description));

    ret = SiStartTestCase (&dma);

    INC_ON_ERR (ret, errCount);


    dma.description = "read with rx_size < will be received";
    dma.test_case_count ++;
    SiSetupDmaTestParam(&dma);

    SiSetupReadTest   (0, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 3, 0);
    SiSetupReadTest   (1, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 3, 0);
    SiSetupReadTest   (2, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 3, 0);
    SiSetupReadTest   (3, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 3, 0);

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiRunTestCase %d: %s",
    dma.testname, dma.test_case_count, dma.description));

    ret = SiStartTestCase (&dma);

    INC_ON_ERR (ret, errCount);



    dma.description = "read with rx_size < will be received";
    dma.test_case_count ++;
    SiSetupDmaTestParam(&dma);

    SiSetupReadTest   (0, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 2, 0);
    SiSetupReadTest   (1, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 2, 0);
    SiSetupReadTest   (2, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 2, 0);
    SiSetupReadTest   (3, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 2, 0);

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiRunTestCase %d: %s",
    dma.testname, dma.test_case_count, dma.description));

    ret = SiStartTestCase (&dma);

    INC_ON_ERR (ret, errCount);



    dma.description = "read with rx_size < will be received";
    dma.test_case_count ++;
    SiSetupDmaTestParam(&dma);

    SiSetupReadTest   (0, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 1, 0);
    SiSetupReadTest   (1, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 1, 0);
    SiSetupReadTest   (2, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 1, 0);
    SiSetupReadTest   (3, &dma, read_addr(),  read_data(), ForceFail_rx_InvalidForCmdType, 1, 0);

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiRunTestCase %d: %s",
    dma.testname, dma.test_case_count, dma.description));

    ret = SiStartTestCase (&dma);

    INC_ON_ERR (ret, errCount);


#if 0

    dma.description = "unsup with rx_size < will be received";
    dma.test_case_count ++;
    SiSetupDmaTestParam(&dma);

    SiSetupUnsupCmdTest (0, &dma, 0x76, 0x0c237393, ForceFail_rx_InvalidForCmdType, 1, 0);
    SiSetupUnsupCmdTest (1, &dma, 0x61, 0xd1c83c63, ForceFail_rx_InvalidForCmdType, 1, 0);
    SiSetupUnsupCmdTest (2, &dma, 0x9e, 0xa84dc099, ForceFail_rx_InvalidForCmdType, 1, 0);
    SiSetupUnsupCmdTest (3, &dma, 0x6d, 0x131c7e6f, ForceFail_rx_InvalidForCmdType, 1, 0);

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiRunTestCase %d: %s",
    dma.testname, dma.test_case_count, dma.description));

    ret = SiStartTestCase (&dma);

    INC_ON_ERR (ret, errCount);


    ret = SiRunTestCase(&dma, "no xmit, rx size 0",
                CtrlNoXmitStat, ForceFail_rx_Zero, 0,
                CtrlNoXmitStat, ForceFail_rx_Zero, 0,
                CtrlNoXmitStat, ForceFail_rx_Zero, 0,
                CtrlNoXmitStat, ForceFail_rx_Zero, 0 );

    INC_ON_ERR (ret, errCount);


    ret = SiRunTestCase( &dma, "Query button/stick with rx_size == 3",
                         CtrlQueryButtons, ForceFail_rx_InvalidForCmdType, 3,
                         CtrlQueryButtons, ForceFail_rx_InvalidForCmdType, 3,
                         CtrlQueryButtons, ForceFail_rx_InvalidForCmdType, 3,
                         CtrlQueryButtons, ForceFail_rx_InvalidForCmdType, 3  );

    INC_ON_ERR (ret, errCount);

    ret = SiRunTestCase( &dma, "Query button/stick with rx_size == 5",
                         CtrlQueryButtons, ForceFail_rx_InvalidForCmdType, 5,
                         CtrlQueryButtons, ForceFail_rx_InvalidForCmdType, 5,
                         CtrlQueryButtons, ForceFail_rx_InvalidForCmdType, 5,
                         CtrlQueryButtons, ForceFail_rx_InvalidForCmdType, 5  );

    INC_ON_ERR (ret, errCount);


    dma.description = "unsup with rx_size > will be received";
    dma.test_case_count ++;
    SiSetupDmaTestParam(&dma);

    SiSetupUnsupCmdTest (0, &dma, 0x76, 0x0c237393, ForceFail_rx_InvalidForCmdType, 6, 0);
    SiSetupUnsupCmdTest (1, &dma, 0x61, 0xd1c83c63, ForceFail_rx_InvalidForCmdType, 6, 0);
    SiSetupUnsupCmdTest (2, &dma, 0x9e, 0xa84dc099, ForceFail_rx_InvalidForCmdType, 6, 0);
    SiSetupUnsupCmdTest (3, &dma, 0x6d, 0x131c7e6f, ForceFail_rx_InvalidForCmdType, 6, 0);

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiRunTestCase %d: %s",
    dma.testname, dma.test_case_count, dma.description));

    ret = SiStartTestCase (&dma);

    INC_ON_ERR (ret, errCount);


    ret = SiRunTestCase( &dma, "Query button/stick with rx_size == 0",
                         CtrlQueryButtons, ForceFail_rx_Zero, 0,
                         CtrlQueryButtons, ForceFail_rx_Zero, 0,
                         CtrlQueryButtons, ForceFail_rx_Zero, 0,
                         CtrlQueryButtons, ForceFail_rx_Zero, 0  );

    INC_ON_ERR (ret, errCount);


    dma.description = "unsup with rx_size == 0";
    dma.test_case_count ++;
    SiSetupDmaTestParam(&dma);

    SiSetupUnsupCmdTest (0, &dma, 0x76, 0x0c237393, ForceFail_rx_Zero, 0, 0);
    SiSetupUnsupCmdTest (1, &dma, 0x61, 0xd1c83c63, ForceFail_rx_Zero, 0, 0);
    SiSetupUnsupCmdTest (2, &dma, 0x9e, 0xa84dc099, ForceFail_rx_Zero, 0, 0);
    SiSetupUnsupCmdTest (3, &dma, 0x6d, 0x131c7e6f, ForceFail_rx_Zero, 0, 0);

    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: SiRunTestCase %d: %s",
    dma.testname, dma.test_case_count, dma.description));

    ret = SiStartTestCase (&dma);

    INC_ON_ERR (ret, errCount);


#endif

#if 0

    {//####################### Start Debug 1#########################

        int i;
        dma.description = "Try a bunch of unsuported cmds with random fail";

        //##############################################################
        //  Test unsupported lctrl cmd types (only 0, 1, or 255 are supported)
        //  without other cmd errors and use the opportunity to test
        //  random failures with unsupported (i.e. passthrough) jc cmds.
        //  All cmd types (i.e. 0-255) are valid for jc's
        //  Unsupported cmd's with specific failures are also
        //  tested in the prev loop.

        for (i = 0;  i < 100;  ++i) {
            ret = SiRunTestCase(&dma, "Unsupported command types",
                         CtrlJcUnsupCmd, ForceFail_None,   0,
                         CtrlJcUnsupCmd, ForceFail_Random, 0,
                         CtrlJcUnsupCmd, ForceFail_Random, 0,
                         CtrlJcUnsupCmd, ForceFail_Random, 0 );
            INC_ON_ERR (ret, errCount);
            if (errCount)
                return -1;
        }

        errorTotal += errCount;

        return ((errCount == 0) ? 0 : -1);

    }//####################### End Debug 1 ##########################

    dma.description = "Wait for no x,y motion before reset without modifying bd";

    ret = SiLctrlJsxyMoveAndVerify(&dma, buttons(), 50, 45, 1);


    dma.description = "Do a reset without modifying bd";

    setCtrlCmdData(&dma.w.ctrlr[0], 0xFF, 0, 1, 3, CtrlReset, 0);
    setCtrlCmdData(&dma.r.ctrlr[0], 0xFF, 0, 1, 3, CtrlReset, 0);

    ret = SiStartTestCase (&dma);

    INC_ON_ERR (ret, errCount);

    dma.description = "Wait for no x,y motion after reset without modifying bd";

    ret = SiLctrlJsxyMoveAndVerify(&dma, buttons(), 0, 0, 1);


    ret = SiRunTestCase( &dma, "Do a real reset",
                         CtrlReset,      ForceFail_None, 0,
                         CtrlNoXmitStat, ForceFail_None, 0,
                         CtrlNoXmitStat, ForceFail_None, 0,
                         CtrlNoXmitStat, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);


    dma.description = "Wait for no x,y motion after real reset";

    ret = SiLctrlJsxyMoveAndVerify(&dma, buttons(), 0, 0, 1);

    INC_ON_ERR (ret, errCount);


   dma.description = "Wait for no x,y motion before no xmit reset";

    ret = SiLctrlJsxyMoveAndVerify(&dma, buttons(), 33, 22, 1);


    ret = SiRunTestCase( &dma, "Do a no xmit reset",
                         CtrlNoXmitRset, ForceFail_None, 0,
                         CtrlNoXmitStat, ForceFail_None, 0,
                         CtrlNoXmitStat, ForceFail_None, 0,
                         CtrlNoXmitStat, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);

    dma.description = "Wait for no x,y motion after no xmit reset";

    ret = SiLctrlJsxyMoveAndVerify(&dma, buttons(), 0, 0, 1);

    INC_ON_ERR (ret, errCount);

#endif


    errorTotal += errCount;

    return((errCount == 0) ? 0 : -1);
}


#endif



int
SiSmJChanResetTest()
{
    int ret;
    int errCount = 0;

    char reg_info[128];
    unsigned int status, config, mi_intr, si_intr, ints;

    static char rn[] = "SiSmJChanResetTest";

    SiDmaTestParam *dmas = &dma_slave_transactions;
    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = rn;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:  In slave mode, test reset of joy channel by master model"
        ,rn));

    isSlaveMode = TRUE;

    SiDefaults();

    // note: A cmd receive is normally kept active at all times we are not doing a different DMA;
    //       To find end of reset, we loop trying transactions til one works.
    //       The master model doesn't currently support resets during cmd xmit or data recv.
    // 1. with rcv active (before cmd rqstd) start a reset, after reset should have completed, check,  
    //     should get reset error bit set (plus maybe no response)
    // 2. with rcv active (before cmd rqstd) start a reset, after it should have completed, rqst cmd and check,
    //     should get reset error bit set (plus maybe no response)
    // 3. with rcv active (before cmd rqstd) start a reset, during reset, check,
    //     should get reset error bit set (plus maybe no response)
    // 4. before start cmd receive start a reset, start rcv during reset, check,
    //     should get reset error bit set
    // 5. reset during reception of a cmd from the master

    // 1. with rcv active (before cmd rqstd) start a reset, after reset should have completed, check,
    //     should get reset error bit set (plus maybe no response)


    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: 1, before request master to do a joy chan reset:  %s", rn, reg_info));
    SiWait(DEF_SmJCResetDelay);
    if(isUseMJCTRL) {
        bd_si_ctrl_setup(MJCTRL, MJCTRL_CTL, MJCTRL_JCRESET, 0);
        SiWait(DEF_SmJCResetDelay);
    } else {
        SiJctrlResetAndClear(JCTRL_1);
    }

    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: 1. after request master to do a joy channel reset:  %s", rn, reg_info));

    isSmCheckRcvNoRqstCmd  = TRUE;
    dmas->r.ctrlr[1].error = CTRL_ERR_CTLR_RESET|CTRL_ERR_NO_RESPONSE;
    ret = SiRunTestCase( &dma, "1. button requests after rqst master to reset jchan",
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);
    if(ret) goto end;

    isSmCheckRcvNoRqstCmd  = FALSE;
    isSmPollTilJCResetDone = TRUE;
    while(isSmPollTilJCResetDone) {
        ret = SiRunTestCase( &dma, "1. poll til jchan reset done",
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0  );
        if(isSmPollTilJCResetDone)
            isSmCheckRcvNoRqstCmd  = TRUE;  // master model will send cmd already requested after reset is done
        else
            isSmCheckRcvNoRqstCmd  = FALSE; // in case more than 1 iteration was done

        INC_ON_ERR (ret, errCount);
        if(ret) goto end;
    }
    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: 1. Poll for jchan reset done:  %s", rn, reg_info));

    // 2. with rcv active (before cmd rqstd) start a reset, after it should have completed, rqst cmd and check,
    //     should get reset error bit set (plus maybe no response)

    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: 2. before request master to do a joy chan reset:  %s", rn, reg_info));
    if(isUseMJCTRL) {
        bd_si_ctrl_setup(MJCTRL, MJCTRL_CTL, MJCTRL_JCRESET, 0);
        SiWait(DEF_SmJCResetDelay);
    } else {
        SiJctrlResetAndClear(JCTRL_1);
    }

    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: 2. after request master to do a joy channel reset:  %s", rn, reg_info));

    isSmCheckRcvNoRqstCmd  = FALSE;
    dmas->r.ctrlr[1].error = CTRL_ERR_CTLR_RESET|CTRL_ERR_NO_RESPONSE;
    ret = SiRunTestCase( &dma, "2. button requests after rqst master to reset jchan",
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);
    if(ret) goto end;

    if(isUseMJCTRL)
        isSmCheckRcvNoRqstCmd  = TRUE;  // cmd rqsted above hasn't been rcv'd yet
    isSmPollTilJCResetDone = TRUE;
    while(isSmPollTilJCResetDone) {
        ret = SiRunTestCase( &dma, "2. poll til jchan reset done",
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0  );
        if(isUseMJCTRL && isSmPollTilJCResetDone)
            isSmCheckRcvNoRqstCmd  = TRUE;  // master model will send cmd already requested after reset is done
        else
            isSmCheckRcvNoRqstCmd  = FALSE; // in case more than 1 iteration was done

        INC_ON_ERR (ret, errCount);
        if(ret) goto end;
    }
    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: 2. Poll for jchan reset done:  %s", rn, reg_info));

    // 3. with rcv active (before cmd rqstd) start a reset, during reset, check,  
    //     should get reset error bit set (plus maybe no response)

    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: 3. before request master to do a joy chan reset:  %s", rn, reg_info));
    if(isUseMJCTRL) {
        bd_si_ctrl_setup(MJCTRL, MJCTRL_CTL, MJCTRL_JCRESET, 0);
    } else {
        SiJctrlSetReset(JCTRL_1);
    }

    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: 3. after request master to do a joy channel reset:  %s", rn, reg_info));

    isSmCheckRcvNoRqstCmd  = TRUE;
    dmas->r.ctrlr[1].error = CTRL_ERR_CTLR_RESET|CTRL_ERR_NO_RESPONSE;
    ret = SiRunTestCase( &dma, "3. button requests after rqst master to reset jchan",
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);
    if(ret) goto end;

    if(!isUseMJCTRL) {
        SiJctrlWaitReset(JCTRL_1);
        SiJctrlClearReset(JCTRL_1);
    }

    isSmCheckRcvNoRqstCmd  = FALSE;
    isSmPollTilJCResetDone = TRUE;
    while(isSmPollTilJCResetDone) {
        ret = SiRunTestCase( &dma, "3. poll til jchan reset done",
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0  );
        if(isUseMJCTRL && isSmPollTilJCResetDone)
            isSmCheckRcvNoRqstCmd  = TRUE;  // master model will send cmd already requested after reset is done
        else
            isSmCheckRcvNoRqstCmd  = FALSE; // in case more than 1 iteration was done

        INC_ON_ERR (ret, errCount);
        if(ret) goto end;
    }
    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: 3. Poll for jchan reset done:  %s", rn, reg_info));

    // 4. before start cmd receive start a reset, start rcv during reset, check,
    //     should get reset error bit set

    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: 4. before start cmd receive start a reset:  %s", rn, reg_info));
    isSmJCResetBeforeRcv = TRUE;

    isSmCheckRcvNoRqstCmd  = FALSE;
    ret = SiRunTestCase( &dma, "4. after this transaction, a jchan reset will be issued before the DMA read that waits for master cmd",
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);
    if(ret) goto end;

    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi, fprintf(DBGOUT, "\n\t%s: 4. after request master to do a joy channel reset:  %s", rn, reg_info));

    isSmCheckRcvNoRqstCmd  = TRUE;
    dmas->r.ctrlr[1].error = CTRL_ERR_CTLR_RESET;
    ret = SiRunTestCase( &dma, "4. button requests after rqst master to reset jchan",
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);
    if(ret) goto end;

    if(!isUseMJCTRL) {
        SiJctrlWaitReset(JCTRL_1);
        SiJctrlClearReset(JCTRL_1);
    }

    isSmCheckRcvNoRqstCmd  = FALSE;
    isSmPollTilJCResetDone = TRUE;
    while(isSmPollTilJCResetDone) {
        ret = SiRunTestCase( &dma, "4. poll til jchan reset done",
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0,
                            CtrlQueryButtons, ForceFail_None, 0  );
        if(isUseMJCTRL && isSmPollTilJCResetDone)
            isSmCheckRcvNoRqstCmd  = TRUE;  // master model will send cmd already requested after reset is done
        else
            isSmCheckRcvNoRqstCmd  = FALSE; // in case more than 1 iteration was done

        INC_ON_ERR (ret, errCount);
        if(ret) goto end;
    }
    SiRegInfo(reg_info, &status, &config, &mi_intr, &si_intr, &ints);
    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: 4. Poll for jchan reset done:  %s", rn, reg_info));


    // 5. reset jchan 1 during reception of a cmd from the master, check,
    //     should get reset error and no response bit set

    logMsg(rn);
    _TRACE(dsi,fprintf(DBGOUT, "\n\t%s: 5. reset jchan 1 during reception of a cmd from master:  %s", rn, reg_info));

    isSmJCResetDurCmd = TRUE;
    isSmCheckRcvNoRqstCmd  = FALSE;
    dmas->r.ctrlr[1].error = CTRL_ERR_CTLR_RESET|CTRL_ERR_NO_RESPONSE;
    ret = SiRunTestCase( &dma, "5. reset jchan 1 during reception of a cmd from master",
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);
    if(ret) goto end;

    isSmJCResetDurCmd = FALSE;



end:
    // SiDefaults reinits the static variables for subsequent tests

    errorTotal += errCount;

    return((errCount == 0) ? 0 : -1);
}



int
SiSmCoQuery()
{
    int ret;
    int errCount = 0;

    static char rn[] = "SiSmCoQuery";

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = rn;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:  In slave mode, test button query while receiving cmd from master"
        ,rn));

    isSlaveMode = TRUE;
    isCoQuerySlaveButtons = TRUE;  // not changed by SiDefaults

    SiDefaults();

    ret = SiRunTestCase( &dma, "test button query while receiving cmd from master",
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0,
                        CtrlQueryButtons, ForceFail_None, 0  );

    INC_ON_ERR (ret, errCount);

    errorTotal += errCount;

    return((errCount == 0) ? 0 : -1);
}



int
SiSmTestErr()
{
    int ret;
    int errCount = 0;
    static char rn[] = "SiSmTestErr";

    CtrlCmdCode cmd_type[] = { CtrlQueryStatus,
                               CtrlQueryButtons,
                               CtrlRead,
                               CtrlWrite,
                               CtrlReset,
                               CtrlJcUnsupCmd };

    int i, num_cmd_types = NUM_ELEMENTS(cmd_type);

    char description[MAX_DESCRIPTION_SIZE];

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = rn;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tTest truncated slave mode cmd from master"
        "\n\t\tTest collision err during slave mode response"
        "\n\t\tTest frame err on slave mode cmd", rn));

    isSlaveMode = TRUE;

    SiDefaults();

    for(i=0; i<num_cmd_types; ++i) {

        CtrlCmdCode cmd = cmd_type[i];

        isSmTruncCmd = TRUE;
        snprintf(description, sizeof description, "%s:  truncate slave mode cmd from master", cmdName(cmd));
        ret = SiRunTestCase( &dma, description,
                            cmd, ForceFail_None, 0,
                            cmd, ForceFail_None, 0,
                            cmd, ForceFail_None, 0,
                            cmd, ForceFail_None, 0  );
        isSmTruncCmd = FALSE;
        INC_ON_ERR (ret, errCount);

        snprintf(description, sizeof description, "%s:  good slave mode cmd from master after trucate error", cmdName(cmd));
        ret = SiRunTestCase( &dma, description,
                            cmd, ForceFail_None, 0,
                            cmd, ForceFail_None, 0,
                            cmd, ForceFail_None, 0,
                            cmd, ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);

        isSmCmdFrameErr = TRUE;
        snprintf(description, sizeof description, "%s:  frame err on slave mode cmd", cmdName(cmd));
        ret = SiRunTestCase( &dma, description,
                            cmd, ForceFail_None, 0,
                            cmd, ForceFail_Frame, 0,
                            cmd, ForceFail_NoResponse, 0,
                            cmd, ForceFail_Collision, 0  );
        isSmCmdFrameErr = FALSE;
        INC_ON_ERR (ret, errCount);

        if( cmd != CtrlJcUnsupCmd ) {
            isSmRspCollision = TRUE;
            snprintf(description, sizeof description, "%s:  collision err during slave mode response", cmdName(cmd));
            ret = SiRunTestCase( &dma, description,
                                cmd, ForceFail_None, 0,
                                cmd, ForceFail_None, 0,
                                cmd, ForceFail_None, 0,
                                cmd, ForceFail_None, 0  );
            isSmRspCollision = FALSE;
            INC_ON_ERR (ret, errCount);
        }
    }

    errorTotal += errCount;

    return((errCount == 0) ? 0 : -1);
}



int
SiSmTestUnsup()
{
    int ret;
    int errCount = 0;
    static char rn[] = "SiSmTestUnsup";
    CtrlCmdCode specific_cmd[] = {0x1f, 0x20};
    int i, num_specific_cmd = NUM_ELEMENTS(specific_cmd);

    char description[MAX_DESCRIPTION_SIZE];

    SiDmaTestParam dma;

    memset(&dma, 0, sizeof(SiDmaTestParam));

    dma.testname = rn;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tTest slave mode unsupported cmds from master", rn));

    isSlaveMode = TRUE;

    SiDefaults();

    for(i=0; i<(5+num_specific_cmd); ++i) {
        CtrlCmdCode cmd = (i<num_specific_cmd) ? specific_cmd[i] : unsupportedCmd();
        snprintf(description, sizeof description, "slave mode unsupported cmd %#x from master", cmd);
        ret = SiRunTestCase( &dma, description,
                            cmd, ForceFail_None, 0,
                            cmd, ForceFail_None, 0,
                            cmd, ForceFail_None, 0,
                            cmd, ForceFail_None, 0  );

        INC_ON_ERR (ret, errCount);
    }

    errorTotal += errCount;

    return((errCount == 0) ? 0 : -1);
}








int
SiTestSlave(int levels, int testid, int extra3, int seed)
{
    int errCount = 0;
    int i,fst,nst;

    static char rn[] = "SiTestSlave";

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
        "\n\t\tTest slave mode: testid %08x  levels %d"
        , rn, testid, levels));

    plant(seed);

    isSlaveMode = TRUE;

    // SiDefaults/SiInitCtrlSim will setup slave mode because isSlaveMode is true

    // When you run the normal SI dma tests in slave mode, all jctrl
    // cmds are changed to no_xmit cmds.

    // Instead, the cmds that are setup for lctrl are fed to the master model
    // so they are received over jctrl 1 and then an lctrl transaction is 
    // used to get the response.
    
    // See SiSlaveTest for extensive comments on slave mode.

    if(testid) {
        fst = testid;
        nst = 1;
    } else {
        fst = 0;
        nst = levels ? levels:31; // max num slave tests
    }

    isUseMJCTRL = TRUE;

    _TRACE(dsi,fprintf(DBGOUT,"\n\tRun slave mode tests %d -> %d", fst, fst+nst-1));

    for (i=fst; i<fst+nst; i++) {
        switch(i) {
          case  0:
            if(SiSmCoQuery()) goto end;
            // leaves isCoQuerySlaveButtons = TRUE
            // set to false here if default desired to be FALSE
            isCoQuerySlaveButtons = FALSE;
            break;
          case  1:
            if(SiTestValidCtrlCmds(0, 0, 0, 0)) goto end;
            break;
          case  2:
            if(SiSmJChanResetTest()) goto end;
            break;
          case  3:
            isUseMJCTRL = FALSE;
            if(SiSmTestErr()) goto end;
            break;
          case  4:
            isUseMJCTRL = FALSE;
            if(SiSmTestUnsup()) goto end;
            break;
          case  5:
            isUseMJCTRL = FALSE;
            if(SiTestRandom(5, ForceFail_None, JChannel_Resp_Rand, 0)) goto end;
            break;
          case  6:
            SiTestRandom(1, ForceFail_None, StartWithXs, 0);
            break;
          default:
            break;
        }
    }

end:
    errorTotal += errCount;

    return SiLogResult(errCount==0?0:-1, "SiTestSlave", "", testid, 0, 0, 0);
}



int
SiTestDmaStress(char* num_iterations)
{
    int    ret,i,iterations;
    static char rn[] = "SiTestDmaStress";
    unsigned int config;

    //SiDmaTestParam dma;

    //memset(&dma, 0, sizeof(SiDmaTestParam));

    //dma.testname = rn;

    //##############################################################
    _TRACE(dsi, fprintf(DBGOUT, "\n\tBegin %s:"
            "\n\t\tJust do short DMA writes to stress random env"
            , rn));

    //SiDefaults();

    config = IO_READ(SI_CTRL_REG);
    if (config & 1) {
        _TRACE(dsi,fprintf(DBGOUT,"\n\tJCRST found to be set:  config/ctrl %08x", config));
        SiJctrlWaitReset(0);
        SiJctrlClearReset(0);
    }

    _TRACE(dsi,fprintf(DBGOUT,"\n\tSet but_rate to 0 to sample once per jc_clk"));
    setLctrlButRate(0);

    //dma.test_case_count ++;
    //dma.description = "";

    //SiInitDmaTestParm(&dma);

    if(num_iterations)
        iterations=strtoul(num_iterations,NULL,10);
    else
        iterations=1;

    for(i=0,ret=0; !ret && i<iterations; i++) {
        ret = SiDma(Dir_From, bufAddr(), random(), 0);
        //ret = SiDmaWrite(&dma);
        SiLogResult(ret, rn, "", i+1,0,0,0);
    }

    SiLogRes(ret, rn, "", "");

    return ret;
}


int
SiTestRandEnv(int testid, char* arg1, char* arg2, int seed)
{
    // Run an Si test in the random env

    int  i;
    char *s;
    char iosim_seed[16];
    char iosim_addr[16];
    char *iosim_mem_size;

    dedicated_env = 0;
    random_env    = 1;

    s = getenv("IOSIM_SEED");
    i = s ? atoi(s):0;
    random_seed = seed ? seed : i;
    srandom(random_seed);
    if (s) snprintf(iosim_seed,sizeof iosim_seed,"%#08x",i);
    else   strcpy(iosim_seed,"NONE");

    s = getenv("IOSIM_ADDR");
    if (s) {
        si_ltd_mem_start = atoi(s);
        snprintf(iosim_addr,sizeof iosim_addr,"%#08x",si_ltd_mem_start);
    } else
        strcpy(iosim_addr,"NONE");

    s = iosim_mem_size = getenv("IOSIM_MEM_SIZE");
    if (s)
        si_ltd_mem_size = atoi(s);
    else
        return SiLogRes(-1, "SiTestRandEnv", "No IOSIM_MEM_SIZE from env", "");

    fprintf(LogFp, "\n\tSiTestRandEnv:"
                   "\n\t\tseed argument %#x   IOSIM_SEED %s   seed used %#x"
                   "\n\t\tIOSIM_ADDR %s   IOSIM_MEM_SIZE %s\n"
                   , seed, iosim_seed, random_seed
                   , iosim_addr, (iosim_mem_size ? iosim_mem_size:"NULL"));

    if (si_ltd_mem_size <= 0)
        return SiLogResult(-1, "SiTestRandEnv", "Invalid IOSIM_MEM_SIZE from env", si_ltd_mem_size, 0,0,0);

    switch(testid) {
      case  0:  default:
        SiTestRandom(1, ForceFail_None, 0, 0);
        break;
      case  1:
        SiTestRandom(1, ForceFail_None, StartWithXs, 0);
        break;
      case  2:
        SiTestValidCtrlCmds(1, 0, 0, 0);
        break;
      case  3:
        SiTestInvalidCtrlrCmds(1, 0, 0, 0);
        break;
      case  4:
        SiTestCtrlrErrViaBD(1, CtrlQueryStatus, 0, 0);
        break;
      case  5:
        SiTestDmaBusyError(1, SI_DMA_WR_REG, PIF_RAM_START, 0);
        break;
      case  6:
        SiTestSingleCmdDetection(1, 1, 0, 0);
        break;
      case  7:
        SiTestJChannelReset(1, 0, 0, 0);
        break;
      case  8:
        SiTestDmaStress(arg1);
        break;
    }

    // errorTotal should be correct, but just to make sure
    // a fail wasn't logged without errorTotal being incremented
    if (!errorTotal && si_log_fail_count)
        errorTotal  = si_log_fail_count;

    return(errorTotal?-1:0);
}





// see comment in SiRunTests

#define  isSET(n) (n<32?(tests&(1<<n)):(tests2&(1<<(n-32))))

#define TEST(n,lvl,func_call)   RQSC(                            \
    {                                                            \
        int    ret;                                              \
        time_t st;                                               \
        time_t en;                                               \
        int run = isSET(n) && (!levels || lvl < levels);         \
        _TRACE(dsi,fprintf(DBGOUT,                               \
            "\n\t%s\n\t\ttests: %08x  tests2: %08x  levels: %d  "\
            "test_num: %d  test_lvl: %d  set: %s  run: %s",      \
            #func_call, tests, tests2, levels, n, lvl,           \
             (isSET(n) ? "yes":"no"), (run ? "yes" : "no") ));   \
        if(run) {                                                \
            st = time(NULL); ret = func_call; en  = time(NULL);  \
            fprintf(DBGOUT,"\n### %s  %s\t\t%s",                 \
                #func_call,ctime(&st),durstr(difftime(en,st)));  \
            if(ret && stop_tests_on_err) {                       \
                SiLogRes(ret, #func_call,"","");                 \
                goto end;                                        \
            }                                                    \
        }                                                        \
    }                                                            \
)




int
SiRunTests(int tests, int tests2, int levels, int seed)
{
    // Run a set of Si tests

    time_t start_time = time(NULL);
    time_t end_time;

    u32 mi_sec_mode = IO_READ(MI_SEC_MODE_REG);

    long Dflags_saved = Dflags; // DLE DEBUG
    Dflags = 0x8101;            // DLE DEBUG

    random_seed = seed ? seed : getpid();
    srandom(random_seed);

    fprintf(LogFp, "\n\tSiRunTests:   tests %08x   tests2 %08x   levels %d"
                   "\n\t\tseed argument %#x   seed used %#x   MI_SEC_MODE_REG %08lx   MI_CTRL_REG %08x\n"
                   , tests, tests2, levels, seed, random_seed, mi_sec_mode, IO_READ(MI_CTRL_REG));

    seed = 0; // normally don't want to reinit seed so can reproduce nightly

    fprintf(DBGOUT, "\n### SiRunTests:  start time:  %s", ctime(&start_time));

    // run test if tests==0 && tests2==0 or bit(test_num) is set in tests or tests2
    // and levels == 0 or test_lvl < levels. For example:
    //       levels == 0
    //           run lvl 0, 1, 2, 3, ...
    //       levels == 1
    //           run lvl 0
    //       levels == 2
    //           run lvl 0, 1
    //       levels == 3
    //           run lvl 0, 1, 2

    if (!tests && !tests2) {
        tests  = 0xFFFFFFFF;
        tests2 = 0xFFFFFFFF;
    }

    if(mi_sec_mode) {
        /* enter non-secure mode */
        u32 val = IO_READ(MI_SEC_MODE_REG);
        val = val & 0x42;
        IO_WRITE(MI_SEC_MODE_REG, val);
        fprintf(LogFp, "\n\tSiRunTests:  SI Tests entered in secure mode\n");
    }

#if RestrictDump
    verilog_dump(0);
#endif

    // test_num  test_lvl
    //     |   /
    TEST( 29, 0, SiTestRegisters          ( levels, 0,                0,                  seed) );
    TEST(  0, 0, SiTestValidCtrlCmds      ( levels, 0,                0,                  seed) );
    TEST(  1, 0, SiTestInvalidCtrlrCmds   ( levels, 0,                0,                  seed) );
    TEST(  2, 2, SiTestCtrlrErrViaBD      ( levels, CtrlQueryStatus,  0,                  seed) );
    TEST(  3, 1, SiTestCtrlrErrViaBD      ( levels, CtrlReset,        0,                  seed) );
    TEST( 32, 1, SiTestCtrlrErrViaBD      ( levels, CtrlRead,         0,                  seed) );
    TEST( 33, 1, SiTestCtrlrErrViaBD      ( levels, CtrlWrite,        0,                  seed) );
    TEST(  4, 0, SiTestCtrlrErrViaBD      ( levels, CtrlQueryButtons, 0,                  seed) );
    TEST(  5, 1, SiTestCtrlrErrViaBD      ( levels, CtrlJcUnsupCmd,   0,                  seed) );
    TEST(  6, 1, SiTestCtrlrErrViaBD      ( levels, CtrlNoXmitRand,   0,                  seed) );
    Dflags = Dflags_saved;      // DLE DEBUG
    TEST(  7, 2, SiTestDmaBusyError       ( levels, SI_DMA_WR_REG,    PIF_RAM_START,         0) );
    TEST(  8, 1, SiTestDmaBusyError       ( levels, SI_DMA_RD_REG,    PIF_RAM_START,         0) );
    TEST(  9, 0, SiTestDmaBusyError       ( levels, SI_DRAM_ADDR_REG, 0x40,                  0) );
    TEST( 10, 1, SiTestSingleCmdDetection ( levels, 0,                0,                  seed) );
    TEST( 11, 0, SiTestSingleCmdDetection ( levels, 1,                0,                  seed) );
    TEST( 12, 0, SiTestJChannelReset      ( levels, 0,                0,                  seed) );
    TEST( 13, 0, SiTestDmaSpecificAddrs   ( levels, 0,                0,                  seed) );
    TEST( 14, 0, SiTestDmaSpecificAddrs   ( levels, 1,                0,                  seed) );
    TEST( 15, 0, SiTestDmaWalkBits        ( levels, 0,                0,                  seed) );
    TEST( 16, 3, SiTestDmaWalkBits        ( levels, 1,                0,                  seed) );
    TEST( 17, 1, SiTestDmaWalkBits        ( levels, 0,                1,                  seed) );
    TEST( 18, 1, SiTestDmaWalkBits        ( levels, 1,                1,                  seed) );
    Dflags = 0x8101;            // DLE DEBUG
    TEST( 19, 1, SiTestRandom             (      5, ForceFail_None,   StartWithXs,        seed) );
    TEST( 20, 2, SiTestRandom             (     10, ForceFail_None,   0,                  seed) );
    TEST( 21, 3, SiTestRandom             (     10, ForceFail_Random, 0,                  seed) );
    TEST( 22, 2, SiTestRandom             (     10, ForceFail_None,   JChannel_Resp_Rand, seed) );
    Dflags = Dflags_saved;      // DLE DEBUG
    TEST( 23, 2, SiTestLCtrlJSRST         ( levels, 0,                0,                  seed) );
    TEST( 24, 1, SiTestLCtrlButRate       ( levels, 0,                0,                  seed) );
    TEST( 25, 1, SiTestLCtrlJsxy          ( levels, LCTRL_SOMEJITTER, 0,                  seed) );
    TEST( 26, 2, SiTestRandom             (      1, ForceFail_ClearSiIntMask, 0,          seed) );
    TEST( 27, 2, SiTestLCtrlButDeglitch   ( levels, 0,                0,                  seed) );
    TEST( 28, 2, SiTestLCtrlJsxyDeglitch  ( levels, 0,                0,                  seed) );
    TEST( 30, 2, SiTestBugFixes           ( levels, 0,                0,                  seed) );
    Dflags = 0x8101;            // DLE DEBUG
    TEST( 31, 0, SiTestSlave              ( levels, 0,                0,                  seed) );

 // TEST( 63, 0, SiTestForDebug           ( levels, 0,                0,                  seed) );

    // errorTotal should be correct, but just to make sure
    // a fail wasn't logged without errorTotal being incremented
    if (!errorTotal && si_log_fail_count)
        errorTotal  = si_log_fail_count;
end:
    end_time = time(NULL);
    fprintf(DBGOUT, "\n\n### SiRunTests:  end time:  %s\t\t%s"
                    , ctime(&end_time), durstr(difftime(end_time,start_time)));
    return(1);
}