r4k_cp0.c 62.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
/*
 * 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. 
 *
 */

/****************************************************************
 * r4k_cp0.c
 * 
 * TranslateVirtual manages the simulator's TLB and EXCEPTION allows 
 * normal exception handling.  The R4000 tlb consists of 48 entries,
 * VPN2 subblocking factor = 2, thus there are 
 * Two pages mapped to one VPN.  Lo0 is even, Lo1 is odd.  
 * All comments have been slightly revised with the most important 
 * changes noted by the R4000 CHANGED >> syntax.  
 *
 * $Author: blythe $
 * $Date: 2003/02/18 23:43:15 $
 *
 *****************************************************************/
#include <stdlib.h>
#include "mipsy.h"
#include "cpu.h"
#include "cpu_state.h"
#include "sim_error.h"
#include "cp0.h"
#include "simmisc.h"
#include "cpu_interface.h"
#include "hw_events.h"
#include "registry.h"
#include "machine_params.h"
#include "tcl_init.h"
#include "mips_arch.h"
#include "cpu_stats.h"
#include "trace.h"

#ifdef MIPSY_MXS
#include "ms.h"
#endif

/* NOTE: the following is included only because of OS_IEC_MAGICERR.
 *       This should be fixed!
 */
#include "simmagic.h"  /* to raise the interrupt line on r4k timing mech. */
#include "simmisc.h"   /* simlocks for raising i bits XXXXXX */ 


/* Local CP0 functions */
static void UTLB_EXCEPTION(CPUState *, int);
static void UpdateCPUMode(CPUState *P);
static Result DoTLBWrite(CPUState *P, int);
static void CompareWritten(CPUState *P);
static void CountWritten(CPUState *P);
static void ExceptionReturn(CPUState *P);
static void ProbeTLB(CPUState *P);
static void ReadTLBEntry(CPUState *P);
static Result WriteRandomTLBEntry(CPUState *P);
static Result WriteTLBEntry(CPUState *P);
static void WriteC0Register(CPUState *P, int c0RegNum, Reg value, int is64bit);


static Cp0RegControl cp0RegCtl[NUM_CP0_REGS] = CP0_REG_CONTROL_ARRAY;

/* Useful macros */

#if defined(SIM_MIPS32)
#define ANY_HIGH32_BITS(_vAddr) (0)
#define HAS_BAD_VADDR_BITS(_vAddr) (0)
#define REGION_COMPARE(_a,_b) (1)
#define IN_32BIT_MODE(_p) (1)
#define ONLY_4K_PAGE_SIZE   /* 32bit only needs 4K pages */
#define IS_R10000(P) 0
#else
#define ANY_HIGH32_BITS(_vAddr) ((_vAddr) >> 32)
#define _BAD_VADDR_MASK  (~(((0x1LL << VA_VALID_BITS)-1)|(0x3LL<<62)))
#define HAS_BAD_VADDR_BITS(_vAddr) ((_vAddr) & _BAD_VADDR_MASK)
#define REGION_COMPARE(_a,_b) ((_a) == (_b))
#define IN_32BIT_MODE(_p) ((_p)->is32bitMode)
/*
 * Is the R10000 TLB?
 */
#define IS_R10000(P) ((P)->numTlbEntries == 64)
#endif

#ifdef ONLY_4K_PAGE_SIZE
#define ComputeTlbEntrySize(_pgmask) (0)
#else
static unsigned char ComputeTlbEntrySize(uint pgMsk);
#endif

#if defined(SIM_MIPS32)
#define TLBHash(_vpn2,_region, _asid) TLBHash32BitOnly(_vpn2,_asid)

/*****************************************************************
 * Hash function for converting a virtual page number and ASID
 * into an entry in the hash table.  Hash function of R3000 ==
 * hash function of R4000.  Hash table stores chained TLB entry 
 * numbers at each bucket, thus decreasing translation time.
 * R4000 COMMENTS >> In all calls to this function, the vpn is 
 * actually vpn2. (you want both vpn's to map to the same index!)
 *****************************************************************/
static int 
TLBHash32BitOnly(register VPN vpn2, register ASID asid)
{
   return ((vpn2 ^ (vpn2 >> (NUM_VPN_BITS - LOG_TLB_HASH_SIZE)) 
            ^ (asid << (LOG_TLB_HASH_SIZE - NUM_ASID_BITS))) 
           % TLB_HASH_SIZE);
}

#else
#define TLBHash(_vpn2,_region, _asid) TLBHash64bit(_vpn2,_region, _asid)

/*****************************************************************
 * Hash function for converting a virtual page number and ASID
 * into an entry in the hash table.  
 * Hash table stores chained TLB entry 
 * numbers at each bucket, thus decreasing translation time.
 *****************************************************************/
static int 
TLBHash64bit(register VPN vpn2, register uint region, register ASID asid)
{
   return ((vpn2 ^ (vpn2 >> (NUM_VPN2_BITS - LOG_TLB_HASH_SIZE)) 
            ^ (vpn2 >> (32 - (NUM_OFFSET_BITS+1) - LOG_TLB_HASH_SIZE)) 
            ^ region
            ^ (asid << (LOG_TLB_HASH_SIZE - NUM_ASID_BITS))) 
           % TLB_HASH_SIZE);
}
#endif

/*****************************************************************
 * The TLB indices are stored in a hash table which maps an odd/even
 * pair of pages to an entry. 
 * R4000 COMMENTS >>  use IS_GLOBAL_HI, GET_VPN2.  In the future will
 * worry about the PageMask register.  Right now pages 4k.
 *****************************************************************/
void 
MipsyInitTLBHashTable(CPUState *P)
{
   int i;
   int hashNum;

   UpdateCPUMode(P);
   /* Set up the hash bucket list headers */
   for (i=0; i < TLB_HASH_SIZE; i++) {
      List_Init(&(P->tlbIndexHeaders[i]));
   }
   for (i=0; i < P->numTlbEntries; i++) {
      List_InitElement(&(P->indexList[i].links));
      P->indexList[i].index = i;
      P->indexList[i].onList = 0;
   }

   /* Reconstruct hash table information for when you want to 
    * directly jump into mipsy after accumulating some state. 
    * I am assuming that a completely blank TLB entry is what
    * it looks like at startup.
    */

   for (i=0; i < P->numTlbEntries; i++) {
      if (IS_UNMAPPED_TLBHI(P->tlbEntry[i].Hi)) {
         continue;
      }
      if(IS_GLOBAL_HI(P->tlbEntry[i].Hi)) {
         hashNum = TLBHash(GET_VPN2(P->tlbEntry[i].Hi), 
                           GET_REGION(P->tlbEntry[i].Hi), 0);
      } else {
         hashNum = TLBHash(GET_VPN2( P->tlbEntry[i].Hi),
                           GET_REGION(P->tlbEntry[i].Hi), 
                           GET_ASID( P->tlbEntry[i].Hi));
      } 
      List_Insert(&(P->indexList[i].links), 
                  LIST_ATFRONT(&(P->tlbIndexHeaders[hashNum])));
      P->indexList[i].onList = 1;
      P->tlbEntrySize[i] = ComputeTlbEntrySize(P->tlbEntry[i].PgMsk);
   }
   P->pcVPNcache = 0;
}


static struct {
   Reg  mask;
   uint loBit;
   uint offset_mask;
} PgSz[TLBPGMASK_NUMSIZES] = {
   { ~(TLBPGMASK_4K>>13), (1 << 12), 4*1024-1},
   { ~(TLBPGMASK_16K>>13), (1 << 14), 16*1024-1},
   { ~(TLBPGMASK_64K>>13), (1 << 16), 64*1024-1},
   { ~(TLBPGMASK_256K>>13), (1 << 18), 256*1024-1},
   { ~(TLBPGMASK_1M>>13), (1 << 20), 1024*1024-1},
   { ~(TLBPGMASK_4M>>13), (1 << 22), 4*1024*1024-1},
   { ~(TLBPGMASK_16M>>13), (1 << 24), 16*1024*1024-1},
};

#ifndef ONLY_4K_PAGE_SIZE
#define SZ2MASK(_s) PgSz[(_s)].mask
#define SIZES_TO_CHECK TLBPGMASK_NUMSIZES
#else
#define SZ2MASK(_s) -1
#define SIZES_TO_CHECK 1

#endif


#ifndef ONLY_4K_PAGE_SIZE
static unsigned char ComputeTlbEntrySize(uint pgMsk)
{

  unsigned char s;
  uint match = ~(pgMsk >> 13);

  ASSERT(SIZES_TO_CHECK < (1 << (sizeof(unsigned char)*8)));

  for (s = 0; s < SIZES_TO_CHECK; s++) { 
     if ((uint)SZ2MASK(s) == match) {
        return s;
     }
  }
  CPUError("Bad PgMsk 0x%x in ComputeTlbEntrySize\n", pgMsk);
  return (unsigned char) 0;
}
#endif
 
/*****************************************************************
 * Given a vpn and asid, this function returns the index+1 of 
 * the corresponding TLB. It returns 0 if the index is not found.  
 * First probe the hash table under the given asid then probe under 
 * asid 0 (to catch global entries ) 
 ******************************************************************/

