simmagic.c 78.6 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
/*
 * Copyright (C) 1996-1998 by the Board of Trustees
 *    of Leland Stanford Junior University.
 * 
 * This file is part of the SimOS distribution. 
 * See LICENSE file for terms of the license. 
 *
 */

 /*****************************************************************
 * simmagic.c
 *
 * Interface between the OS view of the machine and the SimOS
 * device simulators.
 *
 * Created by: John Chapin, 05/95
 * Revision history:
 *   06/95  (Dan Teodosiu) added interrupt subsystem support.
 *   06/95  (John Chapin)  added register access, interrupt event codes
 *   06/95  (John Chapin)  moved flash defines out, added universal I/O ops
 *   11/95  (John Chapin)  added PPC version 2 support
 *   07/96  (Dan Teodosiu) complete OS/SimOS overhaul
 *   02/97  (Ben Werther)  generalized number of devices per machine
 *
 ****************************************************************/

#include "sim.h"

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

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

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

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

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

#include "machine_defs.h"
#ifdef SUPPORT_LINUX
#include "linux_init.h"
#endif

#ifdef TORNADO
#include "simgizmo.h"
#endif

/* Cache counting stuff. The routines are in numa.c */
#define IS_NUMA() (memsysVec.type == NUMA)
uint64 MigRepGetHotPage(int memnum);
uint64 MigRepGetInfo(unsigned long addr, int memnum, 
                                 unsigned long countType, unsigned long countAddr);
void MigRepSetInfo(unsigned long addr, int memnum, uint64 val,
                   unsigned long countType, unsigned long countAddr);

/* Control debugging info printout: 0=off, 1=on */
#define DEBUG_MAGIC 0

#define offsetof(t,m) ((int)&((t*)0)->m)

int FPromUseFL;

long initialBootTime; 

static CptCallback SimMagic_CheckpointCB;

typedef struct MagicStatus {

  MagicRegister iPendingReg;   /* 64b interrupt pending reg */
  MagicRegister iTransReg;     /* 64b int pending reg (transition-sensitive) */
  MagicRegister iEnableMask;   /* 64b interrupt enable mask */
  unsigned char iBitTable[64]; /* IEC -> CPU intrBits map
				* Note: read/written in 64-bit 
				* chunks so must be aligned
				*/
  MagicRegister IEChigh;       /* current interrupt level (board) */

  IEC           ioSlotMap[SIM_MAXSLOTS]; /* slot -> IEC map */
  IEC           ioSlots[SIM_MAXSLOTS];   /* pending count for each slot */
  
  int           timerInterval; /* 0 => no timer interrupt on this CPU
				* > 0 => interrupt with specified
				* periodicity [us].
				*/

  MagicRegister workerMask;    /* mask bits for cell boundary */
  MagicRegister workerMatch;   /* match bits for cell id */

} MagicStatus;

MagicStatus mm[SIM_MAXCPUS]; /* MAGIC status for all nodes */

DeviceToMachineStruct deviceToMachine; /* Device to machine mappings */

/*
 * Save someone a bunch of debugging time if they use some of SGI compilers
 * that doesn't sign-extend correctly when optimization is turned on.
 */
#define CHECK_FOR_COMPILER_BUG CheckForCompilerBug(0x80000000,(VA)0xffffffff80000000LL)
static void
CheckForCompilerBug(uint addr, VA val)
{
   VA   vAddr = (VA)(Reg32_s)addr; /* Sign extend if needed */
   if (vAddr != val) CPUError("Your compiler is broken\n");
}

#define CHECK_FOR_COMPILER_BUG2 \
  CheckForCompilerBug2(0x80000000,(Reg)0xffffffff80000000LL)

static void
CheckForCompilerBug2(Reg addr, Reg val)
{
   Reg new = (Reg)(Reg32_s)addr; /* Sign extend if needed */
   if (new != val) CPUWarning("CAREFUL: Your compiler is broken\n");
}

/****************************************************************************
 *
 * Interrupt subsystem
 *
 ****************************************************************************/

/* recompute intrBits for the specified CPU. */
void
recompute_intr_bits(register int cpu)
{
  MagicRegister pend;
  MagicRegister trans;
  int           iechigh;
  int i;
  MagicRegister mask;

  ASSERT(!USE_MAGIC());
  
  /* compute IEChigh = ffsb(pend) */
  pend = mm[cpu].iPendingReg & mm[cpu].iEnableMask;
  if (pend == 0) {
      iechigh = 0;
  } else {
    for (iechigh = -1; pend >= (1<<8); pend >>= 8) iechigh += 8;
    for ( ; pend != 0; pend >>= 1)                 iechigh++;
  }
  mm[cpu].IEChigh = iechigh;

  /* compute cause bits */
  trans = mm[cpu].iTransReg & mm[cpu].iEnableMask;
  CPUVec.intrBits[cpu] = 0;
  for(i=0, mask = 1; i < 64; i++, mask <<= 1) {
     if (trans & mask) CPUVec.intrBits[cpu] |= (mm[cpu].iBitTable[i]<<2);
  }

#ifdef TORNADO
  /* XXX this may be broken now -- check! */
  if ( mm[cpu].iPendingReg == 0x1 ) {
    CPUVec.intrBits[cpu] |= (CAUSE_IP4 >> CAUSE_IPSHIFT);
  } else if ( mm[cpu].iPendingReg ) {
    CPUVec.intrBits[cpu] |= (CAUSE_IP8 >> CAUSE_IPSHIFT);
  } else {
    CPUVec.intrBits[cpu] &= ~(CAUSE_IPMASK >> CAUSE_IPSHIFT);
  }
#endif

  CPUVec.IntrBitsChanged(cpu);
}

void
RaiseIBit(int cpu, IEC code)
{
  MagicRegister ibit = ((MagicRegister)1) << code;

  ASSERT(!USE_MAGIC());

  if (!(mm[cpu].iPendingReg & ibit)) {
    /* 0->1 transition */
#if (DEBUG_MAGIC == 1)
    LogEntry("RaiseIBit", cpu, "code=0x%x 0->1 transition\n", code);
#endif
    mm[cpu].iPendingReg |= ibit;
    mm[cpu].iTransReg   |= ibit;
    recompute_intr_bits(cpu);
  } else {
    /* no transition */
#if (DEBUG_MAGIC == 1)
    LogEntry("RaiseIBit", cpu, "code=0x%x no transition\n", code);
#endif
  }
}

void
ClearIBit(int cpu, IEC code)
{
  MagicRegister ibit = ((MagicRegister)1) << code;

  ASSERT(!USE_MAGIC());

  if ((mm[cpu].iPendingReg & ibit)) {
    /* 1->0 transition */
#if (DEBUG_MAGIC == 1)
    LogEntry("ClearIBit", cpu, "code=0x%x 1->0 transition\n", code);
#endif
    mm[cpu].iPendingReg &= ~ibit;
    mm[cpu].iTransReg   &= ~ibit;
    recompute_intr_bits(cpu);
  } else {
    /* no transition */
#if (DEBUG_MAGIC == 1)
    LogEntry("ClearIBit", cpu, "code=0x%x no transition\n", code);
#endif
  }
}

static void
RaiseSlot(int cpu, int slot)
{
  ASSERT(0 <= cpu && cpu < TOTAL_CPUS);
  ASSERT(0 <= slot && slot < SIM_MAXSLOTS);
#if (DEBUG_MAGIC == 1)
  LogEntry("RaiseSlot",cpu,"slot=%d  prevVal=0x%x\n",
	   slot, mm[cpu].ioSlots[slot]);
#endif
  if (mm[cpu].ioSlots[slot]++ == 0) {
    /* Slot transitions 0->1, must raise interrupt bit */
    if (USE_MAGIC()) {
      FlashliteRaiseSlot(cpu, slot);
    } else {
      RaiseIBit(cpu, mm[cpu].ioSlotMap[slot]);
    }
  }
}


void
ClearSlot(int cpu, int slot)
{
  register int slotval;
  
  ASSERT(0 <= cpu && cpu < TOTAL_CPUS);
  ASSERT(0 <= slot && slot < SIM_MAXSLOTS);
#if (DEBUG_MAGIC == 1)
  LogEntry("ClearSlot",cpu,"slot=%d  prevVal=0x%x\n",
	   slot, mm[cpu].ioSlots[slot]);
#endif
  slotval = --mm[cpu].ioSlots[slot];
  if (slotval < 0) {
     /* this can occur if: console TX_INTR is
      * pending when a cell is rebooted.  This gets cleared once
      * during cell initialization and again on the next GetIntrStatus
      * since flags in the simulated console device are still set.
      */
      Sim_Warning("ClearSlot(%d, %d): slot value dropped below 0\n", 
                  cpu, slot);
      mm[cpu].ioSlots[slot] = 0;
  } else if (slotval == 0) {
    /* Slot transitions 1->0, must clear interrupt bit. */
    if (USE_MAGIC()) {
      FlashliteClearSlot(cpu, slot);
    } else { 
      ClearIBit(cpu, mm[cpu].ioSlotMap[slot]);
    }
  }
}


/* NOTE: can ack only an internal interrupt cause */
int
AckInternalInt(int n, IEC iec)
{
  switch (iec) {
  case DEV_IEC_OSPC_LO:
  case DEV_IEC_OSPC_HI:
    /* ack SIPS (if any) */
    sim_sips_ack(n, (iec == DEV_IEC_OSPC_LO));
    return 0;
  case DEV_IEC_CLOCK:
  case DEV_IEC_IPI:
  case DEV_IEC_IPI1:
  case DEV_IEC_IPI2:
    /* just clear int */
    ClearIBit(n, iec);
    return 0;
  default: return -1;
  }
}

/*****************************************************************
 * Migration-Replication support
 *****************************************************************/
void 
MigRepStart(int cpu)
{
   RaiseIBit(cpu, DEV_IEC_MIG_REP);
}

void 
MigRepEnd(int cpu)
{
   ClearIBit(cpu, DEV_IEC_MIG_REP);
}

/****************************************************************************
 *
 * Clock interrupt support
 *
 ****************************************************************************/


/* eventcallback hdr for clock timer */
static EventCallbackHdr timerHdr[SIM_MAXCPUS];
/* clock interrupt counter for stats */
static uint             clockIntrs;
/* maintain last time timer was invoked so that
   we can checkpoint the correct timeleft. */
static SimTime          lastTimeout[SIM_MAXCPUS];


/* timer callback: raise interrupt and enqueue yourself for next tick */
static void
TimerCallback(int cpuNum, EventCallbackHdr *hdr, void *arg)
{
  ASSERT(!USE_MAGIC());
  /* if (CPUVec.drainEvents) { */
  if (0) { 
     /* eventqueue is being cleared, so figure out the timeleft so
      * next CPU model can restart the clock correctly */
     CPUVec.clockStarted[cpuNum] = 0;
     
     SBase[cpuNum].clockTimeLeft = SBase[cpuNum].clockInterval - 
        (CPUVec.CycleCount(cpuNum) - lastTimeout[cpuNum])/CPU_CLOCK;
     if (SBase[cpuNum].clockTimeLeft > SBase[cpuNum].clockInterval)
        SBase[cpuNum].clockTimeLeft = SBase[cpuNum].clockInterval;
     return;
  }
  
  lastTimeout[cpuNum] = CPUVec.CycleCount(cpuNum);
  clockIntrs++;

  RaiseIBit(cpuNum, DEV_IEC_CLOCK);
  CPUVec.IntrBitsChanged(cpuNum);
    
  EventDoCallback(cpuNum, TimerCallback, hdr, NULL,
		  CPUVec.clockInterval[cpuNum] * CPU_CLOCK);
}

/* sets up the callback data and the first callback */
void
InstallTimer(int cpuNum, unsigned int interval, unsigned int timeLeft)
{
  ASSERT(!USE_MAGIC());

  CPUVec.clockInterval[cpuNum] = interval;
  
  if (CPUVec.clockStarted[cpuNum]) EventCallbackRemove(&timerHdr[cpuNum]);
  CPUVec.clockStarted[cpuNum] = 1;

  EventDoCallback(cpuNum, TimerCallback, &timerHdr[cpuNum], NULL, 
		  timeLeft * CPU_CLOCK);

  SBase[cpuNum].clockInterval = CPUVec.clockInterval[cpuNum];
  SBase[cpuNum].clockStarted = CPUVec.clockStarted[cpuNum];
}

/* called when restoring from a checkpoint */
void
InstallTimers(void)
{
  int i;

  for(i = 0; i < TOTAL_CPUS; i++) {
     if (SBase[i].clockStarted) {
        if (USE_MAGIC()) {
           FlashliteInstallTimer(i, SBase[i].clockInterval, SBase[i].clockTimeLeft);
        } else {
           InstallTimer(i, SBase[i].clockInterval, SBase[i].clockTimeLeft);
        }
     }
  }
}