unsigned 
TLBLookup(CPUState *P, uint region, VPN vAddrPFN2, ASID realASID)
{
  int hashNum;
  List_Links* indexPtr;
  register unsigned idx;
  register int s;

  for (s = 0; s < SIZES_TO_CHECK; s++) { 
     VPN vpn;
     VPN vpnLookup = vAddrPFN2 & SZ2MASK(s);
     /* Check for pages under this process's true asid */
     hashNum = TLBHash(vpnLookup, region, realASID);
  
     LIST_FORALL( &(P->tlbIndexHeaders[hashNum]), indexPtr) {

        idx = ((IndexListLink*)indexPtr)->index;
        vpn = vAddrPFN2 & SZ2MASK(P->tlbEntrySize[idx]);
        /* Don't check global bit because if the global bit is set, the 
         * entry is stored under ASID 0 */
        if ((vpn == GET_VPN2(P->tlbEntry[idx].Hi))
            && (realASID == GET_ASID(P->tlbEntry[idx].Hi))
            && REGION_COMPARE(region, GET_REGION(P->tlbEntry[idx].Hi))) {
           return idx+1;
        }
     }
  
     /* Now check for global pages, all of which are stored under asid 0 */
     hashNum = TLBHash(vpnLookup, region, 0);
     LIST_FORALL( &(P->tlbIndexHeaders[hashNum]), indexPtr) {
        idx = ((IndexListLink*)indexPtr)->index;
        vpn = vAddrPFN2 & SZ2MASK(P->tlbEntrySize[idx]);
        if ((vpn == GET_VPN2(P->tlbEntry[idx].Hi))
            && (IS_GLOBAL_HI(P->tlbEntry[idx].Hi))
            && REGION_COMPARE(region,GET_REGION(P->tlbEntry[idx].Hi))) {
           return idx+1;
        }
     }
  }
  return 0;
}


/*****************************************************************
 * Address translation on R4000.
 *
 * input: virtual address
 * pointer to phys addr
 * Fully associative search (using hash table)
 * 1.) User Mode or Supervisor Mode
 *     if MSB == 1 in user or MSB = 0 | 110 
 * 2.) VPN2 match?
 *     a.) if no VPN2 match and 32 bit-mode, -> TLB Refill.
 *     b.) VPN2 match, Not Global, No ASID match, -> TLB Refill.
 *     c.) VPN2 match, not Global and ASID match, OR Global, then if not valid
 *     -> TLB Invalid.
 *     d.) valid, not dirty, but writing -> TLB Mod.
 *     e.) valid, dirty, or not dirty and not writing, Non_Cacheable == T
 *     then -> Access Main Mem, else Access Cache.  Phys addr output.    
 *
 * Returns FAILURE if an exception occurred telling the CPU to try
 * this instruction again. tlbFlavor will be set to TLB_BDOOR if this 
 * is a backdoor reference and to TLB_UNCACHED if it is to be uncached. 
 * 
 * tlbFlavor is also used as input to this procedure in an attempt to
 * keep the argument list down. Coming in it will signal whether or not 
 * this address is an ifetch and if this is a write or a read. 
 *
 * RPB: The TLB_PREFETCH flavor is used to indicate that the translation
 * is being performed for a prefetch.  When a prefetch translation fails,
ii * no exception is taken -- we simply return failure and the prefetch is
 * dropped.
 *
 *****************************************************************/

Result 
TranslateVirtual(CPUState *P, VA vAddr, PA *pAddr, uint *tlbFlavor, void **bdoorAddr)
{
   uint       tlbIndex;
   ContextReg contextReg;
   XContextReg xcontextReg;
   int        myASID;
   bool       isIfetch, isPrefetch, writing;
   uint       region;
   Reg        lo_reg;
   Reg        tlbhi;
   Reg32      sr_reg;
   Reg        VPN2;

   /* Gather tlbFlavor information */
   isIfetch   = (bool) TLB_IS_IFETCH(*tlbFlavor);   
   isPrefetch = (bool) TLB_IS_PREFETCH(*tlbFlavor);
   writing    = (bool) TLB_IS_WRITE(*tlbFlavor);
   
   /* Setting this to 0 means that by this is not a backdoor reference */
   *tlbFlavor = 0;

   myASID = GET_ASID(P->CP0[C0_TLBHI]);   
   region = GET_REGION(vAddr);
   sr_reg = (Reg32)(P->CP0[C0_SR]);   

   /*
    * Handle the case of unmapped addresses and address errors. Although
    * we assume most address will hit in the TLB we still need to do 
    * illegal address detection because the TLB lookup doesn't catch them
    * call (i.e. bit 50 being set in user mode). 
    * We do the check by region starting with the user region.
    */

   if (region == 0) { 
      /* Make sure the address is with acceptable range. For the
       * 32 bit mode this means 32 bits, for 64bit mode this means
       * impelementation defined bits. 
       */
      if (IN_32BIT_MODE(P)) {
         if (ANY_HIGH32_BITS(vAddr)) goto addrErr;
      } else {
         if (HAS_BAD_VADDR_BITS(vAddr)) goto addrErr;
         if (IS_R10000(P) 
             && !(sr_reg & SR_UX) && ANY_HIGH32_BITS(vAddr)) 
            goto addrErr;
      }
      /* KUSEG becomes an uncached space when the ERL bit is set. This is 
       * needed for cache error handling. */
      if (sr_reg & SR_ERL) { 
         /* need to add k1base because registry works on kseg1 addresses */
         vAddr += K1BASE;
         goto bdoor;
      }
      /* Fall thru to TLB lookup */

   } else if (region == 3) {
      /* Kernel region, no user and limited supervisor */
      if (vAddr >= CKSEG0_START_ADDR) {
         if (!IS_KERNEL_MODE(P)) {
            /* No user and supervisor limited to single range */
            if (sr_reg & SR_KSU_USR) goto addrErr;
            if ((sr_reg & SR_KSU_SUP) && !IS_SUPERV_SEG(vAddr)) goto addrErr;
         }
         if (IS_KSEG0(vAddr)) {
            if (!IS_KERNEL_MODE(P)) goto addrErr; /* Kernel only */
#if 1
	    /*XXXblythe hook to be able to run uncached */
	    if ((P->CP0[C0_CONFIG]&0x7) == CBIT_UNCACHED) {
               /* switch to uncached space */
               vAddr |= K1BASE;
               goto bdoor;
	    }
#endif
            *pAddr = K0_TO_PHYS(vAddr); 
            /* XXX fix this */
            return SUCCESS;
         }
         if (IS_KSEG1(vAddr)) goto bdoor;
         /* Fall thru to TLB lookup */
      } else { 
         /* If we got here we better not be in 32bit mode and
          * there is nothing that the user or supvisor can access.
          */
         if (IN_32BIT_MODE(P) || !IS_KERNEL_MODE(P)) goto addrErr;
         if (vAddr > XKSEG_END_ADDR) goto addrErr;
      }
      /* Fall thru to TLB lookup */
#if defined(SIM_MIPS64)
   } else if (region == 2) {
      uint cache_algorithm = XKPHYS_CACHE_ALGORITHM(vAddr);
      /* xkphys - only available in kernel 64bit mode */
      if (IN_32BIT_MODE(P) || !IS_KERNEL_MODE(P)) goto addrErr;

      switch (cache_algorithm) {
      case CBIT_UPDATE:
         if (IS_R10000(P)) {
            break; /* fall thru to error, doesn't work on R10000 */
         }
      case CBIT_NONCOHERENT:
      case CBIT_EXCLUSIVE:
      case CBIT_EXCLUSIVE_WRITE:
      {
         Reg64 offset = XKPHYS_ONE_PAGE_OFFSET(vAddr);
         if (XKPHYS_INVALID_OFFSET(offset)) goto addrErr;
         *pAddr = offset;
         /* XXX - NEED TO ACCESS FLAVOR */
         return SUCCESS;
      }
      case CBIT_UNCACHED:
      case CBIT_UNCACHED_ACCEL:
      {
         uint flavor = XKPHYS_UNCACHED_FLAVOR(vAddr);
         Reg64 offset = XKPHYS_FOUR_PAGE_OFFSET(vAddr);

         if (XKPHYS_INVALID_OFFSET(offset)) goto addrErr;
         if (!IS_R10000(P) && (flavor != 0)) goto addrErr;
         *pAddr = offset;
         *tlbFlavor = TLB_UNCACHED;
         if (cache_algorithm == CBIT_UNCACHED_ACCEL) {
            *tlbFlavor |= TLB_ACCELERATED;
         }
         return SUCCESS;
      }
      default:
         /* invalid cache alogrithm fall thru to error */
         break;
      }
      goto addrErr;

   } else if (region == 1) {
      /* Supervisor region - only available in 64bit mode */
      if (IN_32BIT_MODE(P) || ((sr_reg & SR_KSU_USR) && !IS_KERNEL_MODE(P)) || 
          HAS_BAD_VADDR_BITS(vAddr)) goto addrErr;
      if (IS_R10000(P) && !(sr_reg & SR_SX)) goto addrErr;
      /* Fall thru to TLB lookup */
#endif
   }

    /* Check TLB */
    VPN2 = GET_VPN2(vAddr);
    tlbIndex = TLBLookup(P, region, VPN2, myASID);


    if (tlbIndex) {
      int szEntry; 
      /* We have a matching VPN and ASID - see if it is valid */
      tlbIndex--;
      szEntry = P->tlbEntrySize[tlbIndex];
      /* Which lo register? */
      if (vAddr & PgSz[szEntry].loBit)
         lo_reg = P->tlbEntry[tlbIndex].Lo1;
      else
         lo_reg = P->tlbEntry[tlbIndex].Lo0;
      

      if (IS_VALID(lo_reg)) {
         /* Check if the page is dirty or we are reading */
         if ( IS_DIRTY(lo_reg) || !(writing)) {
            /* Everything is cool - form the address */
#ifdef notdef  /* For performance, disable this check by default */
            int cache_algorithm = GET_CACHE_ALGOR(lo_reg);
            
            if (!((cache_algorithm == CBIT_EXCLUSIVE) || 
                  (cache_algorithm == CBIT_EXCLUSIVE_WRITE))) {
               CPUWarning("Unsupported TLB cache algorithm (%d) for address 0x%llx by cpu %d at PC 0x%llx\n",
                          cache_algorithm,  (uint64)vAddr, P->myNum, (uint64)P->PC);

            }
#endif
            
            /* 
             * XXX TO_DO non-cacheable support eventualy support table 
             * which has 8 modes.
             * if (!IS_CACHEABLE(lo_reg){
             *  *tlbFlavor = TLB_UNCACHED;
             * }
             */
if (!IS_CACHEABLE(lo_reg)) {
*tlbFlavor = TLB_UNCACHED;
#if 0
fprintf(stderr, "uncached\r\n");
#endif
}
            *pAddr = (((GET_PFN(lo_reg)&SZ2MASK(szEntry))*4*1024) | 
                      (vAddr & PgSz[szEntry].offset_mask));
            
            return SUCCESS;
         } else { 
            
            /* TLB MODIFICATION */
            /* Page is not dirty and we want to write */
            /* Set up the CTxt register !!! */
            /* EPC set up in EXCEPTION, badVaddr and context */
            /* stored in macro */
            
            if (isPrefetch) return FAILURE;
            

            contextReg.tc_data = P->CP0[C0_CTXT];
            contextReg.s32.tc_badvpn = VPN2;
            
            xcontextReg.tc_data = P->CP0[C0_XCTXT];
            xcontextReg.s64.tc_region = region;
#ifndef BIG_BIT_FIELD_BROKEN
            xcontextReg.s64.tc_badvpn = VPN2;
#else
            xcontextReg.s64.tc_badvpn_hi3 = VPN2>>28;
            xcontextReg.s64.tc_badvpn_lo28 = VPN2;
#endif
            tlbhi = (((Reg)region << TLBHI_REGIONSHIFT) | 
                     (VPN2 << TLBHI_VPN2SHIFT)  | 
                     ((Reg)myASID << TLBHI_PIDSHIFT)) ;

            RECORD_EXCEPTION(P, EXC_MOD, E_VEC, vAddr, 
                             tlbhi,contextReg.tc_data,
                             xcontextReg.tc_data);
            return FAILURE;
         }
      } else { 
  /* TLB INVALID */
         if (isPrefetch) return FAILURE;

         contextReg.tc_data = P->CP0[C0_CTXT];
         contextReg.s32.tc_badvpn = VPN2;
         
         xcontextReg.tc_data = P->CP0[C0_XCTXT];
         xcontextReg.s64.tc_region = region;
#ifndef BIG_BIT_FIELD_BROKEN
         xcontextReg.s64.tc_badvpn = VPN2;
#else
         xcontextReg.s64.tc_badvpn_hi3 = VPN2>>28;
         xcontextReg.s64.tc_badvpn_lo28 = VPN2;
#endif

         
         tlbhi = (((Reg)region << TLBHI_REGIONSHIFT) | 
                  (VPN2 << TLBHI_VPN2SHIFT)  | 
                  ((Reg)myASID << TLBHI_PIDSHIFT)) ;
         
         RECORD_EXCEPTION(P, (writing ? EXC_WMISS : EXC_RMISS),E_VEC,
                          vAddr,tlbhi,contextReg.tc_data,
                          xcontextReg.tc_data);
         return FAILURE;
      }
    }



    /* TLB REFILL 
     * Since there were no matching VPN2s, there is a TLB refill exception.
     * First put the VPN2 and ASID of the non-matching address in Hi.
     * The BadVAddr and Context registers also need to be set.
         * 1.) set TLBL or TLBS(store only) code in cause register
     * use EPC and BD bit in cause reg, inst or load, or store.
     * 2.) BadVAddr, Context, XContect and EntryHi hold the vAddr
     * that failed. Entry HI also has ASID. EPC pts to last instruction
     * take care of branches.
     */

    if (isPrefetch) return FAILURE;


    contextReg.tc_data = P->CP0[C0_CTXT];
    contextReg.s32.tc_badvpn = VPN2;



    xcontextReg.tc_data = P->CP0[C0_XCTXT];
    xcontextReg.s64.tc_region = region;
#ifndef BIG_BIT_FIELD_BROKEN
    xcontextReg.s64.tc_badvpn = VPN2;
#else
    xcontextReg.s64.tc_badvpn_hi3 = VPN2>>28;
    xcontextReg.s64.tc_badvpn_lo28 = VPN2;
#endif

     tlbhi = (((Reg)region << TLBHI_REGIONSHIFT) | 
                     (VPN2 << TLBHI_VPN2SHIFT)  | 
                     ((Reg)myASID << TLBHI_PIDSHIFT)) ;

    if (isIfetch) { 
       ITLB_MISS_EVENT(MipsyReadTime(P->myNum), P->myNum, vAddr);
    } else { 
       DTLB_MISS_EVENT(MipsyReadTime(P->myNum), P->myNum, P->PC, vAddr);
    }

    if (sr_reg & SR_EXL) { 
       RECORD_EXCEPTION(P, (writing ? EXC_WMISS : EXC_RMISS),E_VEC,vAddr,
                        tlbhi,contextReg.tc_data,
                              xcontextReg.tc_data);
    } else {    
       if (((region == 0) && (sr_reg & SR_UX)) ||
           ((region == 3) && (sr_reg & SR_KX)) ||
           ((region == 1) && (sr_reg & SR_SX))) {
          /* Should pass XUT_VEC to RECORD below, but this isn't 
             currently used. */
       }
       RECORD_UTLBEXCEPTION(P, writing ? EXC_WMISS : EXC_RMISS, 
                            UT_VEC, vAddr, tlbhi, contextReg.tc_data, 
                            xcontextReg.tc_data);
    }
    
    return FAILURE;
    
addrErr:
    if (isPrefetch) return FAILURE;
    /* Illegal address - generate an address error */
    
    RECORD_EXCEPTION(P, (writing ? EXC_WADE : EXC_RADE), E_VEC,
                     vAddr,P->CP0[C0_TLBHI], P->CP0[C0_CTXT], P->CP0[C0_XCTXT]);
    return FAILURE;
    
bdoor:
    {
      SimMagic_accesstype a;
      
      if (!IS_KERNEL_MODE(P)) {
         CPUWarning("Accessing bdoor while not in kernel mode (PC %#x RA %#x)\n",
                    P->PC, P->R[REG_RA]);
      }
      
      a = SimMagic_kseg1_accesstype(vAddr);
      
      if (a == SIMMAGIC_UNCACHED) {
         *tlbFlavor = TLB_UNCACHED;
         *pAddr = vAddr;
      } else if (a == SIMMAGIC_UNCACHED_ACCELERATED) {
         *tlbFlavor = TLB_UNCACHED|TLB_ACCELERATED;
         *pAddr = vAddr;
      } else {
         uint flag;

         /* a == SIMMAGIC_DIRECT */
         
         if (!RegistryIsInRange(vAddr, bdoorAddr, &flag)) {
            /* Raise an address error on a bad backdoor address. */
            if (!isPrefetch) {
               CPUWarning("MIPSY: Bad bdoor reference to 0x%x from %#x RA %#x\n", 
                          vAddr, P->PC, P->R[31]);
               /* ASSERT(0); */
               RECORD_EXCEPTION(P, (writing ? EXC_WADE : EXC_RADE), E_VEC,
                                vAddr, P->CP0[C0_TLBHI], P->CP0[C0_CTXT],
                                P->CP0[C0_CTXT]);
            }
            return FAILURE;
         }

         if (flag & REG_DATA) {
            *tlbFlavor = TLB_BDOOR_DATA;
         } else {
            ASSERT(flag & REG_FUNC);
            *tlbFlavor = TLB_BDOOR_FUNC;
         }
          
         SIM_DEBUG(('b', "MIPSY: CPU %d Translated %#x to %#x (%s) at pc %#x\n", 
                    P->myNum, vAddr, pAddr, (flag & REG_DATA)?"data":"func", P->PC));
      }
    }
    
   return  SUCCESS;
}


/* a version of TranslateVirtual intended to be called from the debugger.
 */