/* called when checkpointing, so that timeLeft field can be updated. */
void
TimerUpdateTimeLeft(void)
{
  int cpuNum;
  for(cpuNum = 0; cpuNum < TOTAL_CPUS; cpuNum++)
    if (SBase[cpuNum].clockStarted) {
      SBase[cpuNum].clockTimeLeft = SBase[cpuNum].clockInterval - 
	     (CPUVec.CycleCount(cpuNum) - lastTimeout[cpuNum])/CPU_CLOCK;
      if (SBase[cpuNum].clockTimeLeft > SBase[cpuNum].clockInterval)
	SBase[cpuNum].clockTimeLeft = SBase[cpuNum].clockInterval;
    }
}

/****************************************************************************
 *
 * SIPS support
 *
 ****************************************************************************/

struct { /* SIPS state for each MAGIC */

  MagicRegister stall;   /* shadow of STALLOSPC PPR */

  int           stalled; /* did an access stall on this OSPC? */
  int           st_lo;   /* stalled on OSPC_LO? */
  VA            st_va;   /* stalled VA (could actually be computed) */

} sst[SIM_MAXCPUS];


static void
sips_interrupt(int n, int lo, int on)
{
  /* suppress the interrupt if a cache miss is already stalled
   * on this OSPC.
   */
  if (on && sst[n].stalled && sst[n].st_lo == lo) {
    /* unstall access that stalled on this OSPC */
    CacheCmdUnstall(n, sst[n].st_va);
#if (DEBUG_MAGIC == 1)
    LogEntry("sips_interrupt", n, "lo=%d on=%d SUPPRESSED\n", lo, on);
#endif
    return;
  }

  /* XXX DT not true in general!
     ASSERT(!sst[n].stalled);
     */

#if (DEBUG_MAGIC == 1)
  LogEntry("sips_interrupt", n, "lo=%d on=%d\n", lo, on);
#endif

  if (on) RaiseIBit(n, lo ? DEV_IEC_OSPC_LO : DEV_IEC_OSPC_HI);
  else    ClearIBit(n, lo ? DEV_IEC_OSPC_LO : DEV_IEC_OSPC_HI);
}


/* NOTE ON OSPC ACCESSES:
 *
 * In the real machine, OSPC accesses are done through a distinct
 * (cacheable noncoherent) address space. Lacking enough address bits in
 * the 32bit SimOS version, we have squeezed in the OSPC area in the
 * second page of KSEG0. The various simulators use different mechanisms for
 * accessing this area:
 *
 *  - MIPSY contains a hack in CacheCmdDone. This routine is called
 *    by the memory system when an access completes; in turn, it calls
 *    into sima_magic_OSPC_access below, which may either complete
 *    the access right away (if the data is available), or delay the
 *    access (and call the given continuation later) if we stall on
 *    this OSPC read.
 *
 *  - EMBRA cannot go through the same mechanism, since having all
 *    Embra memory accesses go through a function would defeat the
 *    efficiency goals of Embra. Hence, Embra special-cases the page
 *    in KSEG0 that maps to OSPC's and treats access to this page like
 *    backdoor accesses, which will go through OSPC_access (registered
 *    in the backdoor).
 */

int
sim_magic_OSPC_access(int cpuNum, uint VA, byte *data)
{
  int            err;
  int            stall = 0;
  MagicRegister  errval, okval;
  MagicRegister* dr = (MagicRegister*)data;

  if (USE_MAGIC()) return 0; /* Flashlite */

  /* read the data -- for now, this is only SIPS data */
  if (VA >= (__MAGIC_OSPC_BASE + MAGIC_OSPC_LO_OFFS) &&
      VA <  (__MAGIC_OSPC_BASE + MAGIC_OSPC_LO_OFFS + MAGIC_OSPC_SIZE)) {

    errval = MAGIC_OSPC_LO_NONE;
    okval  = MAGIC_OSPC_LO_SIPSREQ;
    err = sim_sips_get(cpuNum, 1, data);
    if (sst[cpuNum].stall == (MagicRegister)DEV_IEC_OSPC_LO && err != 0) {
      stall = 1;
    }
  } else
    if (VA >= (__MAGIC_OSPC_BASE + MAGIC_OSPC_HI_OFFS) &&
	VA <  (__MAGIC_OSPC_BASE + MAGIC_OSPC_HI_OFFS + MAGIC_OSPC_SIZE)) {

      okval  = MAGIC_OSPC_HI_SIPSREPLY;
      errval = MAGIC_OSPC_HI_NONE;
      err = sim_sips_get(cpuNum, 0, data);
      if (sst[cpuNum].stall == (MagicRegister)DEV_IEC_OSPC_HI && err != 0) {
	stall = 1;
      }
  } else {
    /* access to some other location -- ignore */
    return 0;
  }

  /* SIPS status */
  *dr = ( ((*dr) & ~MAGIC_OSPC_OPCODE_MASK) |
	  (((MagicRegister)(err ? errval : okval)) << MAGIC_OSPC_OPCODE_OFFS) );

#if (DEBUG_MAGIC == 1)
  LogEntry("OSPC_access", cpuNum, "delay=%d\n",
	   stall ? (CPU_CLOCK * MAGIC_OSPC_TIMEOUT_US) : 0);
#endif

  return stall ? (CPU_CLOCK * MAGIC_OSPC_TIMEOUT_US) : 0;
}


void
sim_magic_OSPC_stalled(int cpuNum, VA va, int stalled)
{
#if (DEBUG_MAGIC == 1)
  LogEntry("sim_magic_OSPC_stalled", cpuNum, "va=0x%llx st=%d\n",
	   (uint64)va, stalled);
#endif

  if (stalled) {
    /* access has stalled */
    ASSERT(!sst[cpuNum].stalled);
    sst[cpuNum].stalled = 1;
    sst[cpuNum].st_va   = va;
    sst[cpuNum].st_lo   = (va >= (__MAGIC_OSPC_BASE + MAGIC_OSPC_LO_OFFS)    &&
			   va <  (__MAGIC_OSPC_BASE + MAGIC_OSPC_LO_OFFS + 
				  MAGIC_OSPC_SIZE));
  } else {
    /* stalled access has timed out. Unstall */
    ASSERT(sst[cpuNum].stalled);
    ASSERT(sst[cpuNum].st_va == va);
    ASSERT(sst[cpuNum].st_lo == (va >= (__MAGIC_OSPC_BASE+MAGIC_OSPC_LO_OFFS)&&
				 va <  (__MAGIC_OSPC_BASE+MAGIC_OSPC_LO_OFFS+ 
					MAGIC_OSPC_SIZE)));
    sst[cpuNum].stalled = 0;
    sst[cpuNum].stall   = (MagicRegister)0;
  }
}


/****************************************************************************
 *
 * PPR emulation
 *
 ****************************************************************************/

#define MAX_PPR    0x40     /* max. number of PPR's */

#define PPR_NODE(va) (((va)>>__MAGIC_NODE_OFFS) & \
		      ((1 << __MAGIC_NODE_BITS) - 1))
#define PPR_REG(va)  (((va)>>__MAGIC_REG_OFFS) & \
		      ((1 << __MAGIC_REG_BITS) - 1))

static MagicRegister
node_config(int cell, int realCPU)
{
  unsigned int npc, first, cpu;

  if (inCellMode) {

     ASSERT((NUM_CPUS(0)/NUM_CELLS(0))*NUM_CELLS(0) == NUM_CPUS(0));

     cpu = realCPU;
     npc = NUM_CPUS(0)/NUM_CELLS(0);
     first = cell * npc;

  } else {

     ASSERT((cell == 0) && (NUM_CELLS(0) == 1));

     cpu = MCPU_FROM_CPU(realCPU);
     npc = NUM_CPUS(M_FROM_CPU(realCPU));
     first = 0;

  }

  ASSERT(((((MagicRegister)cpu) << MAGIC_NODECONFIG_THISNODE_OFFS)
	 & ~MAGIC_NODECONFIG_THISNODE_MASK) == 0LL);
  ASSERT(((((MagicRegister)first) << MAGIC_NODECONFIG_FIRSTNODE_OFFS)
	 & ~MAGIC_NODECONFIG_FIRSTNODE_MASK) == 0LL);
  ASSERT(((((MagicRegister)npc) << MAGIC_NODECONFIG_NODESINCELL_OFFS)
	 & ~MAGIC_NODECONFIG_NODESINCELL_MASK) == 0LL);
  ASSERT(((((MagicRegister)cell) << MAGIC_NODECONFIG_THISCELL_OFFS)
	 & ~MAGIC_NODECONFIG_THISCELL_MASK) == 0LL);
  ASSERT(((((MagicRegister)NUM_CELLS(0)) << MAGIC_NODECONFIG_NCELLS_OFFS)
	 & ~MAGIC_NODECONFIG_NCELLS_MASK) == 0LL);

  return (((MagicRegister)cpu) << MAGIC_NODECONFIG_THISNODE_OFFS)      |
         (((MagicRegister)first) << MAGIC_NODECONFIG_FIRSTNODE_OFFS)   |
         (((MagicRegister)npc) << MAGIC_NODECONFIG_NODESINCELL_OFFS)   |
         (((MagicRegister)cell) << MAGIC_NODECONFIG_THISCELL_OFFS)     |
         (((MagicRegister)NUM_CELLS(0)) << MAGIC_NODECONFIG_NCELLS_OFFS);
}

static MagicRegister
addr_config(int n)
{
  unsigned int machNo = M_FROM_CPU(n);
  unsigned int pages = MEM_SIZE(machNo) / SIM_PAGE_SIZE / NUM_CPUS(machNo);
  unsigned int nnb   = __MAGIC_NODE_BITS; /* node_number_bits */
  unsigned int masb  = 0; /* MAGIC address space bits */

  ASSERT((MEM_SIZE(machNo)/NUM_CPUS(machNo))*NUM_CPUS(machNo)
         == MEM_SIZE(machNo));

  ASSERT(((((MagicRegister)pages) << MAGIC_ADDRCONFIG_PAGES_OFFS)
	 & ~MAGIC_ADDRCONFIG_PAGES_MASK) == 0LL);
  ASSERT(((((MagicRegister)nnb) << MAGIC_ADDRCONFIG_NNBITS_OFFS)
	 & ~MAGIC_ADDRCONFIG_NNBITS_MASK) == 0LL);
  ASSERT(((((MagicRegister)masb) << MAGIC_ADDRCONFIG_MASBITS_OFFS)
	 & ~MAGIC_ADDRCONFIG_MASBITS_MASK) == 0LL);

  return (((MagicRegister)pages) << MAGIC_ADDRCONFIG_PAGES_OFFS)      |
         (((MagicRegister)nnb) << MAGIC_ADDRCONFIG_NNBITS_OFFS)       |
         (((MagicRegister)masb) << MAGIC_ADDRCONFIG_MASBITS_OFFS);
}



/* PPR access handler -- handles all accesses to PPR's.
 * Returns:
 *  - 0: ok access
 *  - 1: this type of access not supported (only dword implemented
 *       for now)
 *  - -1: bus-error this access.
 */