Result 
TranslateVirtualNoSideeffect(CPUState *P, VA vAddr, PA *pAddr)
{
   unsigned       tlbIndex;
   int            myASID;
   Reg64          lo_reg;
   int             region = GET_REGION(vAddr);

   if (region==2) {
      *pAddr = XKPHYS_FOUR_PAGE_OFFSET(vAddr);
      return SUCCESS;
   }
   if (region==3 && vAddr >= CKSEG0_START_ADDR) { 
      if (IS_KSEG0(vAddr)) {
         *pAddr = K0_TO_PHYS(vAddr); 
         return SUCCESS;
      }
   }

   /* fall through and cover 32-bit cases. */

   


   if (!IS_KUSEG(vAddr)) {
      if (IS_KSEG1(vAddr)) { 
#ifdef __alpha
         return FAILURE;
#else 
         void *dat;
         uint flag;
         *pAddr = (PA)RegistryGetSimFunction(vAddr);
         if (*pAddr) {
            SIM_DEBUG(('b', "BDOOR: CPU %d found func %#x at 0x%x (PC %#x RA %#x\n", 
                  P->myNum, *pAddr, vAddr, P->PC, P->R[REG_RA]));
            return SUCCESS;
         }
         /* backdoor access */
#if 0
         if (!RegistryIsInRange(vAddr,&dat, &flag) ||
             !(flag & REG_DATA)) {
            /* Raise an address error on a bad backdoor address. */
            return FAILURE;
         }
         *pAddr = (PA) dat;
#else
         if (!RegistryIsInRange(vAddr,&dat, &flag)) {
            return FAILURE;
         }
	 /* if a function, return the vAddr and resolve later */
	 if (!(flag & REG_DATA)) {
           *pAddr = (PA) vAddr;
	 } else {
           *pAddr = (PA) dat;
	 }
#endif
         return SUCCESS;
#endif /* __alpha */
      } else if (IS_KSEG0(vAddr)) {
         *pAddr = K0_TO_PHYS(vAddr);
         return SUCCESS;
      }
      /* KSEG2 references will fall through and be translated normally */
   }
   
   /* Check TLB */
   myASID = GET_ASID(P->CP0[C0_TLBHI]);   
   tlbIndex = TLBLookup(P, region, GET_VPN2(vAddr) , myASID);
   
   if (tlbIndex) {
      int sz;
      /* We have a matching VPN and ASID - see if it is valid */
      tlbIndex--;
      sz = P->tlbEntrySize[tlbIndex];
      /* Which lo register? */
      if (vAddr & PgSz[sz].loBit)
         lo_reg = P->tlbEntry[tlbIndex].Lo1;
      else
         lo_reg = P->tlbEntry[tlbIndex].Lo0;
      
      if (IS_VALID(lo_reg)) {
         *pAddr =  (((GET_PFN(lo_reg)&SZ2MASK(sz))*4*1024) | 
                    (vAddr & PgSz[sz].offset_mask));
         return SUCCESS;
      }
      /* fall through to failure case if not valid */
   }

   /* OK, let's resort to calling tcl for help */
   *pAddr = TclTranslateVirtual(P->myNum, vAddr);
   if (*pAddr) {
      return SUCCESS;
   }

   return FAILURE;
}

  
/*****************************************************************
 * ProbeTLB -
 * Probe TLB for a matching entry. The Index register is loaded 
 * with the address of the TLB entry whose contents match the 
 * contents of the Hi register. If no TLB entry matches, the 
 * high order bit of the Index register is set. 
 * 
 * What to do when there are multiple matches was not specified,
 * so I'm leaving after the first match.
 * R4000 CHANGED >> No changes.
 *****************************************************************/
static void
ProbeTLB(CPUState *P)
{
   int idx;

   idx = TLBLookup(P,  GET_REGION(P->CP0[C0_TLBHI]), 
                   GET_VPN2(P->CP0[C0_TLBHI]), 
                   GET_ASID(P->CP0[C0_TLBHI]));
   if (idx) {
      /* We matched */
      P->CP0[C0_INX] = (idx - 1) << TLBINX_INXSHIFT;
      return;
   }
   
   /* Probe Miss */
   P->CP0[C0_INX] = 0x80000000;
   return;
}

/*****************************************************************
 * ReadTLBEntry -
 * The Hi, Lo0, and Lo1 registers are loaded with the contents 
 * of the TLB entry pointed at by the contents of the TLB Index
 * register. The results are unspecified if the contents or Index
 * are greater than the number of TLB entries.
 * R4000 CHANGED >> G(global) bit from TLB is written into both the lo0 and lo1
 * registers. Entry HI and EntryLo registers are loaded with contents
 * of the TLB entry pointedt at by the index register. As is the 
 * PgMsk register.  if index > numtlbentries, undefined behavior.  
 *****************************************************************/
static void 
ReadTLBEntry(CPUState *P)
{
   IndexReg index;

   /* I'm going to assume that the index register is in the 
      correct range. */
   
   index = P->CP0[C0_INX];
   P->CP0[C0_PGMASK] = P->tlbEntry[GET_IDX(index)].PgMsk;
   P->CP0[C0_TLBHI] = P->tlbEntry[GET_IDX(index)].Hi & 
                      ~P->tlbEntry[GET_IDX(index)].PgMsk & ~TLBHI_G;
   P->CP0[C0_TLBLO_0] = P->tlbEntry[GET_IDX(index)].Lo0;
   P->CP0[C0_TLBLO_1] = P->tlbEntry[GET_IDX(index)].Lo1;

   if (IS_GLOBAL_HI(P->tlbEntry[GET_IDX(index)].Hi)){
      P->CP0[C0_TLBLO_0] |= TLBLO_G; 
      P->CP0[C0_TLBLO_1] |= TLBLO_G;
   } else {
      P->CP0[C0_TLBLO_0] &= ~TLBLO_G;
      P->CP0[C0_TLBLO_1] &= ~TLBLO_G;
   }
   
   /* Reading into TLBHI could change the ASID */
   P->pcVPNcache = 0; 
   TraceCheckASID(P);
   return;
}


/*****************************************************************
 * Do_TLB_Write
 * Write the indexed TLB entry. The TLB entry pointed at by the 
 * contents of the TLB index register is loaded with the contents
 * of the Hi, Lo0, Lo1, and PgMsk registers.  Since both Lo0 and Lo1
 * are written, the C0_TLBLO_1 and _0 must be in a consistent 
 * state before this instruction is called.
 *
 * R4000 CHANGES >> G bit of tlbhi written as AND of G bits
 * in EntryLo0 and EntryLo1.
 *****************************************************************/
static Result 
DoTLBWrite(CPUState *P, int idx)
{
   int hashNum;
   Reg frameMask;

   /* remove old entry from hash table */
   if( P->indexList[idx].onList ) {
      List_Remove( &(P->indexList[idx].links));
      P->indexList[idx].onList = 0;
    }

   /* if we are doing an indexed write into a segment which should not
    * be using the TLB we do NOTHING, and issue a mipsyswarning
    * that this has been called. 
    */
   if (IS_R10000(P)) { 
      frameMask = (P->CP0[C0_FRAMEMASK] << TLBFRAMESHIFT);
   } else {
      frameMask = 0;
   }
   P->tlbEntry[idx].PgMsk = P->CP0[C0_PGMASK];
   P->tlbEntry[idx].Hi = P->CP0[C0_TLBHI] & ~P->CP0[C0_PGMASK];
   P->tlbEntry[idx].Lo0 = (P->CP0[C0_TLBLO_0] & ~TLBLO_G) & ~frameMask;
   P->tlbEntry[idx].Lo1 = (P->CP0[C0_TLBLO_1] & ~TLBLO_G) & ~frameMask;
   P->tlbEntrySize[idx] = ComputeTlbEntrySize(P->tlbEntry[idx].PgMsk);

   if (IS_GLOBAL_LO(P->CP0[C0_TLBLO_0]) 
 && IS_GLOBAL_LO(P->CP0[C0_TLBLO_1])) {
         P->tlbEntry[idx].Hi |= TLBHI_G; 
    }
   
   /* To check which segment it is, I retrieve the VPN2 and shift up 
    * by 1 to get the original vpn.  Since all VPN2's are floored, and 
    * segs are on even boundaries, this should work. Then this number up
    * to account for the page offset so that the MIPSY_IS_KSEG0 test will
    * work.  This will change when PageMask register is used. 
    */

   if (!IS_UNMAPPED_TLBHI(P->tlbEntry[idx].Hi)) { 
      /* update hash table Insert all global entries under ASID 0 */
      if (IS_GLOBAL_HI( P->tlbEntry[idx].Hi)) {
         hashNum = TLBHash(GET_VPN2(P->tlbEntry[idx].Hi), 
                           GET_REGION(P->tlbEntry[idx].Hi), 0);
      } else {
         hashNum = TLBHash(GET_VPN2(P->tlbEntry[idx].Hi),
                           GET_REGION(P->tlbEntry[idx].Hi),
                           GET_ASID(P->tlbEntry[idx].Hi));
         if(GET_ASID(P->tlbEntry[idx].Hi) == 0) {
            if (!((P->tlbEntry[idx].Hi == 0) && 
                 !(TLBLO_V & P->tlbEntry[idx].Lo0) && 
                  !(TLBLO_V & P->tlbEntry[idx].Lo1))) { 
               /* IRIX 6.2 seems to like to slam all zeros into
                * the TLB. Don't print a message if this happens.
                */
#ifndef TORNADO
/* common operation in Tornado; should be nothing wrong with it */
  CPUWarning("Non-global ASID 0 entry written to TLB @%#llx RA %#llx\n",
      P->PC, P->R[31]);
#else
#endif /* TORNADO */
            }
         }
      }
      
      List_Insert(&(P->indexList[idx].links), 
                  LIST_ATFRONT(&(P->tlbIndexHeaders[hashNum])));
      P->indexList[idx].onList = 1;
      
      if (!IS_CACHEABLE(P->tlbEntry[idx].Lo0) ||
          !IS_CACHEABLE(P->tlbEntry[idx].Lo1)) {
         CPUWarning("Entering uncached TLB Entry at PC %#x\n", P->PC);
      } 
      
      
   } /* END IF KSEG0 || KSEG1 */
   
   
   P->pcVPNcache = 0; 
   TraceCheckASID(P);
   return SUCCESS;
}


/*****************************************************************
 * WriteTLBEntry -
 * Write the indexed TLB entry. The TLB entry pointed at by the 
 * contents of the TLB index register is loaded with the contents
 * of the Hi and Lo registers.
 *****************************************************************/
static Result
WriteTLBEntry(CPUState *P)
{
   IndexReg index;
   
   /* I'm going to assume that the index register is in the 
      correct range. */
   index = P->CP0[C0_INX];
   return DoTLBWrite(P, GET_IDX(index));
}

/*****************************************************************
 * WriteRandomTLBEntry -
 * Write random TLB entry. The TLB entry pointed at by the contents  
 * of the TLB Random register is loaded with the contents of Hi
 * and Lo.
 *
 * Technically, the value of the Random register is decremented on
 * each machine clock cycle and ranges between NWIREDENTRIES
 * and NTLBENTRIES. To save time, I'll just read the clock.
 * TO_DO NUMWIREDENTRIES should be based on the register. it 
 * is, I keep the randomReg unimplemented and hueristically done as before.
 * 
 * R4000 CHANGES >> No changes.
 *****************************************************************/
#ifdef DETERMINISTIC_TLB
int currentRandom = 0;
#endif
static Result
WriteRandomTLBEntry(CPUState *P)
{
   unsigned randomReg;

   unsigned numRandEntries = P->numTlbEntries - P->CP0[C0_TLBWIRED];
#ifdef DETERMINISTIC_TLB
   randomReg = (currentRandom++ % numRandEntries);
#else
   randomReg = (MipsyReadTime(P->myNum) % numRandEntries);
#endif
   return DoTLBWrite(P, randomReg + P->CP0[C0_TLBWIRED]);
}


/*****************************************************************
 * EXCEPTION - 
 * This is sort of a major routine. When an exception is raised, 
 * execution is suspended and the processor enters kernel mode. 
 * The CPU should abort the instruction that caused the exception
 * along with any others in the pipeline.
 * 
 * The CPU loads the Exception Program Counter (EPC) with a 
 * restart location - either the instruction, or it's predecessor
 * if it's in the branch delay slot. I check if it's in a branch
 * delay slot by seeing if the difference between PC and nPC is
 * greater than one instruction. 
 *
 * R4000 STATUS REGISTER UPDATE 
 * 1.)  The handler needs to know the mode(user or supervisor)
 * so only do not change mode.
 * 2.)  disable interrupts
 * 3.)  Are we inside another Exception, if EXL == 1 we are,
 * and do not set PC or nPC.
 * 4.)  on start cpu loads EPC with restart location...
 * 5.)  check BEV bit and goto vector.
 *  
 * The current kernel/user mode and interrupt enable status is NOT saved. 
 * Currently does not set ce bit in status register.  
 ****************************************************************/

static bool isREFILLException = FALSE; 