static int
PPR_handler(int   cpu,   /* CPU doing the access */
	    int   n,     /* destination node */
	    int   r,     /* register number */
	    int   type,  /* access type */
	    void *buff)  /* data buffer */
{

#define RDONLY if (type == BDOOR_STORE_DOUBLE) return -1
#define WRONLY if (type == BDOOR_LOAD_DOUBLE) return -1
#define RDWR

  MagicRegister* datap = (MagicRegister*) buff;
  int            isrd  = (type == BDOOR_LOAD_DOUBLE);

  ASSERT(0 <= cpu && cpu < TOTAL_CPUS);
  ASSERT(0 <= n && n < TOTAL_CPUS);
  /* Note: we should never get here if we use Flite! */
  ASSERT(!USE_MAGIC());

#if (DEBUG_MAGIC == 1)
  LogEntry("PPR_handler", cpu, "n=%d r=0x%x t=%d\n", n, r, type);
#endif

  /* we only handle dword accesses and buserror all others */
  if (type != BDOOR_LOAD_DOUBLE && type != BDOOR_STORE_DOUBLE) return 1;

  switch (r) {
    
  case MAGIC_PPR_IECHIGH:                                            RDONLY;
    *datap = mm[n].IEChigh;
    break;

  case MAGIC_PPR_ACKINTERNAL:                                        WRONLY;
    return AckInternalInt(n, (IEC)*datap);

  case MAGIC_PPR_IECPENDING:                                         RDWR;
    if (isrd) {
      *datap = mm[n].iPendingReg;
    } else {
      /* clear selected interrupt bits */
      mm[n].iTransReg &= ~(*datap);
      recompute_intr_bits(n);
    }
    break;

  case MAGIC_PPR_SIPSLOACK:                                          RDONLY;
    return AckInternalInt(n, (IEC)DEV_IEC_OSPC_LO);

  case MAGIC_PPR_SIPSHIACK:                                          RDONLY;
    return AckInternalInt(n, (IEC)DEV_IEC_OSPC_HI);

  case MAGIC_PPR_IECENABLE:                                          RDWR;
    if (isrd) {
      *datap = mm[n].iEnableMask;
    } else {
      mm[n].iEnableMask = *datap;
      recompute_intr_bits(n);
    }
    break;

  case MAGIC_PPR_SENDIPI:                                            WRONLY;
  {
     int iec;
     switch (*datap) {
     case 0:	iec = DEV_IEC_IPI;	break;
     case 1:	iec = DEV_IEC_IPI1;	break;
     case 2:	iec = DEV_IEC_IPI2;	break;
     default:	CPUError("only ipi 0, 1, and 2 supported\n");
     }
     CPUVec.Send_Interrupt(n, iec, IPI_LATENCY);
  }
  break;

  case MAGIC_PPR_OPSPACE:                                            RDWR;
    ASSERT(0); /* not yet implemented */
    break;

  case MAGIC_PPR_ASID:                                               RDWR;
    ASSERT(0); /* not yet implemented */
    break;

  case MAGIC_PPR_TLBINVAL:                                           WRONLY;
    ASSERT(0); /* not yet implemented */
    break;

  case MAGIC_PPR_TLBINUSE:                                           RDONLY;
    ASSERT(0); /* not yet implemented */
    break;

  case MAGIC_PPR_MSGTAG:                                             RDWR;
    ASSERT(0); /* not yet implemented */
    break;

  case MAGIC_PPR_STALLOSPC:                                          RDWR;
    if (isrd) *datap = sst[n].stall;
    else      sst[n].stall = *datap;
    break;

  case MAGIC_PPR_CYCLECOUNT:                                         RDONLY;
    /* XXX is this correct? */
    *datap = (MagicRegister) CPUVec.CycleCount(n);
    break;
    
  case MAGIC_PPR_PROTVERSION:                                        RDONLY;
    /* This always returns 2 for now */
    *datap = (MagicRegister)2;
    break;

  case MAGIC_PPR_HWVERSION:                                          RDONLY;
    ASSERT(0); /* not yet implemented */
    break;

  case MAGIC_PPR_REMAPMASK:                                          RDWR;
    ASSERT( !isrd ); /* w not yet implemented */
    memsysVec.MemsysSetRemap(n, (PA)*datap);
    memsysVec.MemsysControlRemap(n, 1); /* remapenable */
    break;

  case MAGIC_PPR_PROTCONTROL:                                        RDWR;
    ASSERT(0); /* not yet implemented */
    break;

  case MAGIC_PPR_RTC:                                                RDONLY;
     {
        SimTime currentCycle = CPUVec.CycleCount(n) + startingCycle[n];
        *datap = (MagicRegister) CyclesToNanoSecs(currentCycle)/1000;
        break;
     }

  case MAGIC_PPR_INTERVAL:                                           RDWR;
    if (isrd)
      *datap = mm[n].timerInterval;
    else {
      mm[n].timerInterval = *datap;
      /* XXX fix this */
      InstallTimer(n, *datap, *datap);
    }
    break;

  case MAGIC_PPR_SLOTMAP:                                            RDWR;
    if (isrd)
      *datap =
	( (MagicRegister)mm[n].ioSlotMap[0] << MAGIC_SLOTMAP_SLOT0_OFFS ) |
	( (MagicRegister)mm[n].ioSlotMap[1] << MAGIC_SLOTMAP_SLOT1_OFFS ) |
	( (MagicRegister)mm[n].ioSlotMap[2] << MAGIC_SLOTMAP_SLOT2_OFFS ) |
	( (MagicRegister)mm[n].ioSlotMap[3] << MAGIC_SLOTMAP_SLOT3_OFFS );
    else {
      int slot;
      for (slot=0; slot<4; slot++) 
         while (mm[n].ioSlots[slot] > 0) ClearSlot(n, slot);
      mm[n].ioSlotMap[0] = (*datap & MAGIC_SLOTMAP_SLOT0_MASK) >>
	                                           MAGIC_SLOTMAP_SLOT0_OFFS;
      mm[n].ioSlotMap[1] = (*datap & MAGIC_SLOTMAP_SLOT1_MASK) >>
	                                           MAGIC_SLOTMAP_SLOT1_OFFS;
      mm[n].ioSlotMap[2] = (*datap & MAGIC_SLOTMAP_SLOT2_MASK) >>
	                                           MAGIC_SLOTMAP_SLOT2_OFFS;
      mm[n].ioSlotMap[3] = (*datap & MAGIC_SLOTMAP_SLOT3_MASK) >>
	                                           MAGIC_SLOTMAP_SLOT3_OFFS;
    }
    break;

  case MAGIC_PPR_FWSHIFT:                                            RDWR;
    /* obsolete, should be removed */
    ASSERT(0);
    break;

  case MAGIC_PPR_RECOVERYSYNC:                                       RDONLY;
    ASSERT(0); /* not yet implemented */
    break;

  case MAGIC_PPR_REPORT_DIAG_RESULT:                                 RDONLY;
    ASSERT(0); /* not yet implemented */
    break;

  case MAGIC_PPR_NODECONFIG:                                         RDONLY;
    {
      int cell;
      if (inCellMode)
          cell = cpu / CPUS_PER_CELL(0); /* this is my node number */
      else
          cell = 0;
      *datap = node_config(cell, cpu);
    }
    break;

  case MAGIC_PPR_ADDRCONFIG:                                         RDONLY;
    *datap = addr_config(cpu);
    break;

  case MAGIC_PPR_MIG_REP:
     RDONLY;
     if (IS_NUMA() ) {
        /* 
         * Gets any pending pages whose cache-miss counters
         * crossed the threshold set. This is in response to
         * the hotpage interrupt. Returns the local page number
         * or zero when there are no more. The latter also resets
         * the interrupt.
         */
        *datap = (MagicRegister) MigRepGetHotPage(cpu);
     } else {
        /* Currently we just return 0 */
        *datap = (MagicRegister) 0;
     }
    break;
    
  default:

    /* Slow case: uncached access to OSPC mirror area? */
    switch (r & ~(MAGIC_OSPC_SIZE-1)) {
    case (MAGIC_PPR_OSPC + (MAGIC_OSPC_LO_OFFS >> __MAGIC_REG_OFFS)):
    case (MAGIC_PPR_OSPC + (MAGIC_OSPC_HI_OFFS >> __MAGIC_REG_OFFS)):
      {
	int  offs = r & ((MAGIC_OSPC_SIZE-1) >> __MAGIC_REG_OFFS);
	byte ospc_buff[MAGIC_OSPC_SIZE];
	int  result;

	result =
	  sim_magic_OSPC_access(cpu, 
				__MAGIC_OSPC_BASE +
			          ((r - MAGIC_PPR_OSPC) << __MAGIC_REG_OFFS),
				ospc_buff);
	ASSERT(result == 0);
	*datap = ((uint64*)ospc_buff)[offs];
      }
      break;
    case (MAGIC_PPR_OSPC + (MAGIC_OSPC_VEC_REQ_OFFS >> __MAGIC_REG_OFFS)):
    case (MAGIC_PPR_OSPC + (MAGIC_OSPC_VEC_REP_OFFS >> __MAGIC_REG_OFFS)):
      /* not emulated by simmagic */
      ASSERT(0);
      break;
    default:
      /* Illegal PPR access */
      ASSERT(0); /* should actually buserror. Do later */
      break;
    }

  }
#if (DEBUG_MAGIC == 1)
  LogEntry("PPR_handler", cpu, "data 0x%llx\n", (uint64)*datap);
#endif
  return 0;

#undef RDONLY
#undef WRONLY
#undef RDWR
}


/****************************************************************************
 *
 * PPC emulation
 *
 ****************************************************************************/

#define PPC_GROUPS          2       /* only kernel and msg so far */
#define PPC_MAX             0x10    /* max. PPC's per group */
#define PPC_SIZE            16      /* 16 dwords */

typedef struct PPCStat {
  MagicRegister  data[PPC_SIZE]; /* PPC data */
  unsigned int   inited;         /* which words have been inited? */
} PPCStat;

#define PPC_IS_INITED(bf, n) ((bf & (1 << n)) != 0)
#define PPC_WORD_INITED(bf, n) bf |= (1 << n)
#define PPC_ALL_INITED(bf, n) (((bf) & ((1 << n) - 1)) == ((1 << n) - 1))
#define PPC_CLEAR_INITED(bf) bf = 0

static PPCStat ppcs[SIM_MAXCPUS][PPC_GROUPS][PPC_MAX];

/* PPC access handler.
 * Returns:
 *  - 0: access handled successfully
 *  - 1: cannot handle, bus-error access
 */