void 
EXCEPTION(CPUState *P, int code)
{
   
   StatusReg statusReg;
   CauseReg causeReg;
   uint prettyCode = code >> CAUSE_EXCSHIFT;
   VA exceptionBase;

   TraceException(P, code);

   SIM_DEBUG_DETAIL(('i', "INTR", P->myNum, 
                    "EXC code: 0x%x)\tintrbits: 0x%x\tPC: 0x%llx, RA: 0x%llx bad=0x%llx\n",
                    code, P->intrBitsPtr[0], (uint64)P->PC,
                     (uint64) P->R[31],(uint64)P->CP0[C0_BADVADDR]));

   statusReg.ts_data = P->CP0[C0_SR];

   /* no exceptions when ERL is asserted */
   if (statusReg.s32.ts_erl)
      return;


   /* Clear any cached instruction in case this exception is terminating
    * a miss stall
    */
   P->stalledInst = 0;
   
   /* Set the BD bit, CE, IP, and ExcCode fields of the Cause
    * register. Along with the BD bit, set the Exception Program
    * Counter (either to current PC or PC - 4 if BD slot).
    */
   
   causeReg.tc_data = P->CP0[C0_CAUSE];
   causeReg.s32.tc_exccode = code >> CAUSE_EXCSHIFT;
   
   /* The code comes in already shifted to the left 2 bits */
   if ((code == EXC_RMISS) || (code == EXC_WMISS)) {
      STATS_INC(P->myNum, numFaults, 1);
   }
   
   if (code == EXC_INT) {
      STATS_INC(P->myNum, numInterrupts, 1);
   }
   
   STATS_INC(P->myNum, causeCount[prettyCode], 1);
   /* EPC must point to the preceeding branch or delay instruction */ 

   if (P->branchStatus == BranchStatus_bd)  { 
      /* The inst causing the exception is in a BD slot */
      causeReg.s32.tc_bd = TRUE;
      if (statusReg.s32.ts_exl == 0){
 P->CP0[C0_EPC] = P->PC-INST_SIZE;
 statusReg.s32.ts_exl = 1;
      }
   } else {
      causeReg.s32.tc_bd = FALSE;
      if (statusReg.s32.ts_exl == 0){
         P->CP0[C0_EPC] = P->PC;
         statusReg.s32.ts_exl = 1;
      }
   }
   
   P->CP0[C0_SR] = statusReg.ts_data;
   P->CP0[C0_CAUSE] = causeReg.tc_data;

   UpdateCPUMode(P);

   EXC_STALL_EVENT(P->myNum, P->PC, 1);

   exceptionBase = (statusReg.s32.ts_bev == 0) ? EXC_VEC_BASE_0 :
                                               EXC_VEC_BASE_1;

   if (isREFILLException){
#if defined(SIM_MIPS64)
      Reg32     sr_reg =  statusReg.ts_data;
      int region;
      XContextReg xctxt;
      xctxt.tc_data =  P->CP0[C0_XCTXT];
      region = xctxt.s64.tc_region;
      if (((region == 0) && (sr_reg & SR_UX)) ||
          ((region == 3) && (sr_reg & SR_KX)) ||
          ((region == 1) && (sr_reg & SR_SX))) {
         P->PC  = exceptionBase + XUT_VEC_OFFSET;
         P->nPC = exceptionBase + XUT_VEC_OFFSET + 4;
      } else { 
#else
      {
#endif
         P->PC  = exceptionBase;
         P->nPC = exceptionBase+4;
      }
   } else {
      P->PC = exceptionBase + E_VEC_OFFSET;
      P->nPC = exceptionBase + E_VEC_OFFSET + 4;
   }

   if (isREFILLException) {
      UTLB_EVENT();
   } else {
      EXC_EVENT(prettyCode);
   }
}


/*****************************************************************
 * UTLB_EXCEPTION 
 * 
 * R4000 MIPS uses 1 special vector for any
 * TLB refill exception.
 * note:: this used to be called utlb_exception.  
 ****************************************************************/
static void 
UTLB_EXCEPTION(CPUState *P, int code)
{

   /* This will be counted here and in the EXC_WMISS and */
   /* EXC_RMISS. Subtract out if needed. */
   STATS_INC(P->myNum, utlbCount[code >> CAUSE_EXCSHIFT], 1);
   isREFILLException = TRUE;
   EXCEPTION(P, code); 
   isREFILLException = FALSE;
}


/* UNTOUCHED MXS */

#ifdef MIPSY_MXS
/*
 * PrintException - Print the specified exception - used for debugging.
 */
void 
PrintException(struct s_cpu_state *st, int exnum) 
{
   CPUState *P = (CPUState *) (st->mipsyPtr);
   if (exnum >= 0) 
      CPUPrint("MXS: CPU%d: EXC @ 0x%x cause 0x%x badvaddr 0x%x time %lld\n", 
               P->myNum,
               P->CP0[C0_EPC],
               P->exception[exnum].cause, 
               P->exception[exnum].badaddr, (uint64)MipsyReadTime(P->myNum));
   
}

/*
 * HandleException - Modify the register state of the machine
 *                   to reflect an exception happening.
 */
void 
HandleException(struct s_cpu_state *st, int exnum, int in_delay) 
{
   CPUState *P = (CPUState *) (st->mipsyPtr);
   StatusReg statusReg;

   statusReg.ts_data = P->CP0[C0_SR];
     
   CopyFromMXS (P);
   if (in_delay) {
      P->branchStatus = BranchStatus_bd;
   } else {
      P->branchStatus = BranchStatus_none;
   }
   if (exnum < 0) { 
      if (exnum == -1) {
         /* Coherency exception - Restart from point of exception */
         if (in_delay) {
           P->PC -= 4;
           P->nPC = P->PC+4;
         }
         CopyToMXS (P);  /* Resets the MXS instruction window */
         CPUPrint("MXS: Coherency exception at 0x%x time %lld\n", P->PC,
                  (uint64) MipsyReadTime(P->myNum));
      } else if (exnum == -2) {
         /* Switch back to mipsy */
         P->inMXS = 0;
         P->switchToMIPSY = 0;
         CopyToMXS(P);  /* This will cause MXS to be reset */
         CPUPrint("MXS: Switching to MIPSY on CPU%d at 0x%x time %lld\n",
                  P->myNum, P->PC, (uint64)MipsyReadTime(P->myNum));
      } else if (exnum == -3) {
         CPUPrint("MXS: About to ProcEXIT cpu %d at 0x%x time %lld\n",
                  P->myNum, P->PC, (uint64)MipsyReadTime(P->myNum));
         /* MakeProcessExit(P->myNum); */ 
         CPUError("MakeProcessExit doesn't work\n");
         CopyToMXS(P);  /* This will cause MXS to be reset */
      } else if (exnum == -4) {
         CPUPrint("MXS: About to EXIT cpu %d at 0x%x time %lld\n",
                  P->myNum, P->PC, (uint64)MipsyReadTime(P->myNum));
         CopyToMXS(P);  /* This will cause MXS to be reset */
         MipsyExit(BASE);
      }

      return;
   }

   P->CP0[C0_TLBHI] = P->exception[exnum].hireg;
   if (P->exception[exnum].cause == EXC_CPU)  {
      CauseReg  causeReg;
      causeReg.tc_data = P->CP0[C0_CAUSE];
      causeReg.s32.tc_ce = P->exception[exnum].badaddr;
      P->CP0[C0_CAUSE] = causeReg.tc_data;
   } else {
      
      /*
       * MIPS r4k manual is WRONG on this one.
       * Always latch badvaddr
       */
      P->CP0[C0_BADVADDR] = P->exception[exnum].badaddr;
   }
   P->CP0[C0_CTXT] = P->exception[exnum].ctxtreg;
   if (P->exception[exnum].vec == UT_VEC) { 
     UTLB_EXCEPTION(P, P->exception[exnum].cause);
   } else { 
     EXCEPTION(P, P->exception[exnum].cause);
   }
   P->PC = P->exception[exnum].vec;
   P->nPC = P->exception[exnum].vec+4;

   if (P->exception[exnum].cause == EXC_SYSCALL) {
#define SYSVoffset 1000
      int syscallNum = P->R[REG_V0] - SYSVoffset;
      ASSERT((syscallNum < MAX_SYSCALL) && (syscallNum >= 0));
      STATS_INC(P->myNum, numSyscalls, 1);
      STATS_INC(P->myNum, syscallCount[syscallNum], 1);
   }
   CopyToMXS (P);  /* Resets the MXS instruction window */
   return;

}

int
FPusable(struct s_cpu_state *st)
{

   CPUState *P = (CPUState *) (st->mipsyPtr);
   StatusReg statusReg;

   statusReg.ts_data = P->CP0[C0_SR];
   if (!(statusReg.s32.ts_cu1)) {
      /* CE bits of the cause register are set in badvaddr */
      RECORD_EXCEPTION(P, EXC_CPU, E_VEC, 1, 
                       P->CP0[C0_TLBHI], P->CP0[C0_CTXT],P->CP0[C0_XCTXT]);
      return 0;
   }
   return 1;
}

#endif /* MIPSY_MXS */

/* END UNTOUCHED MXS */

/*****************************************************************
 * ExceptionReturn
 * instruction for returning from an interrupt, exception, or
 * error trap.  if error trap load pc from the ErrorEPC and clear
 * ERL bit of the status register. else load pc from EPC and clear
 * EXL bit of the status register.
 * PC gets set in R4, not in R3.
 * Handler must save pc, op mode, status or interrupts enable, 
 * and restore.
 *****************************************************************/
void 
ExceptionReturn(CPUState *P)
{
   StatusReg statusReg;

   statusReg.ts_data = P->CP0[C0_SR];

   RFE_EVENT();
   
   if (statusReg.s32.ts_erl){
     P->PC = P->CP0[C0_ERROR_EPC];
     statusReg.s32.ts_erl = 0;
   } else {
     P->PC = P->CP0[C0_EPC];
     statusReg.s32.ts_exl = 0;
   }
   P->nPC = P->PC + INST_SIZE;
   P->CP0[C0_SR] = statusReg.ts_data;
   UpdateCPUMode(P);

   MipsyCheckForInterrupts(P);

}

/*****************************************************************
 * MipsyCheckForInterrupts
 * The cause register needs to have its interrupt pending (IP) bits
 * before we determine if we have to take an interrupts.
 * MipsyCheckForInterrupts is called every time the cpu simulator
 * sets an interrupt, on every mtc_op to CO_SR and periodically to 
 * catch TTY and net interrupts.
 * For an interrupt exception to take place, a few things have  to be true: 
 * (1) an interrupt bit has to be set in the cause register 
 * (2) that interrupt must be enabled in the SR's IM field 
 * (3) the SR must have the current interrupt enabled field set
 * (4) Can't be running at exception level.
 ****************************************************************/

void MipsyCheckForInterrupts(CPUState *P)
{

   P->CP0[C0_CAUSE] = (P->CP0[C0_CAUSE] & ~CAUSE_EXTINTBITS) |
      ((P->intrBitsPtr[0] << CAUSE_IPSHIFT) & CAUSE_EXTINTBITS);
   
   if (((P->CP0[C0_CAUSE] & P->CP0[C0_SR]) & SR_IMASK)
       && (P->CP0[C0_SR] & SR_IEC) && 
          !(P->CP0[C0_SR] & (SR_EXL|SR_ERL))) {
      STATS_SET(P->myNum, syncStallStart, 0);
      P->takeInterrupt = TRUE;
   }
}

int
MipsyNmi()
{
   int cpuNum=0; /* AJP: hard code this for now */
   StatusReg statusReg;
   CPUState *P = &PE[cpuNum];

   statusReg.ts_data = P->CP0[C0_SR];   
   statusReg.s32.ts_erl = 1;
   statusReg.s32.ts_bev = 1;
   statusReg.s32.ts_ts  = 0;
   statusReg.s32.ts_sr  = 1;

   P->CP0[C0_SR] = statusReg.ts_data;

   P->cpuMode = KERNEL_MODE;

   /* for uncached stalled cpus, wait for the stalled instruction 
    * to complete first */
   if (P->cpuStatus == cpu_stalled_uncached) {
      P->CP0[C0_ERROR_EPC] = P->nPC;
      P->nPC = R_VEC;
   } else {
      /* if cpu is running, take cache error right now */
      /* Save the current pc as C0_ERROR_EPC, DONT set Branch delay bit */
      if (P->nPC != (P->PC + INST_SIZE)) { 
         /* The inst that was preempted is in a BD slot */
         P->CP0[C0_ERROR_EPC] = P->PC - INST_SIZE;
      } else {
         P->CP0[C0_ERROR_EPC] = P->PC;
      }
      P->PC = R_VEC;
      P->nPC = R_VEC + 4;
   }
   P->stalledInst = FALSE;    /* Force inst refetch from exc vect */
    
   return 0;
}

/*****************************************************************
 * MipsyCacheError
 * 
 * Flashlite calls this for Cache Errors
 * 
 * 1) Set ERL
 * 2) Save the current PC as ERROR_EPC
 * 3) Set the PC to CACHE_ERROR_VEC (addr_layout.h)
 *
 * CAVEAT user:
 *  This doesn't yet implement the full R10K functionality. In the
 *  R10K, a second cache error may be posted, but will not be taken
 *  while the ERL status bit is set. To be done.
 *
 *****************************************************************/
void
MipsyCacheError(int cpuNum, bool isAsync)
{
   StatusReg statusReg;
   CPUState *P = &PE[cpuNum];

   /*
    * Shift current mode and interrupt status to previous, 
    * previous to old, and old can be discarded. This lets the CPU
    * respond to three levels of exceptions before software must
    * save the contents of the Status register.
    */
   statusReg.ts_data = P->CP0[C0_SR];   
   statusReg.s32.ts_erl = 1;

   P->CP0[C0_SR] = statusReg.ts_data;

   P->cpuMode = KERNEL_MODE;

   /* This is kind of messy. The R100000 manual says one thing and the
      R4000 manual (and sbd.h) says another, so using the R4000 settings
      for now... */
   if (isAsync) {
      /* from sysAD:  setting ED and EE */
      P->CP0[C0_CACHE_ERR] = 0x24000000;
   } else {
      /* a real cache error:  setting ED */
      P->CP0[C0_CACHE_ERR] = 0x20000000;
   }

   /* for uncached stalled cpus, wait for the stalled instruction to complete first */
   if (P->cpuStatus == cpu_stalled_uncached) {
      P->CP0[C0_ERROR_EPC] = P->nPC;
      if (statusReg.s32.ts_bev == 0) {
         P->nPC = CACHE_ERR_VEC_BEV0;
      } else {
         P->nPC = CACHE_ERR_VEC_BEV1;
      }
   } else {
      /* if cpu is running, take cache error right now */
      /* Save the current pc as C0_ERROR_EPC, DONT set Branch delay bit */
      if (P->nPC != (P->PC + INST_SIZE)) { 
         /* The inst that was preempted is in a BD slot */
         P->CP0[C0_ERROR_EPC] = P->PC - INST_SIZE;
      } else {
         P->CP0[C0_ERROR_EPC] = P->PC;
      }
      if (statusReg.s32.ts_bev == 0) {
         P->PC = CACHE_ERR_VEC_BEV0;
         P->nPC = CACHE_ERR_VEC_BEV0 + 4;
      } else {
         P->PC = CACHE_ERR_VEC_BEV1;
         P->nPC = CACHE_ERR_VEC_BEV1 + 4;
      }
   }
   P->stalledInst = FALSE;    /* Force inst refetch from exc vect */
}

/*****************************************************************
 * UpdateCPUMode
 *
 * This function is shared between mipsy and embra
 * Update with care. Do not remove the embra specific
 * stuff.
 *****************************************************************/
static void 
UpdateCPUMode(CPUState *P)
{
   StatusReg  statusReg; 
   statusReg.ts_data = P->CP0[C0_SR];
   P->cpuMode = KERNEL_MODE;
   if (!statusReg.s32.ts_erl && !statusReg.s32.ts_exl) { 
      ASSERT(statusReg.s32.ts_ksu != 3);
     if (statusReg.s32.ts_ksu == 2) {
        P->cpuMode = USER_MODE;
     } else if (statusReg.s32.ts_ksu == 1) { 
        P->cpuMode = SUPERVISOR_MODE;
     }
  }


   P->notFRbit = (statusReg.s32.ts_fr == 0);
   switch (P->cpuMode) { 
   case KERNEL_MODE: 
      P->is32bitMode = (statusReg.s32.ts_kx == 0);
      break;
   case SUPERVISOR_MODE: 
      P->is32bitMode = (statusReg.s32.ts_sx == 0);
#if defined(SIM_MIPS32)
      ASSERT(IS_SUPERV_SEG(P->PC));
#endif
      break;
   case USER_MODE:
      P->is32bitMode = (statusReg.s32.ts_ux == 0);
#if defined(SIM_MIPS32)
      ASSERT( IS_KUSEG(P->PC));
#endif
      break;
   default: 
      ASSERT(0);
   }

   SIM_DEBUG_DETAIL(('i', "CPUMode" , P->myNum, 
                    " going to %d PC=0x%llx SR=%x erl=%d exl=%d ksu=%d 32bit=%d\n",
                    P->cpuMode, (uint64)P->PC, P->CP0[C0_SR],
                    statusReg.s32.ts_erl,statusReg.s32.ts_exl,
                    statusReg.s32.ts_ksu,P->is32bitMode));

}


extern int numLLactive;
extern PA  LLAddrs[MIPSY_MAX_CPUS];

/*****************************************************************
 * All cop0 instructions are handled here. 
 *****************************************************************/
int
ExecuteC0Instruction(CPUState *P, Inst instr)
{
   uint rs = RS(instr);
   uint rt = RT(instr);
   uint rd = RD(instr);

   /* Handle the rs instructions */
   if (!IS_KERNEL_MODE(P)) {                 
      /* CP0 is unusable only in kernel and or when the cu0 bit is set. */
      CauseReg  causeReg;
      StatusReg statusReg;
      statusReg.ts_data = P->CP0[C0_SR];
      if (!statusReg.s32.ts_cu0) {
         causeReg.tc_data = P->CP0[C0_CAUSE];
         causeReg.s32.tc_ce = 0;
         P->CP0[C0_CAUSE] = causeReg.tc_data;
         EXCEPTION(P, EXC_CPU);
         return C0_CONTINUE;
      }
   }

   switch(rs) {

   case bc_op:
      CPUError("BCC0 is not valid\n");
      return C0_ILLEGAL_INST;
      
   case cfc_op:
      CPUError("CFC0 is not valid\n");
      return C0_ILLEGAL_INST;
      
   case ctc_op:
      CPUError("CTC0 is not valid\n");
      return C0_ILLEGAL_INST;
      
   case dmfc_op:
      if (P->is32bitMode) {  
         return C0_ILLEGAL_INST;
      }
      /* Fall thru */ 
   case mfc_op:
      /* update the count on a read */
      if (rd == C0_COUNT){
         /* If someone writes to count we need to watch the timer. */
         P->CP0[C0_COUNT] += (MipsyReadTime(P->myNum) - P->timerCycleCount)/
               COUNTER_FREQUENCY_DIVIDER;
         P->CP0[C0_COUNT] &= 0xffffffff;
         P->timerCycleCount = MipsyReadTime(P->myNum);
       } else if (rd == C0_RAND) {
  unsigned numRandEntries = P->numTlbEntries - P->CP0[C0_TLBWIRED];
  P->CP0[C0_RAND] = P->CP0[C0_TLBWIRED] +
            ((uint32)MipsyReadTime(P->myNum)) % numRandEntries; 
      }
      
      if (rs == mfc_op) { 
#if defined(SIM_MIPS64)
         if (P->CP0[rd] == 0x0000000080000000LL) {
            /* WARNING! This is a hack to fix a compiler bug in 7.2. 
               It assigns 0x0000000080000000 rather than 
               0xffffffff80000000 */
            P->R[rt] = 0xffffffff80000000LL;
         } else {
            P->R[rt] = (Reg)(Reg32_s)P->CP0[rd];
         }
#else
         P->R[rt] = (Reg)(Reg32_s)P->CP0[rd];
#endif
      } else { 
         P->R[rt] = P->CP0[rd];
      }
      break;
      
   case dmtc_op:
      if (P->is32bitMode) {  
         return C0_ILLEGAL_INST;
      }
      /* Fall thru */ 
   case mtc_op:  
      if (rs == dmtc_op) { 
         WriteC0Register(P, rd, P->R[rt], 1);
      } else {
         WriteC0Register(P, rd, (Reg32_s)(P->R[rt]), 0);
      } 
      break;
      
   default: 
      /* It wasn't any of these, so it's a CO function */
      switch(FUNC(instr)) {
         
      case rfe_op:
      /* Treat rfe as an eret for NachOS */
      case eret_op:
         if (UNCACHED_LL_SC) {
            if (P->LLbit) {
               numLLactive--;
               LLAddrs[P->myNum] = (PA) -1;
            }
         } 
         
         /* Note that this is now check for >= instead of
            just >. This is so we can capture the
            instruction that causes the transistion in the
            sample */ 
         if (STATS_VALUE(P->myNum, numInstructions) 
             >= STATS_VALUE(P->myNum, nextInstrSample)) {
            INST_SAMPLE_EVENT(MipsyReadTime(P->myNum), P->myNum, P->PC);
            STATS_INC(P->myNum, nextInstrSample, MS_SAMPLE_INSTR_INTERVAL);
         }
         
         P->LLbit = 0;
         /* This is bad... this is the one case where flow control
         gets messed up. */
         TraceInstruction(P, instr);
         ExceptionReturn(P);
         return C0_CONTINUE;
         
      case tlbp_op:
         ProbeTLB(P);
         break;
         
      case tlbr_op:
         ReadTLBEntry(P);
         break;
         
      case tlbwi_op:
         if (WriteTLBEntry(P) != SUCCESS) {
            CPUWarning("WriteTLB failed at %#x on %d\n",
                       P->PC, P->myNum);
         } else 
            break;
         
      case tlbwr_op:
         if (WriteRandomTLBEntry(P) != SUCCESS) {
            CPUWarning("WriteRandomTLB failed at %#x on %d\n",
                       P->PC, P->myNum);
         } else
            break;
         
      default:
         ASSERT(0);
         return C0_ILLEGAL_INST;
      }
   }
   return C0_SUCCESS;
}

/*****************************************************************
 * WriteC0Register
 * 
 * All writes to coprocessor come here for handling. This allows 
 * us to do whatever we want with read-only bits, etc.
 *****************************************************************/

static void
WriteC0Register(CPUState *P, int c0RegNum, Reg value, int is64bit)
{


   if (cp0RegCtl[c0RegNum].read_only) {
      return;
   }
   if (cp0RegCtl[c0RegNum].size == -1) {
      CPUWarning("WriteC0Reg write to invalid reg %d\n",
                 c0RegNum);
   }
   if ((cp0RegCtl[c0RegNum].zero_mask & value) != 0) {
      /* Trying to write must be zero bits, force them to zero. */
      value &= ~cp0RegCtl[c0RegNum].zero_mask;
      /* Print a warning message for the programmer. Special
       * case 32bit signed-extention bits that set high zero bits
       * of 64 bit registers (IRIX 6.2 does this). 
       */
      if (is64bit || (cp0RegCtl[c0RegNum].size != 1) ||
            ((cp0RegCtl[c0RegNum].zero_mask & value & 0xffffffff) != 0)) { 
#if defined(TORNADO) || defined(IRIX6_4)
         /* for now, tornado sometimes writes funny values for tlb stuff */
         /* So does IRIX 6.4 that that matter */
        int warning = (c0RegNum != C0_TLBLO_0) && (c0RegNum != C0_TLBLO_1);
#else
         int warning = 1;
#endif
         if (warning) { 
            CPUWarning("WriteC0Reg zero bits set during write to %d @%#llx RA %#llx, clearing\n",
                       c0RegNum, P->PC, P->R[31]);
         }
      }

   }
   if (is64bit && (cp0RegCtl[c0RegNum].size == 0)) {
#ifdef IRIX6_4       
      if (c0RegNum != C0_SR) 
#endif
      CPUWarning("WriteC0Reg 64bit write to 32bit reg %d\n",
                 c0RegNum);

   }
   if (c0RegNum == C0_CAUSE){ 
      P->CP0[C0_CAUSE] &= ~(CAUSE_SW2|CAUSE_SW1);
      P->CP0[C0_CAUSE] |= (value & (CAUSE_SW2|CAUSE_SW1));
   } else if (c0RegNum == C0_CONFIG) {
      P->CP0[C0_CONFIG] &= ~0x3f;
      P->CP0[C0_CONFIG] |= value & 0x3f;
   } else { 
      P->CP0[c0RegNum] = value;        
   }

   if (c0RegNum == C0_COMPARE) {
      CompareWritten(P);
   }
   
   if (c0RegNum == C0_COUNT) {
      CountWritten(P);
   }
   if (c0RegNum == C0_TLBHI) {
      /* Clear the fill bits */
      P->CP0[c0RegNum] &= TLBHI_FILLMASK;
      /* Might be changing the ASID */
      P->pcVPNcache = 0; 
      TraceCheckASID(P);
   }
   if (c0RegNum == C0_SR){ 
      StatusReg statusReg;

      statusReg.ts_data = P->CP0[C0_SR];
#if defined(SIM_MIPS32)
      if ((statusReg.s32.ts_ux) || (statusReg.s32.ts_sx) ||
          (statusReg.s32.ts_kx)) {
         static int warned_64 = 0;
         if (!warned_64) {
            CPUWarning("MIPSY: 64-bit mode not implemented, ignoring SR write\n");
            warned_64 = 1;
         }
         
         statusReg.s32.ts_ux = 0;
         statusReg.s32.ts_sx = 0;
         statusReg.s32.ts_kx = 0;
         P->CP0[C0_SR] = statusReg.ts_data;
      }
#endif

      /* Don't allow reverse endian either. */
      if (statusReg.s32.ts_re) {
         static int warned_re = 0;
         if (!warned_re) {
            CPUWarning("MIPSY: reverse-endian mode not implemented, ignore SR write\n");
            warned_re = 1;
         }
         statusReg.s32.ts_re = 0;
      }
      UpdateCPUMode(P);
      MipsyCheckForInterrupts(P);
   }
   if (c0RegNum == C0_CAUSE){ 
      MipsyCheckForInterrupts(P);
   }
} 


/*****************************************************************
 * R4000 Timer support
 *****************************************************************/ 

static EventCallbackHdr timerCallbackHdr[MIPSY_MAX_CPUS];
static void MipsySetTimerCallback(int cpuNum);

/*****************************************************************
 * Things that need doing when the compare register is written. 
 * Right now just timer related actions.
 *****************************************************************/
static void
CompareWritten(CPUState *P)
{
   int cpuNum = P->myNum;

   /* make sure upper bits are zero */
   P->CP0[C0_COMPARE] &= 0xffffffff;


   PE[cpuNum].CP0[C0_CAUSE] &= ~CAUSE_IP8;


   if (EventCallbackActive(&(timerCallbackHdr[cpuNum]))) {
      EventCallbackRemove(&(timerCallbackHdr[cpuNum]));
   }
   MipsySetTimerCallback(cpuNum); 
}

/*****************************************************************
 * Things that need doing when the count register is written. 
 * Right now just timer related actions.
 *****************************************************************/
static void
CountWritten(CPUState *P) 
{
   int cpuNum = P->myNum;

   /* make sure upper bits are zero */
   P->CP0[C0_COUNT] &= 0xffffffff;

   P->timerCycleCount = MipsyReadTime(P->myNum);
   if (EventCallbackActive(&(timerCallbackHdr[cpuNum]))) {
      EventCallbackRemove(&(timerCallbackHdr[cpuNum]));
   }
   MipsySetTimerCallback(cpuNum);
}

/****************************************************************
 * TMipsyimerCallback
 *
 * This is the routine called back on the event that
 * the C0_COMPARE == C0_COUNT, it is  set when the 
 * COMPARE register is written.  Raise IP(7) in the 
 * C0_CAUSE register to signal a timer interrupt is 
 * pending.  Note: IP(7) is cleared when when the 
 * C0_COMPARE register is written. use DEV_IEC_MAGICERR
 * as it corresponds to hw interrupt bit #5 which raises
 * ip7 in the cause register.
 ****************************************************************/
static void 
MipsyTimerCallback(int cpuNum, EventCallbackHdr *ECBhdr, void *empty) 
{
  if (simosCPUType != MIPSY) {
     return;
  }
  PE[cpuNum].CP0[C0_CAUSE] |= CAUSE_IP8;
  MipsyCheckForInterrupts(&PE[cpuNum]);
}

/*****************************************************************
 * MipsySetTimerCallback
 *
 * Each processor has its own r4kTimerInfo and r4k_timerHdr
 * associated with it.  When the Compare register is written to
 * we check current cycle count, and, projecting into the future the
 * diff btwn the new Compare reg value and the current cycle count, a
 * callback is set to fire in that calculate amt of time.  It is tricky
 * only when they decide to write to the count reg, which is permited on
 * system initialization or to synchronize processors.  Since we do not 
 * update the Count register continually, our cycle count and the Count
 * register value could then be out-of-synch.  The r4kTimerInfo variable
 * is used to track this discrepency.
 ****************************************************************/
static void 
MipsySetTimerCallback(int cpuNum)
{
   CPUState *P = &PE[cpuNum]; 
   SimTime  timeInFuture;

   P->CP0[C0_COUNT] += (MipsyReadTime(cpuNum) - P->timerCycleCount)/
      COUNTER_FREQUENCY_DIVIDER;
   P->timerCycleCount = MipsyReadTime(cpuNum);
   
   P->CP0[C0_COUNT] &= 0xffffffff;

   if (P->CP0[C0_COMPARE] >= P->CP0[C0_COUNT]) {
       timeInFuture =  (P->CP0[C0_COMPARE] - P->CP0[C0_COUNT]);
       timeInFuture *=  COUNTER_FREQUENCY_DIVIDER;
   } else {
       timeInFuture =  0x100000000LL - (P->CP0[C0_COUNT] - P->CP0[C0_COMPARE]);
       timeInFuture *=  COUNTER_FREQUENCY_DIVIDER;
   }
   EventDoCallback(cpuNum, MipsyTimerCallback, 
                   &(timerCallbackHdr[cpuNum]), NULL, timeInFuture);

}


/*****************************************************************
 * CHECKING OF INTERRUPTS
 *****************************************************************/

/*****************************************************************
 * CheckForInterrupts callback
 * This callback is in charge of polling for interrupts and checking 
 * if mipsy should be exited. You can exit by running the set number
 * of cycles or by attaching with a debugger and setting "mipsyExit"
 * to true.
 *****************************************************************/
static struct CheckForInterruptsCallbackHdr { 
   EventCallbackHdr hdr;
   SimTime interval;
} checkForInterruptsEvent[SIM_MAXCPUS];

extern bool exitMipsy;

static void
CheckForInterruptsCallback(int cpuNum, EventCallbackHdr *hdr, void *empty)
{
   int cpu;

   if (simosCPUType != MIPSY) {
      return;
   }

   for (cpu = 0; cpu < TOTAL_CPUS; cpu++) {
      MipsyCheckForInterrupts(&PE[cpu]);
   }

   EventDoCallback(cpuNum, CheckForInterruptsCallback, hdr, 0, 
                   checkForInterruptsEvent[cpuNum].interval);

   /* Another way of leaving mipsy is to attach to it with the */
   /* debugger and set the exitMipsy flag to TRUE */
   if (exitMipsy) {
      CPUPrint("exitMipsy set to true (by debugger)\n");
      MipsyExit(BASE);
   }
}

void EnableInterruptCheck(CPUState *P, int interval)
{
   checkForInterruptsEvent[P->myNum].interval = interval;
   EventDoCallback(P->myNum, CheckForInterruptsCallback, 
                   &checkForInterruptsEvent[P->myNum].hdr, 
                   0, interval);
}



#ifdef MIPSY_MXS
/*****************************************************************
 * DoPrivInst - Perform a priviledged instruction for MXS. 
 *              MXS passes us the instr and any source register
 *              values that come from the GP register set. We return
 *              to MXS any destination registers.
 *****************************************************************/      
bool
DoPrivInst(struct s_cpu_state *st, uint instr, uint srcreg, uint *dstreg, 
           bool *hack)
{
   CPUState *P = (CPUState *) (st->mipsyPtr);
   uint rs = RS(instr);
   uint rd = RD(instr);
   uint op = MAJOR_OP(instr);

   (*hack) = FALSE;   
   if (!IS_KERNEL_MODE(P)) {
      /* CP0 is unusable */
      CPUWarning("Using CP0 inst in user mode!\n");
      RECORD_EXCEPTION(P, EXC_CPU, E_VEC, 0,  P->CP0[C0_TLBHI], 
                       P->CP0[C0_CTXT],P->CP0[C0_XCTXT]);
      return TRUE;
   }
   if (op == cop0_op) { 
      /* First handle the rs instructions */
      switch(rs) {

      case bc_op:
         CPUError("BCC0 is not valid\n");
         break;

      case mfc_op:
         (*dstreg) = P->CP0[rd];
         break;

      case mtc_op:
        /*BAN: BEGIN*/
        if (rs == dmtc_op) { 
          WriteC0Register(P, rd, srcreg, 1);
        } else {
          WriteC0Register(P, rd, (Reg32_s)srcreg, 0);
        } 
        /*BAN: END*/
        break;
      
      default: 
         /* It wasn't any of these, so it's a CO function */
         CopyFromMXS(P);
         switch(FUNC(instr)) {

         case eret_op:
            P->LLbit = 0;
#ifdef BANREMOVE
            if (P->numInstructions >= P->nextInstrSample) {
               INST_SAMPLE_EVENT(MipsyReadTime(P->myNum), P->myNum, P->PC);
               P->nextInstrSample += MS_SAMPLE_INSTR_INTERVAL;
            }
#endif
            /*BAN: BEGIN*/
            ExceptionReturn(P);
            /*BAN: END*/
            (*hack) = TRUE;
            break;

         case rfe_op:
            CPUError("MIPSY: Hit an RFE on an R4000\n");
            break;

         case tlbp_op:
            ProbeTLB(P);
            break;

         case tlbr_op:
            ReadTLBEntry(P);
            break;

         case tlbwi_op:
            WriteTLBEntry(P);
            break;

         case tlbwr_op:
            WriteRandomTLBEntry(P);
            break;

         default:
            CPUWarning("COP0 instruction not found at %#x\n", P->PC);
            break;

         } /* cp0 functions */
      } /* rs values */
   } else if (op == cache_op) {
      /* Be careful with this one. Mipsy's caches are
         physically indexed. */
      uint targetCache;

      targetCache = TARGET_CACHE(instr);

      switch(targetCache) {
      case CACH_PI:
      case CACH_PD:
      case CACH_SI:
         CPUWarning("Bad op for cache instruction\n");
         break;

      case CACH_SD:
         CPUWarning("Bad op for cache instruction\n");
         break;

      default:
            CPUWarning("BAD TARGET CACHE at %#x\n", P->PC);
            break;
       }
   } else {
      CPUError("Unknown CP0 opcode in DoPrivInst\n");
   }
   return FALSE;
}
#endif