static int
PPC_handler(int   cpu,   /* CPU doing the access */
	    int   n,     /* destination node */
	    int   g,     /* PPC group */
	    int   p,     /* PPC number */
	    int   offs,  /* byte offset */
	    int   type,  /* access type */
	    void *buff)  /* data buffer */
{
#define ARGS(n)       if (!PPC_ALL_INITED(ps->inited, n)) goto retry
#define BAD_PPC(_why) (MAGIC_PPC_NOT_SUCCESSFUL_BIT | (_why))
  MagicRegister* datap = (MagicRegister*)buff;
  PPCStat*       ps    = &ppcs[n][g][p];

  ASSERT(0 <= cpu && cpu < TOTAL_CPUS);
  ASSERT(0 <= n && n < TOTAL_CPUS);
  /* Note: we should never get here if we use Flite! */
  /* except for the few PPCs that are not yet implemented in flite */
  if (USE_MAGIC()) {
     ASSERT((p == MAGIC_PPC_OP_CELLNODECONFIG) ||
            (p == MAGIC_PPC_OP_NODEADDRCONFIG) ||
            (p == MAGIC_PPC_OP_STARTSLAVENODE));
  }

#if (DEBUG_MAGIC == 1)
  LogEntry("PPC_handler", cpu, "n=%d g=%d p=0x%x offs=0x%x t=%d\n",
	   n, g, p, offs, type);
#endif

  /* we only handle dword accesses and buserror all others */
  if (type != BDOOR_LOAD_DOUBLE && type != BDOOR_STORE_DOUBLE) return 1;

  /* henceforth, we only deal with word offsets */
  offs = offs / sizeof(MagicRegister);

  if (type == BDOOR_STORE_DOUBLE) {
#if (DEBUG_MAGIC == 1)
    LogEntry("PPC_handler", cpu, "data = 0x%llx\n", (uint64)*datap);
#endif
    /* Store PPC argument */
    ps->data[offs] = *datap;
    PPC_WORD_INITED(ps->inited, offs);
    return 0;
  }

  /* we can only handle reads to the first dword of a PPC. We buserr
   * all other reads.
   */
  if (offs != 0) return 1;

  switch (g) {

  case MAGIC_PPC_GROUP_KERNEL: /* KERNEL group */

    switch (p) {
    case MAGIC_PPC_OP_SIPSLO:
    case MAGIC_PPC_OP_SIPSHI:                                   ARGS(PPC_SIZE);
      switch (sim_sips_send(cpu,
			    (p == MAGIC_PPC_OP_SIPSLO),
			    (void*)ps->data, 0)) {
      case SIPS_OK:         *datap = (MagicRegister)0;                 break;
      case SIPS_RETRYLOCAL: *datap = BAD_PPC(MAGIC_PPC_BUSY);          break;
      case SIPS_RETRYREMOTE:*datap = BAD_PPC(MAGIC_PPC_REMOTEBUSY);    break;
      case SIPS_BADDEST:    *datap = BAD_PPC(MAGIC_PPC_ARGOUTOFRANGE); break;
      case SIPS_REMOTEDEAD: *datap = BAD_PPC(MAGIC_PPC_REMOTEDEAD);    break;
      default:              ASSERT(0); break;
      }
      break;
    case MAGIC_PPC_OP_MEMCPY:                                   ARGS(4);
      ASSERT(0); /* not yet implemented */
      break;
    case MAGIC_PPC_OP_IBITWRITE:                                ARGS(2);
      {
	if ((int)ps->data[0] > DEV_IEC_MAX) {
	  CPUWarning("sws_ppc_op_ibitwrite: iec out of range\n");
	  goto out_of_range;
	}
	if ((int)ps->data[1] != 0x00 &&
	    (int)ps->data[1] != 0x01 &&
	    (int)ps->data[1] != 0x02 &&
	    (int)ps->data[1] != 0x04 &&
	    (int)ps->data[1] != 0x08 &&
	    (int)ps->data[1] != 0x10) {
	  CPUWarning("sws_ppc_op_ibitwrite: bad ibit\n");
#ifdef IRIX6_4
          /* Temp patch to keep the current 6.4 kernel working. */
          *datap = (MagicRegister)0; /* success */
          break;
#else
 	  goto out_of_range;
#endif
	}
	mm[n].iBitTable[(int)ps->data[0]] = (int) ps->data[1];
	recompute_intr_bits(n);
      }
      *datap = (MagicRegister)0; /* success */
      break;
    case MAGIC_PPC_OP_IBITREAD:                                 ARGS(1);
      {
	if ((int)ps->data[0] > DEV_IEC_MAX) {
	  CPUWarning("sws_ppc_op_ibitread: iec out of range\n");
	  goto out_of_range;
	}
	*datap = mm[n].iBitTable[(int)ps->data[0]];
      }
      break;
    case MAGIC_PPC_OP_DONATE:                                   ARGS(3);
      ASSERT(0); /* not yet implemented */
      break;
    case MAGIC_PPC_OP_RESETPOOL:                                ARGS(1);
      ASSERT(0); /* not yet implemented */
      break;
    case MAGIC_PPC_OP_LOADSTATE:                                ARGS(1);
      CPUPrint("LOADSTATE not implemented\n");
      *datap = 0;
      break;
    case MAGIC_PPC_OP_STORESTATE:                               ARGS(2);
      ASSERT(0); /* not yet implemented */
      break;
    case MAGIC_PPC_OP_MEMRESET:                                 ARGS(2);
      ASSERT(0); /* not yet implemented */
      break;
    case MAGIC_PPC_OP_VECTORPKT:                                ARGS(7);
      ASSERT(0); /* not yet implemented */
      break;
    case MAGIC_PPC_OP_BZERO:                                    ARGS(3);
      ASSERT(0); /* not yet implemented */
      break;
    case MAGIC_PPC_OP_CELLNODECONFIG:                           ARGS(1);
      {
	MagicRegister cell = ps->data[0];
	if (cell >= NUM_CELLS(0)) goto out_of_range;
	*datap = node_config((int)cell, cpu);
      }
      break;
    case MAGIC_PPC_OP_NODEADDRCONFIG:                           ARGS(1);
      {
	MagicRegister node = FIRST_CPU(M_FROM_CPU(cpu))+ps->data[0]; 
	if (node >= TOTAL_CPUS) goto out_of_range;
	*datap = addr_config((int)node);
      }
      break;
#if !defined(IRIX6_4)
    case MAGIC_PPC_OP_STARTSLAVENODE:                           ARGS(3);
      {
	int slave = FIRST_CPU(M_FROM_CPU(cpu))+ps->data[0];
	if (slave >= TOTAL_CPUS) goto out_of_range;
        if (inCellMode) {
            if (((cpu / CPUS_PER_CELL(0))*CPUS_PER_CELL(0)) != cpu ||
                slave < cpu ||
                slave >= cpu+CPUS_PER_CELL(0)) goto out_of_range;
        }
	if (LaunchSlave(slave, (VA)(ps->data[1]), (Reg)(ps->data[2]), 
                        0, 0, 0))
	  goto out_of_range;
      }
      *datap = 0;
      break;
#else
    case MAGIC_PPC_OP_STARTSLAVENODE:                           ARGS(4);
      {
	int slave = FIRST_CPU(M_FROM_CPU(cpu))+ps->data[0];
	if (slave >= TOTAL_CPUS) goto out_of_range;
        if (inCellMode) {
            if (((cpu / CPUS_PER_CELL(0))*CPUS_PER_CELL(0)) != cpu ||
                slave < cpu ||
                slave >= cpu+CPUS_PER_CELL(0)) goto out_of_range;
        }
	if (LaunchSlave(slave, (VA)(ps->data[1]), (Reg)(ps->data[2]), 
                        (Reg)(ps->data[3]), 0, 0))
	  goto out_of_range;
      }
      *datap = 0;
      break;

#endif
    default: goto bad_opc;
    }
    break;
    
  case MAGIC_PPC_GROUP_MSG: /* MSG group */

    switch (p) {
    case MAGIC_PPC_OP_MEMCPY_V:                                 ARGS(4);
      ASSERT(0); /* not yet implemented */
      break;
    case MAGIC_PPC_OP_SIPS_V:                                   ARGS(16);
      ASSERT(0); /* not yet implemented */
      break;
    case MAGIC_PPC_OP_BZERO_V:                                  ARGS(3);
      ASSERT(0); /* not yet implemented */
      break;
    default: goto bad_opc;
    }
    break;
    
  default: goto bad_grp;
  }
    
  PPC_CLEAR_INITED(ps->inited);
#if (DEBUG_MAGIC == 1)
  LogEntry("PPC_handler", cpu, "result=0x%016llx\n", (uint64)*datap);
#endif
  return 0;
    
  /* Error returns: */
out_of_range:
  CPUWarning("MAGIC value out of range\n");
  *datap = MAGIC_PPC_NOT_SUCCESSFUL_BIT|MAGIC_PPC_ARGOUTOFRANGE;
  return 0;
retry:
  *datap = MAGIC_PPC_NOT_SUCCESSFUL_BIT|MAGIC_PPC_RETRY_CODE; return 0;
bad_opc:
  *datap = MAGIC_PPC_NOT_SUCCESSFUL_BIT|MAGIC_PPC_BADOPCODE; return 0;
bad_grp:
  *datap = MAGIC_PPC_NOT_SUCCESSFUL_BIT|MAGIC_PPC_BADGROUP; return 0;

#undef ARGS
#undef BAD_PPC
}


/****************************************************************************
 *
 * Device registers and interrupt emulation
 *
 ****************************************************************************/

/*
 * DISK device.
 * The shadow array is indexed by:
 *   - absolute node number (i.e. NOT machine-relative one)
 *   - controller number
 *   - disk unit number
 */
static DevDiskRegisters**** disk_shadow;
#define DISK_SHADOW(_NODE,_CTRL,_UNIT) (*disk_shadow[_NODE][_CTRL][_UNIT])

static void
disk_initialize(void)
{
  disk_shadow = (DevDiskRegisters****)
    ZMALLOC(DISK_NODES*sizeof(DevDiskRegisters***), "disk_shadow");
}

static void
disk_touch(int node, int ctrl, int unit)
{
  char name[32];
  int  nc = NUM_DISK_CONTROLLERS(M_FROM_CPU(node), MCPU_FROM_CPU(node));
  int  uc = DEV_DISK_MAX_UNIT / nc;

  ASSERT(0 <= node && node < DISK_NODES &&
	 0 <= ctrl && ctrl < nc         &&
	 0 <= unit && unit < uc);

  if (!disk_shadow[node]) {
    sprintf(name, "disk_shadow[%d]", node);
    disk_shadow[node] = (DevDiskRegisters***)
      ZMALLOC(nc*sizeof(DevDiskRegisters**), name);
  }
  if (!disk_shadow[node][ctrl]) {
    sprintf(name, "disk_shadow[%d][%d]", node, ctrl);
    disk_shadow[node][ctrl] = (DevDiskRegisters**)
      ZMALLOC(uc*sizeof(DevDiskRegisters*), name);
  }
  if (!disk_shadow[node][ctrl][unit]) {
    sprintf(name, "disk_shadow[%d][%d][%d]", node, ctrl, unit);
    disk_shadow[node][ctrl][unit] = (DevDiskRegisters*)
      ZMALLOC(sizeof(DevDiskRegisters), name);
    sim_disk_touch(node, ctrl, unit);
  }
}


static void
disk_status_update(int node, int ctrl, int unit)
{
  int done, bytes_tr, errno_val;
  DevDiskRegisters* regs = &DISK_SHADOW(node,ctrl,unit);

  sim_disk_status(node, ctrl, unit,
		  &done, &bytes_tr, &errno_val);

  regs->intr_pending     = (DevRegister)done;
  regs->bytesTransferred = (DevRegister)bytes_tr;
  regs->errnoVal         = (DevRegister)errno_val;
  regs->doneIO           = (DevRegister)done;
}

/*
 * Note: when running multiple machines, the following routine
 * is called with an absolute node number (i.e. not a machine-
 * relative one).
 */
static int
disk_handler(int node, int nd, int doff, int type, void* buff)
{
   int          nc    = NUM_DISK_CONTROLLERS(M_FROM_CPU(node),
                                             MCPU_FROM_CPU(node));
   int          uc    = DEV_DISK_MAX_UNIT / nc;
   int          ctrl  = nd / uc; /* controller */
   int          unit  = nd % uc; /* unit attached to controller */
   DevRegister* datap = (DevRegister*)buff;

   ASSERT(0 <= node && node < DISK_NODES &&
          0 <= ctrl && ctrl < nc         &&
          0 <= unit && unit < uc);

#if (DEBUG_MAGIC == 1)
   LogEntry("disk_handler", CPUVec.CurrentCpuNum(),
            "node=%d ctrl=%d unit=%d doff=0x%x t=%d data=0x%08x\n",
            node, ctrl, unit, doff, type, *datap);
#endif

   disk_touch(node, ctrl, unit);
  
  /* we only handle dword accesses and buserror all others */
   ASSERT (BDOOR_SIZE(type) == sizeof(DevRegister));
  
   if (doff == offsetof(DevDiskRegisters, intr_pending)) {
    
      if (BDOOR_IS_LOAD(type)) {
         /* note: bogus mapping (n,nd) -> SimOS disk #. To be improved */
         disk_status_update(node, ctrl, unit);
         *datap = DISK_SHADOW(node,ctrl,unit).intr_pending;
      } else {
         /* note: bogus mapping (n,nd) -> SimOS disk #. To be improved */
         sim_disk_iodone(node, ctrl, unit);
         disk_status_update(node, ctrl, unit);
      }
    
   } else if (doff == offsetof(DevDiskRegisters, errnoVal)) {
    
      if (BDOOR_IS_STORE(type)) goto illegal;
      disk_status_update(node, ctrl, unit);
      *datap = DISK_SHADOW(node,ctrl,unit).errnoVal;

   } else if (doff == offsetof(DevDiskRegisters, bytesTransferred)) {
    
      if (BDOOR_IS_STORE(type)) goto illegal;
      disk_status_update(node, ctrl, unit);
      *datap = DISK_SHADOW(node,ctrl,unit).bytesTransferred;
    
   } else if (doff == offsetof(DevDiskRegisters, interruptNode)) {
    
      /* interruptNode is always the first cpu of the
     * cell in the current implementation.
     * Writes to this register have no effect.
     */
      if (BDOOR_IS_LOAD(type)) *datap = (DevRegister)0;
    
   } else if (doff >= offsetof(DevDiskRegisters, k0Addr[0]) &&
              doff <= offsetof(DevDiskRegisters,
                               k0Addr[DEV_DISK_MAX_DMA_LENGTH-1])) {
    
      int ix = (doff-offsetof(DevDiskRegisters, k0Addr[0])) /
         sizeof(DevRegister);
      if (BDOOR_IS_LOAD(type)) {
         *datap = DISK_SHADOW(node,ctrl,unit).k0Addr[ix];
      } else {
         DISK_SHADOW(node,ctrl,unit).k0Addr[ix] = *datap;
      }
    
   } else if (doff == offsetof(DevDiskRegisters, offset)) {
    
      if (BDOOR_IS_LOAD(type)) {
         *datap = DISK_SHADOW(node,ctrl,unit).offset;
      } else {
         DISK_SHADOW(node,ctrl,unit).offset = *datap;
      }
    
   } else if (doff >= offsetof(DevDiskRegisters, command[0]) &&
              doff <= offsetof(DevDiskRegisters, command[DEV_DISK_CMD_SIZE-1])) {
    
      int ix = (doff-offsetof(DevDiskRegisters, command[0])) /
         sizeof(DevRegister);
      if (BDOOR_IS_LOAD(type)) {
         *datap = DISK_SHADOW(node,ctrl,unit).command[ix];
      } else {
         DISK_SHADOW(node,ctrl,unit).command[ix] = *datap;
      }    
   } else if (doff == offsetof(DevDiskRegisters, startIO)) {
    
      unsigned char cmd[SIM_DISK_CMD_SIZE];
      PA            pages[SIM_DISK_MAX_DMA_LENGTH];
      int           i;
    
      if (BDOOR_IS_LOAD(type)) goto illegal;
    
      /* note: bogus mapping (n,nd) -> SimOS disk #. To be improved */
      ASSERT(DEV_DISK_MAX_DMA_LENGTH <= SIM_DISK_MAX_DMA_LENGTH);
      ASSERT(DEV_DISK_CMD_SIZE <= SIM_DISK_CMD_SIZE);
    
      for (i = 0; i < SIM_DISK_CMD_SIZE; i++)
         cmd[i] = (unsigned char)DISK_SHADOW(node,ctrl,unit).command[i];
      for (i = 0; i < SIM_DISK_MAX_DMA_LENGTH; i++)
         pages[i] = DISK_SHADOW(node,ctrl,unit).k0Addr[i];
    
      sim_disk_startio(node, ctrl, unit,
                       cmd, pages, (int)DISK_SHADOW(node,ctrl,unit).offset);
    
   } else if (doff == offsetof(DevDiskRegisters, doneIO)) {
    
      if (BDOOR_IS_LOAD(type)) goto illegal;
      /* write is (almost) a no-op */
      DISK_SHADOW(node,ctrl,unit).doneIO = (DevRegister)0;
    
   } else {
      /* bad disk offset */
      ASSERT(0);
      return 0;
   }
   return 0;
  
illegal: /* illegal access type */
   ASSERT(0);
   return 1;
}

static void
disk_interrupt(int node, int ctrl, int unit, int on)
{
  int cpu;

  /* cpu to which interrupt is directed */
  if (inCellMode) {
    /* in cell mode (1 machine), node is absolute CPU number.
     * Must send interrupt to first CPU of that cell.
     */
    cpu = (node / CPUS_PER_CELL(0)) * CPUS_PER_CELL(0); /* CPU 0 in cell */
  } else {
    /* otherwise, node encodes both a machine number and a node.
     * Must send interrupt to first CPU in that machine.
     */
    cpu = FIRST_CPU(M_FROM_CPU(node));
  }

#if (DEBUG_MAGIC == 1)
  LogEntry("disk_interrupt", CPUVec.CurrentCpuNum(),
	   "node=%d ctrl=%d unit=%d cpu=%d on=%d\n",
	   node, ctrl, unit, cpu, on);
#endif

  if (on) RaiseSlot(cpu, DEV_PCI_DISK_SLOT);
  else    ClearSlot(cpu, DEV_PCI_DISK_SLOT);
}


/* CONSOLE device.
 *
 */
static int
console_handler(int cpuNum, int n, int offs, int type, void* buff)
{
  DevRegister* datap = (DevRegister*)buff;
  int        console;

  if (inCellMode) {
    console = n / CPUS_PER_CELL(0); /* XXX one console / cell */
  } else {
    console = FIRST_CONSOLE(M_FROM_CPU(cpuNum)) + n;
  }
#ifdef TORNADO
  ASSERT(n == cpuNum);
#endif

#if (DEBUG_MAGIC == 1)
  LogEntry("console_handler", cpuNum, "console=%d offs=0x%x t=%d data=0x%08x\n",
	   console, offs, type, *datap);
#endif

  /* we only handle DevRegister accesses and buserror all others */
  ASSERT (BDOOR_SIZE(type) == sizeof(DevRegister));

  switch (offs) {

  case offsetof(DevConsoleRegisters, intr_status):
     if (BDOOR_IS_LOAD(type)) {
        *datap = (DevRegister) sim_console_int_status(console);
     } else {
        sim_console_int_set(console, (int)*datap);
     }
     break;

  case offsetof(DevConsoleRegisters, data):
     if (BDOOR_IS_LOAD(type)) {
        *datap = (DevRegister) sim_console_in(console);
     } else {
        sim_console_out(console, (char)*datap);
     }
     break;

  default: ASSERT(0);
  }
  return 0;
}

static void
console_interrupt(int n, int on)
{
  int cpu;

  if (inCellMode) {
     /* always interrupts first CPU in cell */
     cpu = n * CPUS_PER_CELL(0);
  } else {
     cpu = FIRST_CPU(M_FROM_CONSOLE(n));
  }
#ifdef TORNADO
  /* Give to cpu n */
  cpu = n;
#endif
  if (on) RaiseSlot(cpu, DEV_PCI_CONSOLE_SLOT);
  else    ClearSlot(cpu, DEV_PCI_CONSOLE_SLOT);
}


/* ETHERNET device.
 *
 */
int
ether_handler(int cpuNum, int n, int offs, int type, void* buff)
{
  DevRegister* datap = (DevRegister*)buff;
  int          ctrl;

  if (inCellMode) {
    ctrl = n / CPUS_PER_CELL(0); /* XXX one console / cell */
  } else {
    ctrl = FIRST_ETHER_CONTROLLER(M_FROM_CPU(cpuNum)) + n;
  }

#if (DEBUG_MAGIC == 1)
  LogEntry("ether_handler", cpuNum, "ctrl=%d offs=0x%x t=%d data=0x%08x\n",
	   ctrl, offs, type, *datap);
#endif

  /* we only handle dword accesses and buserror all others */
  ASSERT (BDOOR_SIZE(type) == sizeof(DevRegister));

  /* NOTE: it so "happens" that the SimetherRegisters structure is
   * isomorphic to DevEtherRegisters. This helps us simplify the
   * mapping from the simulated registers to the ether simulator.
   */

  if (BDOOR_IS_LOAD(type)) {
    *datap = (DevRegister)SimetherIO(ctrl, offs, 0, (DevRegister)0);
  } else {
    (void)SimetherIO(ctrl, offs, 1, (DevRegister)*datap);
  }
  return 0;
}

static void
ether_interrupt(int n, int on)
{
  /* always interrupt first cpu in cell */
  int cpu;
  if (inCellMode) {
     cpu = n * CPUS_PER_CELL(0);
  } else {
     cpu = FIRST_CPU(M_FROM_ETHER_CONTROLLER(n));
  }
  if (on) RaiseSlot(cpu, DEV_PCI_ETHER_SLOT);
  else    ClearSlot(cpu, DEV_PCI_ETHER_SLOT);
}

/* A fundamental assumption of simether.c is that the DevEtherRegisters
 * (machine_defs.h) and the SimetherRegisters structures are isomorphic.
 * We'd better check for this.
 */
static void
check_ether_offs(void)
{
  ASSERT(offsetof(DevEtherRegisters, etheraddr[0]) == 
	 offsetof(SimetherRegisters, etheraddr[0]));
  ASSERT(offsetof(DevEtherRegisters, numRcvEntries) == 
	offsetof(SimetherRegisters, numRcvEntries));
  ASSERT(offsetof(DevEtherRegisters, numSndEntries) ==
	 offsetof(SimetherRegisters, numSndEntries));
  ASSERT(offsetof(DevEtherRegisters, numSndChunks) ==
	 offsetof(SimetherRegisters, numSndChunks));
  ASSERT(offsetof(DevEtherRegisters, rcvEntries[0].pAddr) ==
	 offsetof(SimetherRegisters, rcvEntries[0].pAddr));
  ASSERT(offsetof(DevEtherRegisters, rcvEntries[0].maxLen) ==
	 offsetof(SimetherRegisters, rcvEntries[0].maxLen));
  ASSERT(offsetof(DevEtherRegisters, rcvEntries[0].len) ==
	 offsetof(SimetherRegisters, rcvEntries[0].len));
  ASSERT(offsetof(DevEtherRegisters, rcvEntries[0].flag) ==
	 offsetof(SimetherRegisters, rcvEntries[0].flag));
  ASSERT(offsetof(DevEtherRegisters, sndEntries[0].firstChunk) ==
	 offsetof(SimetherRegisters, sndEntries[0].firstChunk));
  ASSERT(offsetof(DevEtherRegisters, sndEntries[0].lastChunk) ==
	 offsetof(SimetherRegisters, sndEntries[0].lastChunk));
  ASSERT(offsetof(DevEtherRegisters, sndEntries[0].flag) ==
	 offsetof(SimetherRegisters, sndEntries[0].flag));
  ASSERT(offsetof(DevEtherRegisters, sndChunks[0].pAddr) ==
	 offsetof(SimetherRegisters, sndChunks[0].pAddr));
  ASSERT(offsetof(DevEtherRegisters, sndChunks[0].len) ==
	 offsetof(SimetherRegisters, sndChunks[0].len));
}


/* CMOS RT clock device.
 *
 */
static int
clock_handler(int cpuNum, int n, int offs, int type, void* buff)
{
  DevRegister* datap = (DevRegister*)buff;

  ASSERT (BDOOR_SIZE(type) == sizeof(DevRegister));

  if (BDOOR_IS_LOAD(type)) {
     int secsSinceStart = CyclesToNanoSecs(CPUVec.CycleCount(cpuNum))/1000000000;
    *datap = (DevRegister)(machines.InitialTime + secsSinceStart);
  } else {
    ASSERT(0); /* for debugging */
    return 1;  /* clock register not writable */
  }
  return 0;
}



/****************************************************************************
 *
 * MAGIC initialization / registry code
 *
 ****************************************************************************/

#define VA_NODE(va) (((va) >> __MAGIC_NODE_OFFS) & \
		     ((1<<__MAGIC_NODE_BITS)-1))
#define VA_ZONE(va) (((va) >> __MAGIC_ZONE_OFFS) & \
		     ((1<<__MAGIC_ZONE_BITS)-1))
#define VA_REG(va) (((va) >> __MAGIC_REG_OFFS) & \
		    ((1<<__MAGIC_REG_BITS)-1))
#define VA_GRP(va) (((va) >> __MAGIC_PPC_GRP_OFFS) & \
		    ((1<<__MAGIC_PPC_GRP_BITS)-1))
#define VA_OPC(va) (((va) >> __MAGIC_PPC_OPC_OFFS) & \
		    ((1<<__MAGIC_PPC_OPC_BITS)-1))
#define VA_SEQ(va) (((va) >> __MAGIC_PPC_SEQ_OFFS) & \
		    ((1<<__MAGIC_PPC_SEQ_BITS)-1))
#define VA_OFFS(va) ((va) & ((1<<__MAGIC_ZONE_OFFS)-1))


static int
FPROM_access(int cpuNum, uint VA, int type, uint* buff)
{
   /* boot prom must be initialized, else this is a bus error */
   /* ASSERT(sim_misc.fprom != NULL); */
   if (sim_misc.fprom[cpuNum] == NULL) {
      return BUSERROR;  
   }

  ASSERT(!USE_MAGIC() || !FPromUseFL);
#ifndef N64
  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_FPROM_ALIAS);
#endif

#if 0
  ASSERT(type == BDOOR_LOAD_WORD);
  ASSERT(VA_OFFS(VA) < FPROM_SIZE);
  *(uint *)buff = *(uint *)(VA_OFFS(VA)+sim_misc.fprom[cpuNum]);
#else
#define WRITABLE_ROM
#ifdef WRITABLE_ROM
  if (BDOOR_IS_STORE(type)) {
    CPUWarning("Warning: writing to rom address 0x%x\n", (int)VA);
  }
#endif
  switch (type) {
  case BDOOR_LOAD_BYTE:
     ASSERT(VA_OFFS(VA) < FPROM_SIZE);
     *(byte *)buff = *(byte *)(VA_OFFS(VA)+sim_misc.fprom[cpuNum]);
     break;
  case BDOOR_LOAD_HALF:
     ASSERT(VA_OFFS(VA) < FPROM_SIZE);
     *(unsigned short *)buff = *(unsigned short *)(VA_OFFS(VA)+sim_misc.fprom[cpuNum]);
     break;
  case BDOOR_LOAD_WORD:
     ASSERT(VA_OFFS(VA) < FPROM_SIZE);
     *(uint *)buff = *(uint *)(VA_OFFS(VA)+sim_misc.fprom[cpuNum]);
     break;
  case BDOOR_LOAD_DOUBLE:
     ASSERT(VA_OFFS(VA) < FPROM_SIZE);
     *(uint64*)buff = *(uint64*)(VA_OFFS(VA)+sim_misc.fprom[cpuNum]);
     break;
#ifdef WRITABLE_ROM
  case BDOOR_STORE_BYTE:
     ASSERT(VA_OFFS(VA) < FPROM_SIZE);
     *(byte *)(VA_OFFS(VA)+sim_misc.fprom[cpuNum]) = *(byte *)buff;
     break;
  case BDOOR_STORE_HALF:
     ASSERT(VA_OFFS(VA) < FPROM_SIZE);
     *(unsigned short *)(VA_OFFS(VA)+sim_misc.fprom[cpuNum]) = *(unsigned short *)buff;
     break;
  case BDOOR_STORE_WORD:
     ASSERT(VA_OFFS(VA) < FPROM_SIZE);
     *(uint *)(VA_OFFS(VA)+sim_misc.fprom[cpuNum]) = *(uint *)buff;
     break;
  case BDOOR_STORE_DOUBLE:
     ASSERT(VA_OFFS(VA) < FPROM_SIZE);
     *(uint64*)(VA_OFFS(VA)+sim_misc.fprom[cpuNum]) = *(uint64*)buff;
     break;
#endif
  default:
     CPUError("FPROM access is not supported by type %d", type);
  }
#endif
  return 0;
}

static int
FRAM_access(int cpuNum, uint VA, int type, uint* buff)
{
  /* boot prom must be initialized */
  ASSERT(sim_misc.fprom[cpuNum] != NULL);
  ASSERT(!USE_MAGIC() || !FPromUseFL);
  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_FRAM_ALIAS);

#ifdef LARGE_SIMULATION
  if (VA_NODE(VA) == 127) {
     /* this is really a fprom access from VA 0xbfc0....  */
     return FPROM_access(cpuNum, VA, type, buff);
  }
#endif

  ASSERT(VA_OFFS(VA) < FRAM_SIZE);

  switch (type) {
  case BDOOR_LOAD_BYTE:
     ASSERT(VA_OFFS(VA) < FRAM_SIZE);
     *(byte *)buff = *(byte *)(VA_OFFS(VA)+sim_misc.fram[cpuNum]);
     break;
  case BDOOR_LOAD_HALF:
     ASSERT(VA_OFFS(VA) < FRAM_SIZE);
     *(unsigned short *)buff = *(unsigned short *)(VA_OFFS(VA)+sim_misc.fram[cpuNum]);
     break;
  case BDOOR_LOAD_WORD:
     ASSERT(VA_OFFS(VA) < FRAM_SIZE);
     *(uint *)buff = *(uint *)(VA_OFFS(VA)+sim_misc.fram[cpuNum]);
     break;
  case BDOOR_LOAD_DOUBLE:
     ASSERT(VA_OFFS(VA) < FRAM_SIZE);
     *(uint64*)buff = *(uint64*)(VA_OFFS(VA)+sim_misc.fram[cpuNum]);
     break;
  case BDOOR_STORE_BYTE:
     /* also need to check if the fram is writeable during recovery,
      but for now this will do... */
     ASSERT(VA_OFFS(VA) < FRAM_SIZE);
     *(byte *)(VA_OFFS(VA)+sim_misc.fram[cpuNum]) = *(byte *)buff;
     break;
  case BDOOR_STORE_HALF:
     /* also need to check if the fram is writeable during recovery,
      but for now this will do... */
     ASSERT(VA_OFFS(VA) < FRAM_SIZE);
     *(unsigned short *)(VA_OFFS(VA)+sim_misc.fram[cpuNum]) = *(unsigned short *)buff;
     break;
  case BDOOR_STORE_WORD:
     /* also need to check if the fram is writeable during recovery,
      but for now this will do... */
     ASSERT(VA_OFFS(VA) < FRAM_SIZE);
     *(uint *)(VA_OFFS(VA)+sim_misc.fram[cpuNum]) = *(uint *)buff;
     break;
  case BDOOR_STORE_DOUBLE:
     /* also need to check if the fram is writeable during recovery,
      but for now this will do... */
     ASSERT(VA_OFFS(VA) < FRAM_SIZE);
     *(uint64*)(VA_OFFS(VA)+sim_misc.fram[cpuNum]) = *(uint64*)buff;
     break;
  default:
     CPUError("FRAM access is not supported by type %d", type);
  }
  return 0;
}

#ifdef SUPPORT_LINUX
static int 
MILO_access(int cpuNum, uint VA, int type, void *buff)
{
   ASSERT(VA_ZONE(VA) == MAGIC_ZONE_MILO_ALIAS);
   switch (type) {
   case BDOOR_LOAD_WORD:
     if (!VA_OFFS(VA)) { 
       *(uint*)buff = sizeof(tagPairs);
     } else { 
       *(uint *)buff = *(uint*)(VA_OFFS(VA)+(uint)&tagPairs-4);
     }
     CPUWarning("MILO: %x  val=%x \n",
		VA_OFFS(VA), *(uint *)buff );
		
     break;
   default: 
     ASSERT(0);
   }
   return 0;
 }
#endif

static int
PPRALIAS_access(int cpuNum, uint VA, int type, void* buff)
{
  /* PPR alias: always accesses local node PPR */
  ASSERT(!USE_MAGIC());
  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_PPR_ALIAS);
  return PPR_handler(cpuNum, cpuNum, VA_REG(VA), type, buff);
}

static int
PPCALIAS_access(int cpuNum, uint VA, int type, void* buff)
{
  /* PPC alias: always accesses local node PPC */
/* some PPC are not implemented in flashlite, so need to run them
   through simmagic even with USE_MAGIC set.. 
   ASSERT(!USE_MAGIC());
   */
  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_PPC_ALIAS);
  return PPC_handler(cpuNum, cpuNum,
		     VA_GRP(VA), VA_OPC(VA), VA_SEQ(VA), type, buff);
}

static int
FIREWALL_access(int cpuNum, uint VA, int type, void* buff)
{
  MagicRegister* datap = (MagicRegister*)buff;
  int            node  = FIRST_CPU(M_FROM_CPU(cpuNum)) + VA_NODE(VA);
  int            pg    = VA_OFFS(VA)/sizeof(MagicRegister);

  ASSERT(!USE_MAGIC());
  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_FIREWALL);

  /* actually, we should return a bus error for accesses which fall
   * outside the valid range. For now, we have an assertion since this
   * makes things easier to debug.
   */
  ASSERT(pg < (MEM_SIZE(M_FROM_CPU(cpuNum))
               / NUM_CPUS(M_FROM_CPU(cpuNum))));

  if (type == BDOOR_LOAD_DOUBLE) {

    /* anyone can read the firewall status */
    *datap = (MagicRegister)sim_firewall_page_prot(node, pg);

  } else if (type == BDOOR_STORE_DOUBLE) {
    /* only nodes in the same cell and cells which have firewall write
     * access to this page can write the firewall.
     */
    return sim_firewall_set_page_prot(cpuNum, node, pg, (uint64)*datap);

  } else return 1; /* can only handle dword accesses */
  return 0;
}

/*
 * Routine called when the MIG_REP zone is accessed 
 * for reading or setting cache-miss or write counters.
 */
static int
MIG_REP_access(int cpuNum, uint VA, int type, void* buff)
{
  MagicRegister* datap = (MagicRegister*)buff;
  int            node  = FIRST_CPU(M_FROM_CPU(cpuNum)) + VA_NODE(VA);
  unsigned long  pg    = VA_OFFS(VA);

  ASSERT(!USE_MAGIC());
  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_MIG_REP);

  if (IS_NUMA()) {
     unsigned long typeMask = (1<<(__MAGIC_ZONE_OFFS-1));
     unsigned long countType = pg & typeMask;
     unsigned long countAddr = (pg & (~typeMask))/sizeof(uint64);

     if (type == BDOOR_LOAD_DOUBLE) {

        *datap = (MagicRegister) MigRepGetInfo(pg, node, countType, countAddr);
     } else if (type == BDOOR_STORE_DOUBLE) {
        MigRepSetInfo(pg, node, *datap, countType, countAddr);
     } else {
        return 1; /* can only handle dword accesses */
     }
  } else {
     /*
      * For now we just return 0 for reads and do nothing for writes
      */
     if (type == BDOOR_LOAD_DOUBLE) {
        *datap = (MagicRegister) 0;
     } else if (type == BDOOR_STORE_DOUBLE) {
     } else {
        return 1; /* can only handle dword accesses */
     }
  }
  return 0;
}

static int
PPR_access(int cpuNum, uint VA, int type, void* buff)
{
  /* PPR access to specified node */
  int n = FIRST_CPU(M_FROM_CPU(cpuNum)) + VA_NODE(VA);
  ASSERT(!USE_MAGIC());
  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_PPR);
  return PPR_handler(cpuNum, n, VA_REG(VA), type, buff);
}

static int
PPC_access(int cpuNum, uint VA, int type, void* buff)
{  
  /* PPC access to specified node */
  int n = FIRST_CPU(M_FROM_CPU(cpuNum)) + VA_NODE(VA);
  ASSERT(!USE_MAGIC());
  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_PPC);
  return PPC_handler(cpuNum, n,
		     VA_GRP(VA), VA_OPC(VA), VA_SEQ(VA), type, buff);
}

static int
BDOOR_disk_access(int cpuNum, uint VA, int type, void* buff)
{
  int node = VA_NODE(VA); /* relative to current machine */
  int offs = VA_OFFS(VA) - __MAGIC_BDOOR_DISKS_OFFS;
  int nd   = offs / sizeof(DevDiskRegisters); /* unit # */
  int doff = offs % sizeof(DevDiskRegisters); /* offset in unit regs */

  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_BDOOR_DEV);

  /* XXX
   * Uncomment the following assert when not using more disk
   * controllers than nodes any longer. Currently, I think this
   * is only used for DISCO. DT.
   * XXX
   */
  /* ASSERT(0 <= node && node < NUM_CPUS(M_FROM_CPU(cpuNum))); */

  /* Note for multiple machines:
   * must translate this access to an absolute node number.
   */
  return disk_handler(node + FIRST_CPU(M_FROM_CPU(cpuNum)),
		      nd, doff, type, buff);
}

static int
BDOOR_console_access(int cpuNum, uint VA, int type, void* buff)
{
  int n    = VA_NODE(VA);
  int offs = VA_OFFS(VA) - __MAGIC_BDOOR_CNSLE_OFFS;

  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_BDOOR_DEV);
  ASSERT(!inCellMode || (n % CPUS_PER_CELL(0) == 0)); 
  ASSERT(0 <= offs && offs < sizeof(DevConsoleRegisters));

  return console_handler(cpuNum, n, offs, type, buff);
}

static int
BDOOR_ether_access(int cpuNum, uint VA, int type, void* buff)
{
  int n    = VA_NODE(VA);
  int offs = VA_OFFS(VA) - __MAGIC_BDOOR_ETHER_OFFS;

  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_BDOOR_DEV);
  ASSERT(!inCellMode || (n % CPUS_PER_CELL(0) == 0)); 
  ASSERT(0 <= offs && offs < sizeof(DevEtherRegisters));

  return ether_handler(cpuNum, n, offs, type, buff);
}

static int
BDOOR_clock_access(int cpuNum, uint VA, int type, void* buff)
{
  int n    = VA_NODE(VA);
  int offs = VA_OFFS(VA) - __MAGIC_BDOOR_CLOCK_OFFS;

  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_BDOOR_DEV);
  ASSERT(!inCellMode || (n % CPUS_PER_CELL(0) == 0)); 
  ASSERT(0 <= offs && offs < sizeof(DevClockRegisters));

  return clock_handler(cpuNum, n, offs, type, buff);
}

#ifdef TORNADO
static int
BDOOR_gizmo_access(int cpuNum, uint VA, int type, void* buff)
{
  int n    = VA_NODE(VA);
  int offs = VA_OFFS(VA) - __MAGIC_BDOOR_GIZMO_OFFS;

  ASSERT(VA_ZONE(VA) == MAGIC_ZONE_BDOOR_DEV);
  ASSERT(0 <= offs && offs < sizeof(DevGizmoRegisters));

  return gizmo_handler(cpuNum, n, offs, type, buff);
}
#endif /* TORNADO */


static int
OSPC_access(int cpuNum, uint VA, int type, void* buff)
{
  int offs = VA & (MAGIC_OSPC_SIZE-1);
  int err;
  byte ospc_buff[MAGIC_OSPC_SIZE];

  ASSERT(!USE_MAGIC());
  ASSERT(VA >= __MAGIC_OSPC_BASE && VA < __MAGIC_OSPC_END);

  if (type != BDOOR_LOAD_BYTE &&
      type != BDOOR_LOAD_HALF &&
      type != BDOOR_LOAD_WORD &&
      type != BDOOR_LOAD_DOUBLE) {
    ASSERT(0); /* for debugging */
    return 1;
  }

  err = sim_magic_OSPC_access(cpuNum, VA, ospc_buff);
  ASSERT(err >= 0);

  switch (type) {
  case BDOOR_LOAD_BYTE:
    *(unsigned char*)buff = ((unsigned char*)ospc_buff)[offs];
#if (DEBUG_MAGIC == 1)
    LogEntry("OSPC_access", cpuNum, "VA 0x%08x BYTE data 0x%02x\n",
	     VA, *(unsigned char*)buff);
#endif
    break;
  case BDOOR_LOAD_HALF:
    *(unsigned short*)buff =
      ((unsigned short*)ospc_buff)[offs/sizeof(unsigned short)];
#if (DEBUG_MAGIC == 1)
    LogEntry("OSPC_access", cpuNum, "VA 0x%08x HALF data 0x%04x\n",
	     VA, *(unsigned short*)buff);
#endif
    break;
  case BDOOR_LOAD_WORD:
    ASSERT(offs % sizeof(uint) == 0);
    *(uint*)buff   = ((uint*)ospc_buff)[offs/sizeof(uint)];
#if (DEBUG_MAGIC == 1)
    LogEntry("OSPC_access", cpuNum, "VA 0x%08x WORD data 0x%08x\n",
	     VA, *(uint*)buff);
#endif
    break;
  case BDOOR_LOAD_DOUBLE:
    ASSERT(offs % sizeof(uint64) == 0);
    *(uint64*)buff = ((uint64*)ospc_buff)[offs/sizeof(uint64)];
#if (DEBUG_MAGIC == 1)
    LogEntry("OSPC_access", cpuNum, "VA 0x%08x DWORD data 0x%016lx\n",
	     VA, *(uint64*)buff);
#endif
    break;
  }
  return 0;
}


/* CAVEAT: we currently DON'T model the latency of getting an OSPC
 * cacheline when not running under Flashlite. This is not tragic,
 * but should be fixed at some point.
 */
Result 
sim_magic_MemsysCmd(int cpunum, int cmd, unsigned int paddr,
                    int transId,  unsigned int replacedPaddr, 
                    int writeback, byte *data)
{
  int command = cmd & MEMSYS_CMDMASK;
  int flavor  = cmd & (~MEMSYS_CMDMASK);
  byte *wb_buff = data;
  Result res;

  /* Is this an OSPC access we should handle? */
  if ( 0 &&
       !USE_MAGIC()                                                  &&
       (command == MEMSYS_GET || command == MEMSYS_REPLACEMENT_HINT) &&
       (flavor == 0)                                                 &&
       (paddr >= (__MAGIC_OSPC_BASE - K0BASE) &&
	paddr <  (__MAGIC_OSPC_BASE - K0BASE + 2*MAGIC_OSPC_SIZE)) ) {

CPUWarning("OSPC access...\n");

    /* OSPC access -- handle hic et nunc */
    if (cmd == MEMSYS_GET) {
      /* Note: paddr is critical-word-first, which is irrelevant for now */
      unsigned int offs = (paddr & ~(MAGIC_OSPC_SIZE-1)) -
	                  (__MAGIC_OSPC_BASE - K0BASE);
      byte ospc_buff[MAGIC_OSPC_SIZE];
      static byte wb_save[MAGIC_OSPC_SIZE];
      MagicRegister errval, okval;
      int err;

      /* read the data -- for now, this is only SIPS data */
      switch (offs) {
      case MAGIC_OSPC_LO_OFFS:
	errval = MAGIC_OSPC_LO_NONE;
	okval  = MAGIC_OSPC_LO_SIPSREQ;
	err = sim_sips_get(cpunum, 1, ospc_buff);
	break;
      case MAGIC_OSPC_HI_OFFS:
	okval  = MAGIC_OSPC_HI_SIPSREPLY;
	errval = MAGIC_OSPC_HI_NONE;
	err = sim_sips_get(cpunum, 0, ospc_buff);
	break;
      default: ASSERT(0);
      }
      /* SIPS status */
      *((MagicRegister*)ospc_buff) = err ? errval : okval;

      /* Note: at this point, the GET is done, as far as we're concerned.
       * However, we still might have to do a WB, which might stall.
       * This is sort of perverse, since we're actually doing the operations
       * in the reverse order than on the real machine (i.e. we're satisfying
       * the GET first...
       * In order to avoid clobbering the unique copy of the wb data, we'll
       * save it to a private buffer.
       */
      ASSERT(MAGIC_OSPC_SIZE >= SCACHE_LINE_SIZE);
      bcopy(wb_buff, wb_save, sizeof(wb_save));
      wb_buff = wb_save;

      /* Now tell the processor the GET has completed. If the WB stalls,
       * then we'll call MipsyStall to stall the processor (!).
       * THIS IS A HACK!!!
       */
      CacheCmdDone(cpunum, transId, MEMSYS_SHARED, MEMSYS_STATUS_SUCCESS,
		   MEMSYS_RESULT_MEMORY, ospc_buff);
    }
    /* else: replacement hint is ignored */
    if (writeback) {
      ASSERT((paddr & ~(MAGIC_OSPC_SIZE-1)) !=
	     (replacedPaddr & ~(MAGIC_OSPC_SIZE-1)));
      /* Need to perform the writeback, too! */
      res = memsysVec.MemsysCmd(cpunum, MEMSYS_GET, 0LL, -1,
                                replacedPaddr, writeback, data);
      if (res == STALL) {
	/* oops, write buffer filled up. We'll have to stall the
	 * CPU again. This is a total hack.
	 */
	CPUWarning("Stalling during OSPC....\n");
      }
      return res;
    } else {
      return SUCCESS;
    }
  } else
    /* Main memory access -- pass on unaffected */
    return memsysVec.MemsysCmd(cpunum, cmd, paddr, transId,
                               replacedPaddr, writeback, data);
}


/*
 * Device polling. Some simulated devices which take asynchronous
 * input from the "real world" need to have a poll function called
 * periodically to check for input.
 */
static EventCallbackHdr pollHdr;	/* poll devices callback */

static void PollDevices(int cpuNum, EventCallbackHdr *hdr, void *arg)
{
#if (DEBUG_MAGIC == 1)
  LogEntry("PollDevices", 0, "\n");
#endif

  /* 1. Poll all consoles */
  sim_console_poll();
  /* 2. Poll all ethernet interfaces */
#ifndef linux
  SimetherPoll();
#endif
#ifdef TORNADO
  /* 3. Poll gizmo interface */
  gizmo_poll();
#endif /* TORNADO */


  /* register callback for next poll round */
  EventDoCallback(0, PollDevices, &pollHdr, NULL, MAGIC_POLL_INTERVAL);
}

void InstallPoller(void)
{
  static int installed = 0;
  if (!installed) {
    installed = 1;
    EventDoCallback(0, PollDevices, &pollHdr, NULL, MAGIC_POLL_INTERVAL);
  }
}


/* ***
 * *** MAGIC & devices initialization.
 * ***
 * *** Initialize all devices, device polling, MAGIC emulation, etc.
 * ***
 */

static void
InitDevices(int restoreFromChkpt)
{

  /*
   * CPUVector
   */
  
  CPUVec.UncachedPIO = SimMagic_DoPIO;

  /* disks */
  {
    int m, n, uc = NUM_UNITS_PER_CONTROLLER(0);
    for (m = 0; m < NUM_MACHINES; m++)
      for (n = 0; n < TOTAL_CPUS; n++) {
	ASSERT(NUM_UNITS_PER_CONTROLLER(m) * NUM_DISK_CONTROLLERS(m,n) <=
	       DEV_DISK_MAX_UNIT);
	ASSERT(uc == NUM_UNITS_PER_CONTROLLER(m));
      }
  }
  sim_disk_init(DISK_NODES,
		NUM_UNITS_PER_CONTROLLER(0),
		disk_interrupt, restoreFromChkpt);

  /* ethernet interfaces */
  SimetherInit(restoreFromChkpt, ether_interrupt);

  /* consoles */
  sim_console_init(TOTAL_CONSOLES, console_interrupt);


  /* NOTE: at this point, we'd also like to initialize polling (for those
   * devices that need it). Unfortunately, this depends on the CPUVec
   * being more completely initialized than it is now (before any CPU
   * simulator has started). So we'll let the CPU simulators call
   * InstallPoller().
   */

  /* 3. Misc. initialization */
  sim_sips_init(TOTAL_CPUS, sips_interrupt);

  /* 4. Checkpointing stuff */
  Simcpt_Register("magic", SimMagic_CheckpointCB, ALL_CPUS);

  if (restoreFromChkpt) Simcpt_Restore("magic");
}

static void
BuildDeviceToMachine(void)
{
   int machNo, count;

   /*
    * Build the arrays that map from device number back to machine number
    */
   
   deviceToMachine.console = (int*)malloc(TOTAL_CONSOLES*sizeof(int));
   deviceToMachine.ether = (int*)malloc(TOTAL_ETHER_CONTROLLERS*sizeof(int));
   deviceToMachine.clock = (int*)malloc(TOTAL_CLOCKS*sizeof(int));
   ASSERT(deviceToMachine.console);
   ASSERT(deviceToMachine.ether);
   ASSERT(deviceToMachine.clock);

   for (machNo = 0; machNo < NUM_MACHINES; machNo++) {
      for (count = FIRST_CONSOLE(machNo);
           count <= LAST_CONSOLE(machNo); count++) {
         deviceToMachine.console[count] = machNo;
      }
      for (count = FIRST_ETHER_CONTROLLER(machNo);
           count <= LAST_ETHER_CONTROLLER(machNo); count++) {
         deviceToMachine.ether[count] = machNo;
      }
      for (count = FIRST_CLOCK(machNo);
           count <= LAST_CLOCK(machNo); count++) {
         deviceToMachine.clock[count] = machNo;
      }
   }
}



#define ZONE_SZ (1 << __MAGIC_ZONE_OFFS)

void
sim_magic_init(int restoreFromChkpt)
{
  int n;
  char name[128];

  if (inCellMode) {
     ASSERT((NUM_CPUS(0) / NUM_CELLS(0)) * NUM_CELLS(0) == NUM_CPUS(0)); 
  }

  CHECK_FOR_COMPILER_BUG;
  CHECK_FOR_COMPILER_BUG2;

  BuildDeviceToMachine();

  /* 1. Initialize service ranges for all nodes */

  for (n = 0; n < MAX_CPUS_PER_MACHINE; n++) {
#if 0  
#ifdef SUPPORT_LINUX
     /* MILO alias */
     sprintf(name, "MILO alias %d", n);
     RegistryAddRange((VA)__MAGIC_ZONE(n, 0, MAGIC_ZONE_MILO_ALIAS), ZONE_SZ,
                      REG_FUNC, (void*)MILO_access, name);
#endif
#endif

     /* FRAM alias */
     sprintf(name, "FRAM alias %d", n);
     RegistryAddRange((VA)__MAGIC_ZONE(n, 0, MAGIC_ZONE_FRAM_ALIAS), ZONE_SZ,
                      REG_FUNC, (void*)FRAM_access, name);
     /* PPR alias */
     sprintf(name, "PPR alias %d", n);
     RegistryAddRange((VA)__MAGIC_ZONE(n, 0, MAGIC_ZONE_PPR_ALIAS), ZONE_SZ,
                      REG_FUNC, (void*)PPRALIAS_access, name);
     /* PPC alias */
     sprintf(name, "PPC alias %d", n);
     RegistryAddRange((VA)__MAGIC_ZONE(n, 0, MAGIC_ZONE_PPC_ALIAS), ZONE_SZ,
                      REG_FUNC, (void*)PPCALIAS_access, name);
     /* FIREWALL */
     sprintf(name, "FIREWALL %d", n);
     RegistryAddRange((VA)__MAGIC_ZONE(n, 0, MAGIC_ZONE_FIREWALL), ZONE_SZ,
                      REG_FUNC, (void*)FIREWALL_access, name);
     /* PPR */
     sprintf(name, "PPR %d", n);
     RegistryAddRange((VA)__MAGIC_ZONE(n, 0, MAGIC_ZONE_PPR), ZONE_SZ,
                      REG_FUNC, (void*)PPR_access, name);
     /* PPC */
     sprintf(name, "PPC %d", n);
     RegistryAddRange((VA)__MAGIC_ZONE(n, 0, MAGIC_ZONE_PPC), ZONE_SZ,
                      REG_FUNC, (void*)PPC_access, name);
     
#ifndef LARGE_SIMULATION
     /* in large simulation with only 32 bits, zone number for 0xbfc0xxxx
        ends up being 0 (same as FRAM) */
     /* FPROM alias */
     sprintf(name, "FPROM alias %d", n);
     RegistryAddRange((VA)__MAGIC_ZONE(n, 0, MAGIC_ZONE_FPROM_ALIAS), ZONE_SZ,
                      REG_FUNC, (void*)FPROM_access, name);
#endif
     
#ifdef TORNADO
     sprintf(name, "Gizmo %d", n);
     RegistryAddRange((VA)(__MAGIC_ZONE(n, 0, MAGIC_ZONE_BDOOR_DEV) +
                           __MAGIC_BDOOR_GIZMO_OFFS), 0x1000,
                      REG_FUNC, (void*)BDOOR_gizmo_access, name);
#endif /* TORNADO */
     
     /* MIG_REP alias */
     sprintf(name, "MIG_REP alias %d", n);
     RegistryAddRange((VA)__MAGIC_ZONE(n, 0, MAGIC_ZONE_MIG_REP), ZONE_SZ,
                      REG_FUNC, (void*)MIG_REP_access, name);
  }

  /*
   * Add all the devices to the registry.
   * Add devices are numbered 0 to the MAXVAL-1
   * Here we map the address spaces for the largest number of devices on any
   * one machine.
   * When using cells, they are numbered by cell.
   * Use M_FROM_CONSOLE, M_FROM_ETHER_CONTROLLER,
   * or M_FROM_CLOCK to find machine number.
   */
  
  /* XXX caveat DISCO XXX */
  for (n = 0; n < DISK_NODES; n++) {
     sprintf(name, "DevDiskRegisters %d", n);
     RegistryAddRange((VA)(__MAGIC_ZONE(n, 0, MAGIC_ZONE_BDOOR_DEV) +
                           __MAGIC_BDOOR_DISKS_OFFS),
                      sizeof(DevDiskRegisters)*DEV_DISK_MAX_UNIT,
                      REG_FUNC, (void*)BDOOR_disk_access, name);
  }
  for (n = 0; n < MAX_CONSOLES_PER_MACHINE; n++) {
     int node = n * CPUS_PER_CELL(0);
     sprintf(name, "DevConsoleRegisters %d", node);
     RegistryAddRange((VA)(__MAGIC_ZONE(node, 0, MAGIC_ZONE_BDOOR_DEV) +
                           __MAGIC_BDOOR_CNSLE_OFFS),
                      sizeof(DevConsoleRegisters),
                      REG_FUNC, (void*)BDOOR_console_access, name);
  }
  check_ether_offs();
  for (n = 0; n < MAX_ETHER_CONTROLLERS_PER_MACHINE; n++) {
     int node = n * CPUS_PER_CELL(0);
     sprintf(name, "DevEtherRegisters %d", node);
     RegistryAddRange((VA)(__MAGIC_ZONE(node, 0, MAGIC_ZONE_BDOOR_DEV) +
                           __MAGIC_BDOOR_ETHER_OFFS),
                      sizeof(DevEtherRegisters),
                      REG_FUNC, (void*)BDOOR_ether_access, name);
  }
  for (n = 0; n < MAX_CLOCKS_PER_MACHINE; n++) {
     int node = n * CPUS_PER_CELL(0);
     sprintf(name, "DevClockRegisters %d", node);
     RegistryAddRange((VA)(__MAGIC_ZONE(node, 0, MAGIC_ZONE_BDOOR_DEV) +
                           __MAGIC_BDOOR_CLOCK_OFFS),
                      sizeof(DevClockRegisters),
                      REG_FUNC, (void*)BDOOR_clock_access, name);
  }
  
  {
#ifdef LARGE_SIMULATION
     int fpromCPU = 127;
#else
     int fpromCPU = 31;
#endif
     /* need to add FPROM alias for the range 0xbfc00000 */
     if (MAX_CPUS_PER_MACHINE < fpromCPU) {
        /* FPROM alias */
        sprintf(name, "FPROM alias %d", fpromCPU);
        RegistryAddRange((VA)__MAGIC_ZONE(fpromCPU, 0, MAGIC_ZONE_FPROM_ALIAS),
                         ZONE_SZ, REG_FUNC, (void*)FPROM_access, name);
     }
  }
  
  /* OSPC range is kind of special, since in the 32 bit address space
   * version there is only one range (0x80001000 - 0x80001fff), which
   * is an alias for each node's local range. We register this, too.
   */
  sprintf(name, "OSPC range");
  RegistryAddRange((VA)__MAGIC_OSPC_BASE,
                   __MAGIC_OSPC_END - __MAGIC_OSPC_BASE,
                   REG_FUNC, (void*)OSPC_access, name);
  
#if (DEBUG_MAGIC == 1)
  RegistryDumpEntries();
#endif
  RegistryComplete();
  
  /* init shadow data structures for disk handlers */
  disk_initialize();
  
  InitDevices(restoreFromChkpt);
}


/****************************************************************************
 *
 * KSEG1 access type.
 *
 ****************************************************************************/

/*
 * SimMagic_kseg1_accesstype: determine whether a given KSEG1
 *    address should be accessed directly without memory system
 *    activity (SIMMAGIC_DIRECT), passed to the memory system
 *    as an uncached access (SIMMAGIC_UNCACHED) or passed to
 *    the memory system as an accelerated uncached access
 *    (SIMMAGIC_UNCACHED_ACCELERATED).
 *
 * Note that making the distinction between uncached and uncached_accelerated
 * here is purely a workaround, until we improve the OS and the cop0
 * model to construct the access type directly.
 *
 * XXX for now, FRAM and FPROM accesses are handled by sim_magic.c.
 * Need a switch to select beween this (faster) option and the
 * (realistic) one of letting those accesses go to Flite.
 */
SimMagic_accesstype
SimMagic_kseg1_accesstype(uint VA)
{
  switch (VA_ZONE(VA)) {

  case MAGIC_ZONE_FRAM_ALIAS:
#ifndef LARGE_SIMULATION
     /* in large_simulation, fram and fprom zones are the same */
  case MAGIC_ZONE_FPROM_ALIAS:
#endif
    if (USE_MAGIC() && FPromUseFL) return SIMMAGIC_UNCACHED;
    else                         return SIMMAGIC_DIRECT;

  case MAGIC_ZONE_MILO_ALIAS:
    return SIMMAGIC_DIRECT;
    
  case MAGIC_ZONE_PPR_ALIAS:
  case MAGIC_ZONE_FIREWALL:
  case MAGIC_ZONE_PPR:
  case MAGIC_ZONE_MIG_REP:
    if (USE_MAGIC()) return SIMMAGIC_UNCACHED;
    else             return SIMMAGIC_DIRECT;

  case MAGIC_ZONE_PPC:
  case MAGIC_ZONE_PPC_ALIAS:
     /* Until flashlite implements these PPCs, we'll use simmagic */
     if (VA_GRP(VA) == MAGIC_PPC_GROUP_KERNEL) {
        switch (VA_OPC(VA)) {
        case MAGIC_PPC_OP_CELLNODECONFIG:
        case MAGIC_PPC_OP_NODEADDRCONFIG:
        case MAGIC_PPC_OP_STARTSLAVENODE:
           return SIMMAGIC_DIRECT;
        }
     }

    if (USE_MAGIC()) return SIMMAGIC_UNCACHED_ACCELERATED;
    else             return SIMMAGIC_DIRECT;

  case MAGIC_ZONE_DMAMAP:
  case MAGIC_ZONE_SWTLB:
  case MAGIC_ZONE_MISSCNT:
    ASSERT(0);
    return SIMMAGIC_DIRECT;

  case MAGIC_ZONE_NODEMAP:
    if (USE_MAGIC()) return SIMMAGIC_UNCACHED;
    else             ASSERT(0);
    return SIMMAGIC_DIRECT;

  case MAGIC_ZONE_NODECOMM:
    if (USE_MAGIC()) return SIMMAGIC_UNCACHED;
    else             ASSERT(0);
    return SIMMAGIC_DIRECT;

  case MAGIC_ZONE_BDOOR_DEV:
#if (DEBUG_MAGIC == 1)
     CPUPrint("PIO 0x%x\n", VA);
#endif
    return SIMMAGIC_UNCACHED;

  default: break; /* keep compiler happy */
  }
  ASSERT(0);
  return SIMMAGIC_DIRECT;
}


/****************************************************************************
 *
 * Checkpointing support.
 *
 ****************************************************************************/

static int
SimMagic_CheckpointCB(CptDescriptor *cptd)
{
  uint version;
  int  nmagics;
  int  cpu;

  if (cptVersion.ver == 3) {
     /* XXX NOTE: the following not only _looks_ bogus, it actually _is_.
      * It's this way for compatibility reasons only.
      */
     Simcpt_OptionalUint(cptd, "version", NO_INDEX, NO_INDEX, 0);
     
     version = 3;
     Simcpt_CptUint(cptd, "version", NO_INDEX, NO_INDEX, &version);
     ASSERT(version == 3);
  }
  nmagics = TOTAL_CPUS;
  Simcpt_CptInt(cptd, "numMagics", NO_INDEX, NO_INDEX, &nmagics);
  ASSERT(nmagics == TOTAL_CPUS);

  /* XXX whoops... Now checkpointing some SIPS state!
   * This call is placed here for compatibility with older SimOS version.
   */
  sim_sips_cpt_from_magic(cptd);
  return 0;
}


static int
MPCheckpointCB(CptDescriptor *cptd)
{
  int cpu, j;
  unsigned char c;

  Simcpt_OptionalInt(cptd, "UseR3kLocks", NO_INDEX, NO_INDEX, 0);

  for (cpu = 0; cpu < TOTAL_CPUS; cpu++) {

    Simcpt_OptionalHex(cptd, "R3k.lockCAShackAddr", cpu, NO_INDEX, 0); 
    Simcpt_OptionalHex(cptd, "SpinLockStartAddr", cpu, NO_INDEX, 0);
    Simcpt_OptionalHex(cptd, "SpinLockEndAddr", cpu, NO_INDEX, 0);

    Simcpt_CptULL(cptd, "iPendingReg", cpu, NO_INDEX, &mm[cpu].iPendingReg);
    if (cptd->mode == CPT_RESTORE) {
      /* compatibility with older checkpoints */
      mm[cpu].iTransReg = mm[cpu].iPendingReg;
    }
    Simcpt_OptionalULL(cptd, "iTransReg", cpu, NO_INDEX, &mm[cpu].iTransReg);
    Simcpt_CptULL(cptd, "iEnableMask", cpu, NO_INDEX, &mm[cpu].iEnableMask);
    for (j = 0; j < 64; j++)
      Simcpt_CptUchar(cptd, "iBitTable", cpu, j, &mm[cpu].iBitTable[j]);

    c = (unsigned char) mm[cpu].IEChigh;
    Simcpt_CptUchar(cptd, "IEChigh", cpu, NO_INDEX, &c);
    mm[cpu].IEChigh = (MagicRegister) c;

    Simcpt_CptInt(cptd, "intrBits", cpu, NO_INDEX, &CPUVec.intrBits[cpu]);

    for (j = 0; j < SIM_MAXSLOTS; j++) {
      int s;
      Simcpt_CptUchar(cptd, "ioSlotMap", cpu, j, &mm[cpu].ioSlotMap[j]);
      s = mm[cpu].ioSlots[j]; /* fudge for compatibility */
      Simcpt_CptInt(cptd, "ioSlots", cpu, j, &s);
      mm[cpu].ioSlots[j] = s;
    }
  }
  return 0;
}


void
sim_magic_cpt(int restoreFromChkpt)
{
  Simcpt_Register("mp", MPCheckpointCB, ALL_CPUS);
  if(restoreFromChkpt) Simcpt_Restore("mp");
}

/* NOTE:  for flashlite, cpuNum is the destination node,
   not the node originating the PIO */
Result
SimMagic_DoPIO(int cpuNum, PA addr, int isRead, int size, void *data)
{
   void *func;
   uint type, flag;
   VA vAddr    = (VA)(Reg32_s)addr; /* Sign extend if needed */
   int inRange = RegistryIsInRange(vAddr, &func, &flag);
   
   if (!inRange) {
      CPUError("PIO out of range pc=0x%llx vAddr=0x%llx \n",
               (uint64) CPUVec.CurrentPC(cpuNum), (uint64)vAddr);
   }
   
   ASSERT(flag & REG_FUNC);
   
   switch (size) {
   case sizeof(char):
      type = isRead ? BDOOR_LOAD_BYTE : BDOOR_STORE_BYTE;
      break;

   case sizeof(int):
      type = isRead ? BDOOR_LOAD_WORD : BDOOR_STORE_WORD;
      break;

   case sizeof(long long):
      type = isRead ? BDOOR_LOAD_DOUBLE : BDOOR_STORE_DOUBLE;
      break;

   default:
      CPUError("Bad PIO access size %x\n", size);
      type = 0;
   }
   return (Result)((MagicFunction)func)(cpuNum, vAddr, type, data);
}

int
SimMagic_IsIncoherent(uint pAddr)
{
   int pgNum = pAddr / SIM_PAGE_SIZE;
   int byteIndex = pgNum / sizeof(char);
   int bitIndex = pgNum % sizeof(char);

   if (inCellMode) {
      ASSERT(IS_VALID_PA(0, pAddr));
      return (sim_misc.incoherentPages[byteIndex] >> bitIndex) & 1;
   } else
      return 0;
}

void
SimMagic_MakeIncoherent(uint pAddr)
{
   int pgNum = pAddr / SIM_PAGE_SIZE;
   int byteIndex = pgNum / sizeof(char);
   int bitIndex = pgNum % sizeof(char);

   if (inCellMode) {
      ASSERT(IS_VALID_PA(0, pAddr));
      sim_misc.incoherentPages[byteIndex] |= 1 << bitIndex;
   }
}

void
SimMagic_InsertOspcHiQueue(int cpunum, char *data)
{
   SipsErr result;
   /* For now this function only handles SIPS */
   ASSERT(*(uint64*)data == (uint64)MAGIC_OSPC_HI_SIPSREPLY);
   *(uint64*)data = cpunum;
   /* Best guess at sender, for purposes of debugging messages.
      In the current format the sender is the first 2 bytes of
      the second doubleword. */
   result = sim_sips_send((((uint64*)data)[1] & 0xFFFF000000000000LL) >> 48,
                          0, data, 1);
   ASSERT(result == SIPS_OK);
}

void
SimMagic_InsertOspcLoQueue(int cpunum, char *data)
{
   SipsErr result;
   /* For now this function only handles SIPS */
   ASSERT(*(uint64*)data == (uint64)MAGIC_OSPC_LO_SIPSREQ);
   *(uint64*)data = cpunum;
   /* Best guess at sender, for purposes of debugging messages.
      In the current format the sender is the first 2 bytes of
      the second doubleword. */
   result = sim_sips_send((((uint64*)data)[1] & 0xFFFF000000000000LL) >> 48,
                          1, data, 1);
   ASSERT(result == SIPS_OK);
}


unsigned char
SimMagic_GetIbitTableEntry(int cpunum, int entry)
{
  return mm[cpunum].iBitTable[entry];
}


uint64
SimMagic_GetIECPending(int cpunum)
{
  return (uint64) mm[cpunum].iPendingReg;
}

uint64
SimMagic_GetIECTrans(int cpunum)
{
  return (uint64) mm[cpunum].iTransReg;
}

uint64
SimMagic_GetIECEnable(int cpunum)
{
  return (uint64) mm[cpunum].iEnableMask;
}