summaryrefslogtreecommitdiffstatshomepage
path: root/src/mame/machine/xbox.cpp
blob: 7a428d6f65aae3e460ddfca34cb11c9d970faa97 (plain) (blame)
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
// license:BSD-3-Clause
// copyright-holders:Samuele Zannoli

#include "emu.h"
#include "cpu/i386/i386.h"
#include "machine/lpci.h"
#include "machine/pic8259.h"
#include "machine/pit8253.h"
#include "machine/idectrl.h"
#include "video/poly.h"
#include "bitmap.h"
#include "debug/debugcon.h"
#include "debug/debugcmd.h"
#include "debug/debugcpu.h"
#include "includes/chihiro.h"
#include "includes/xbox.h"

#define LOG_PCI
//#define LOG_AUDIO
//#define LOG_OHCI
#define USB_HACK_ENABLED

static void dump_string_command(running_machine &machine, int ref, int params, const char **param)
{
	xbox_base_state *state = machine.driver_data<xbox_base_state>();
	address_space &space = state->m_maincpu->space();
	UINT64  addr;
	offs_t address;
	UINT32 length, maximumlength;
	offs_t buffer;

	if (params < 1)
		return;
	if (!debug_command_parameter_number(machine, param[0], &addr))
		return;
	address = (offs_t)addr;
	if (!debug_cpu_translate(space, TRANSLATE_READ_DEBUG, &address))
	{
		debug_console_printf(machine, "Address is unmapped.\n");
		return;
	}
	length = space.read_word_unaligned(address);
	maximumlength = space.read_word_unaligned(address + 2);
	buffer = space.read_dword_unaligned(address + 4);
	debug_console_printf(machine, "Length %d word\n", length);
	debug_console_printf(machine, "MaximumLength %d word\n", maximumlength);
	debug_console_printf(machine, "Buffer %08X byte* ", buffer);
	if (!debug_cpu_translate(space, TRANSLATE_READ_DEBUG, &buffer))
	{
		debug_console_printf(machine, "\nBuffer is unmapped.\n");
		return;
	}
	if (length > 256)
		length = 256;
	for (int a = 0; a < length; a++)
	{
		UINT8 c = space.read_byte(buffer + a);
		debug_console_printf(machine, "%c", c);
	}
	debug_console_printf(machine, "\n");
}

static void dump_process_command(running_machine &machine, int ref, int params, const char **param)
{
	xbox_base_state *state = machine.driver_data<xbox_base_state>();
	address_space &space = state->m_maincpu->space();
	UINT64 addr;
	offs_t address;

	if (params < 1)
		return;
	if (!debug_command_parameter_number(machine, param[0], &addr))
		return;
	address = (offs_t)addr;
	if (!debug_cpu_translate(space, TRANSLATE_READ_DEBUG, &address))
	{
		debug_console_printf(machine, "Address is unmapped.\n");
		return;
	}
	debug_console_printf(machine, "ReadyListHead {%08X,%08X} _LIST_ENTRY\n", space.read_dword_unaligned(address), space.read_dword_unaligned(address + 4));
	debug_console_printf(machine, "ThreadListHead {%08X,%08X} _LIST_ENTRY\n", space.read_dword_unaligned(address + 8), space.read_dword_unaligned(address + 12));
	debug_console_printf(machine, "StackCount %d dword\n", space.read_dword_unaligned(address + 16));
	debug_console_printf(machine, "ThreadQuantum %d dword\n", space.read_dword_unaligned(address + 20));
	debug_console_printf(machine, "BasePriority %d byte\n", space.read_byte(address + 24));
	debug_console_printf(machine, "DisableBoost %d byte\n", space.read_byte(address + 25));
	debug_console_printf(machine, "DisableQuantum %d byte\n", space.read_byte(address + 26));
	debug_console_printf(machine, "_padding %d byte\n", space.read_byte(address + 27));
}

static void dump_list_command(running_machine &machine, int ref, int params, const char **param)
{
	xbox_base_state *state = machine.driver_data<xbox_base_state>();
	address_space &space = state->m_maincpu->space();
	UINT64 addr, offs, start, old;
	offs_t address, offset;

	if (params < 1)
		return;
	if (!debug_command_parameter_number(machine, param[0], &addr))
		return;
	offs = 0;
	offset = 0;
	if (params >= 2)
	{
		if (!debug_command_parameter_number(machine, param[1], &offs))
			return;
		offset = (offs_t)offs;
	}
	start = addr;
	address = (offs_t)addr;
	if (!debug_cpu_translate(space, TRANSLATE_READ_DEBUG, &address))
	{
		debug_console_printf(machine, "Address is unmapped.\n");
		return;
	}
	if (params >= 2)
		debug_console_printf(machine, "Entry    Object\n");
	else
		debug_console_printf(machine, "Entry\n");
	for (int num = 0; num < 32; num++)
	{
		if (params >= 2)
			debug_console_printf(machine, "%08X %08X\n", (UINT32)addr, (offs_t)addr - offset);
		else
			debug_console_printf(machine, "%08X\n", (UINT32)addr);
		old = addr;
		addr = space.read_dword_unaligned(address);
		if (addr == start)
			break;
		if (addr == old)
			break;
		address = (offs_t)addr;
		if (!debug_cpu_translate(space, TRANSLATE_READ_DEBUG, &address))
			break;
	}
}

static void dump_dpc_command(running_machine &machine, int ref, int params, const char **param)
{
	xbox_base_state *state = machine.driver_data<xbox_base_state>();
	address_space &space = state->m_maincpu->space();
	UINT64 addr;
	offs_t address;

	if (params < 1)
		return;
	if (!debug_command_parameter_number(machine, param[0], &addr))
		return;
	address = (offs_t)addr;
	if (!debug_cpu_translate(space, TRANSLATE_READ_DEBUG, &address))
	{
		debug_console_printf(machine, "Address is unmapped.\n");
		return;
	}
	debug_console_printf(machine, "Type %d word\n", space.read_word_unaligned(address));
	debug_console_printf(machine, "Inserted %d byte\n", space.read_byte(address + 2));
	debug_console_printf(machine, "Padding %d byte\n", space.read_byte(address + 3));
	debug_console_printf(machine, "DpcListEntry {%08X,%08X} _LIST_ENTRY\n", space.read_dword_unaligned(address + 4), space.read_dword_unaligned(address + 8));
	debug_console_printf(machine, "DeferredRoutine %08X dword\n", space.read_dword_unaligned(address + 12));
	debug_console_printf(machine, "DeferredContext %08X dword\n", space.read_dword_unaligned(address + 16));
	debug_console_printf(machine, "SystemArgument1 %08X dword\n", space.read_dword_unaligned(address + 20));
	debug_console_printf(machine, "SystemArgument2 %08X dword\n", space.read_dword_unaligned(address + 24));
}

static void dump_timer_command(running_machine &machine, int ref, int params, const char **param)
{
	xbox_base_state *state = machine.driver_data<xbox_base_state>();
	address_space &space = state->m_maincpu->space();
	UINT64 addr;
	offs_t address;

	if (params < 1)
		return;
	if (!debug_command_parameter_number(machine, param[0], &addr))
		return;
	address = (offs_t)addr;
	if (!debug_cpu_translate(space, TRANSLATE_READ_DEBUG, &address))
	{
		debug_console_printf(machine, "Address is unmapped.\n");
		return;
	}
	debug_console_printf(machine, "Header.Type %d byte\n", space.read_byte(address));
	debug_console_printf(machine, "Header.Absolute %d byte\n", space.read_byte(address + 1));
	debug_console_printf(machine, "Header.Size %d byte\n", space.read_byte(address + 2));
	debug_console_printf(machine, "Header.Inserted %d byte\n", space.read_byte(address + 3));
	debug_console_printf(machine, "Header.SignalState %08X dword\n", space.read_dword_unaligned(address + 4));
	debug_console_printf(machine, "Header.WaitListEntry {%08X,%08X} _LIST_ENTRY\n", space.read_dword_unaligned(address + 8), space.read_dword_unaligned(address + 12));
	debug_console_printf(machine, "%s", string_format("DueTime %I64x qword\n", (INT64)space.read_qword_unaligned(address + 16)).c_str());
	debug_console_printf(machine, "TimerListEntry {%08X,%08X} _LIST_ENTRY\n", space.read_dword_unaligned(address + 24), space.read_dword_unaligned(address + 28));
	debug_console_printf(machine, "Dpc %08X dword\n", space.read_dword_unaligned(address + 32));
	debug_console_printf(machine, "Period %d dword\n", space.read_dword_unaligned(address + 36));
}

static void curthread_command(running_machine &machine, int ref, int params, const char **param)
{
	xbox_base_state *state = machine.driver_data<xbox_base_state>();
	address_space &space = state->m_maincpu->space();
	UINT64 fsbase;
	UINT32 kthrd, topstack, tlsdata;
	offs_t address;

	fsbase = state->m_maincpu->state_int(44);
	address = (offs_t)fsbase + 0x28;
	if (!debug_cpu_translate(space, TRANSLATE_READ_DEBUG, &address))
	{
		debug_console_printf(machine, "Address is unmapped.\n");
		return;
	}
	kthrd = space.read_dword_unaligned(address);
	debug_console_printf(machine, "Current thread is %08X\n", kthrd);
	address = (offs_t)kthrd + 0x1c;
	if (!debug_cpu_translate(space, TRANSLATE_READ_DEBUG, &address))
		return;
	topstack = space.read_dword_unaligned(address);
	debug_console_printf(machine, "Current thread stack top is %08X\n", topstack);
	address = (offs_t)kthrd + 0x28;
	if (!debug_cpu_translate(space, TRANSLATE_READ_DEBUG, &address))
		return;
	tlsdata = space.read_dword_unaligned(address);
	if (tlsdata == 0)
		address = (offs_t)topstack - 0x210 - 8;
	else
		address = (offs_t)tlsdata - 8;
	if (!debug_cpu_translate(space, TRANSLATE_READ_DEBUG, &address))
		return;
	debug_console_printf(machine, "Current thread function is %08X\n", space.read_dword_unaligned(address));
}

static void generate_irq_command(running_machine &machine, int ref, int params, const char **param)
{
	UINT64 irq;
	xbox_base_state *chst = machine.driver_data<xbox_base_state>();

	if (params < 1)
		return;
	if (!debug_command_parameter_number(machine, param[0], &irq))
		return;
	if (irq > 15)
		return;
	if (irq == 2)
		return;
	chst->debug_generate_irq((int)irq, true);
}

static void nv2a_combiners_command(running_machine &machine, int ref, int params, const char **param)
{
	int en;

	xbox_base_state *chst = machine.driver_data<xbox_base_state>();
	en = chst->nvidia_nv2a->toggle_register_combiners_usage();
	if (en != 0)
		debug_console_printf(machine, "Register combiners enabled\n");
	else
		debug_console_printf(machine, "Register combiners disabled\n");
}

static void waitvblank_command(running_machine &machine, int ref, int params, const char **param)
{
	int en;

	xbox_base_state *chst = machine.driver_data<xbox_base_state>();
	en = chst->nvidia_nv2a->toggle_wait_vblank_support();
	if (en != 0)
		debug_console_printf(machine, "Vblank method enabled\n");
	else
		debug_console_printf(machine, "Vblank method disabled\n");
}

static void grab_texture_command(running_machine &machine, int ref, int params, const char **param)
{
	UINT64 type;
	xbox_base_state *chst = machine.driver_data<xbox_base_state>();

	if (params < 2)
		return;
	if (!debug_command_parameter_number(machine, param[0], &type))
		return;
	if ((param[1][0] == 0) || (strlen(param[1]) > 127))
		return;
	chst->nvidia_nv2a->debug_grab_texture((int)type, param[1]);
}

static void grab_vprog_command(running_machine &machine, int ref, int params, const char **param)
{
	xbox_base_state *chst = machine.driver_data<xbox_base_state>();
	UINT32 instruction[4];
	FILE *fil;

	if (params < 1)
		return;
	if ((param[0][0] == 0) || (strlen(param[0]) > 127))
		return;
	if ((fil = fopen(param[0], "wb")) == nullptr)
		return;
	for (int n = 0; n < 136; n++) {
		chst->nvidia_nv2a->debug_grab_vertex_program_slot(n, instruction);
		fwrite(instruction, sizeof(UINT32), 4, fil);
	}
	fclose(fil);
}

static void vprogdis_command(running_machine &machine, int ref, int params, const char **param)
{
	UINT64 address, length, type;
	UINT32 instruction[4];
	offs_t addr;
	vertex_program_disassembler vd;
	char line[64];
	xbox_base_state *chst = machine.driver_data<xbox_base_state>();
	address_space &space = chst->m_maincpu->space();

	if (params < 2)
		return;
	if (!debug_command_parameter_number(machine, param[0], &address))
		return;
	if (!debug_command_parameter_number(machine, param[1], &length))
		return;
	type = 0;
	if (params > 2)
		if (!debug_command_parameter_number(machine, param[2], &type))
			return;
	while (length > 0) {
		if (type == 1) {
			addr = (offs_t)address;
			if (!debug_cpu_translate(space, TRANSLATE_READ_DEBUG, &addr))
				return;
			instruction[0] = space.read_dword_unaligned(address);
			instruction[1] = space.read_dword_unaligned(address + 4);
			instruction[2] = space.read_dword_unaligned(address + 8);
			instruction[3] = space.read_dword_unaligned(address + 12);
		}
		else
			chst->nvidia_nv2a->debug_grab_vertex_program_slot((int)address, instruction);
		while (vd.disassemble(instruction, line) != 0)
			debug_console_printf(machine, "%s\n", line);
		if (type == 1)
			address = address + 4 * 4;
		else
			address++;
		length--;
	}
}

static void help_command(running_machine &machine, int ref, int params, const char **param)
{
	debug_console_printf(machine, "Available Xbox commands:\n");
	debug_console_printf(machine, "  xbox dump_string,<address> -- Dump _STRING object at <address>\n");
	debug_console_printf(machine, "  xbox dump_process,<address> -- Dump _PROCESS object at <address>\n");
	debug_console_printf(machine, "  xbox dump_list,<address>[,<offset>] -- Dump _LIST_ENTRY chain starting at <address>\n");
	debug_console_printf(machine, "  xbox dump_dpc,<address> -- Dump _KDPC object at <address>\n");
	debug_console_printf(machine, "  xbox dump_timer,<address> -- Dump _KTIMER object at <address>\n");
	debug_console_printf(machine, "  xbox curthread -- Print information about current thread\n");
	debug_console_printf(machine, "  xbox irq,<number> -- Generate interrupt with irq number 0-15\n");
	debug_console_printf(machine, "  xbox nv2a_combiners -- Toggle use of register combiners\n");
	debug_console_printf(machine, "  xbox waitvblank -- Toggle support for wait vblank method\n");
	debug_console_printf(machine, "  xbox grab_texture,<type>,<filename> -- Save to <filename> the next used texture of type <type>\n");
	debug_console_printf(machine, "  xbox grab_vprog,<filename> -- save current vertex program instruction slots to <filename>\n");
	debug_console_printf(machine, "  xbox vprogdis,<address>,<length>[,<type>] -- disassemble <lenght> vertex program instructions at <address> of <type>\n");
	debug_console_printf(machine, "  xbox help -- this list\n");
}

static void xbox_debug_commands(running_machine &machine, int ref, int params, const char **param)
{
	if (params < 1)
		return;
	if (strcmp("dump_string", param[0]) == 0)
		dump_string_command(machine, ref, params - 1, param + 1);
	else if (strcmp("dump_process", param[0]) == 0)
		dump_process_command(machine, ref, params - 1, param + 1);
	else if (strcmp("dump_list", param[0]) == 0)
		dump_list_command(machine, ref, params - 1, param + 1);
	else if (strcmp("dump_dpc", param[0]) == 0)
		dump_dpc_command(machine, ref, params - 1, param + 1);
	else if (strcmp("dump_timer", param[0]) == 0)
		dump_timer_command(machine, ref, params - 1, param + 1);
	else if (strcmp("curthread", param[0]) == 0)
		curthread_command(machine, ref, params - 1, param + 1);
	else if (strcmp("irq", param[0]) == 0)
		generate_irq_command(machine, ref, params - 1, param + 1);
	else if (strcmp("nv2a_combiners", param[0]) == 0)
		nv2a_combiners_command(machine, ref, params - 1, param + 1);
	else if (strcmp("waitvblank", param[0]) == 0)
		waitvblank_command(machine, ref, params - 1, param + 1);
	else if (strcmp("grab_texture", param[0]) == 0)
		grab_texture_command(machine, ref, params - 1, param + 1);
	else if (strcmp("grab_vprog", param[0]) == 0)
		grab_vprog_command(machine, ref, params - 1, param + 1);
	else if (strcmp("vprogdis", param[0]) == 0)
		vprogdis_command(machine, ref, params - 1, param + 1);
	else
		help_command(machine, ref, params - 1, param + 1);
}

void xbox_base_state::debug_generate_irq(int irq, bool active)
{
	int state;

	if (active)
	{
		debug_irq_active = true;
		debug_irq_number = irq;
		state = 1;
	}
	else
	{
		debug_irq_active = false;
		state = 0;
	}
	switch (irq)
	{
	case 0:
		xbox_base_devs.pic8259_1->ir0_w(state);
		break;
	case 1:
		xbox_base_devs.pic8259_1->ir1_w(state);
		break;
	case 3:
		xbox_base_devs.pic8259_1->ir3_w(state);
		break;
	case 4:
		xbox_base_devs.pic8259_1->ir4_w(state);
		break;
	case 5:
		xbox_base_devs.pic8259_1->ir5_w(state);
		break;
	case 6:
		xbox_base_devs.pic8259_1->ir6_w(state);
		break;
	case 7:
		xbox_base_devs.pic8259_1->ir7_w(state);
		break;
	case 8:
		xbox_base_devs.pic8259_2->ir0_w(state);
		break;
	case 9:
		xbox_base_devs.pic8259_2->ir1_w(state);
		break;
	case 10:
		xbox_base_devs.pic8259_2->ir2_w(state);
		break;
	case 11:
		xbox_base_devs.pic8259_2->ir3_w(state);
		break;
	case 12:
		xbox_base_devs.pic8259_2->ir4_w(state);
		break;
	case 13:
		xbox_base_devs.pic8259_2->ir5_w(state);
		break;
	case 14:
		xbox_base_devs.pic8259_2->ir6_w(state);
		break;
	case 15:
		xbox_base_devs.pic8259_2->ir7_w(state);
		break;
	}
}

void xbox_base_state::vblank_callback(screen_device &screen, bool state)
{
	nvidia_nv2a->vblank_callback(screen, state);
}

UINT32 xbox_base_state::screen_update_callback(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
	return nvidia_nv2a->screen_update_callback(screen, bitmap, cliprect);
}

READ32_MEMBER(xbox_base_state::geforce_r)
{
	return nvidia_nv2a->geforce_r(space, offset, mem_mask);
}

WRITE32_MEMBER(xbox_base_state::geforce_w)
{
	nvidia_nv2a->geforce_w(space, offset, data, mem_mask);
}

static UINT32 geforce_pci_r(device_t *busdevice, device_t *device, int function, int reg, UINT32 mem_mask)
{
#ifdef LOG_PCI
	busdevice->logerror("  bus:1 device:NV_2A function:%d register:%d mask:%08X\n",function,reg,mem_mask);
#endif
	return 0;
}

static void geforce_pci_w(device_t *busdevice, device_t *device, int function, int reg, UINT32 data, UINT32 mem_mask)
{
#ifdef LOG_PCI
	busdevice->logerror("  bus:1 device:NV_2A function:%d register:%d data:%08X mask:%08X\n",function,reg,data,mem_mask);
#endif
}

/*
 * ohci usb controller
 */

#ifdef LOG_OHCI
static const char *const usbregnames[] = {
	"HcRevision",
	"HcControl",
	"HcCommandStatus",
	"HcInterruptStatus",
	"HcInterruptEnable",
	"HcInterruptDisable",
	"HcHCCA",
	"HcPeriodCurrentED",
	"HcControlHeadED",
	"HcControlCurrentED",
	"HcBulkHeadED",
	"HcBulkCurrentED",
	"HcDoneHead",
	"HcFmInterval",
	"HcFmRemaining",
	"HcFmNumber",
	"HcPeriodicStart",
	"HcLSThreshold",
	"HcRhDescriptorA",
	"HcRhDescriptorB",
	"HcRhStatus",
	"HcRhPortStatus[1]"
};
#endif

const device_type OHCI_USB_CONTROLLER = &device_creator<ohci_usb_controller>;

ohci_usb_controller::ohci_usb_controller(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) :
	device_t(mconfig, OHCI_USB_CONTROLLER, "OHCI USB CONTROLLER", tag, owner, clock, "ohciusb", __FILE__),
	m_interrupt_handler(*this)
{
	memset(&ohcist, 0, sizeof(ohcist));
}

void ohci_usb_controller::device_start()
{
	m_maincpu = machine().device<cpu_device>("maincpu");
	m_interrupt_handler.resolve_safe();
	ohcist.hc_regs[HcRevision] = 0x10;
	ohcist.hc_regs[HcFmInterval] = 0x2edf;
	ohcist.hc_regs[HcLSThreshold] = 0x628;
	ohcist.hc_regs[HcRhDescriptorA] = 4;
	ohcist.hc_regs[HcControl] = UsbReset << 6;
	ohcist.state = UsbReset;
	ohcist.interruptbulkratio = 1;
	ohcist.writebackdonehadcounter = 7;
	for (int n = 0; n <= 4; n++)
		ohcist.ports[n].address = -1;
	for (int n = 0; n < 256; n++)
		ohcist.address[n].port = -1;
	ohcist.space = &(m_maincpu->space());
	ohcist.timer = timer_alloc(0);
	ohcist.timer->enable(false);
}

void ohci_usb_controller::device_reset()
{
}

READ32_MEMBER(ohci_usb_controller::read)
{
	UINT32 ret;

#ifdef LOG_OHCI
	if (offset >= 0x54 / 4)
		logerror("usb controller 0 register HcRhPortStatus[%d] read\n", (offset - 0x54 / 4) + 1);
	else
		logerror("usb controller 0 register %s read\n", usbregnames[offset]);
#endif
	ret = ohcist.hc_regs[offset];
	if (offset == 0) { /* hacks needed until usb (and jvs) is implemented */
#ifndef USB_HACK_ENABLED
		hack_usb();
#endif
	}
	return ret;
}

WRITE32_MEMBER(ohci_usb_controller::write)
{
	UINT32 old = ohcist.hc_regs[offset];

#ifdef LOG_OHCI
	if (offset >= 0x54 / 4)
		logerror("usb controller 0 register HcRhPortStatus[%d] write %08X\n", (offset - 0x54 / 4) + 1, data);
	else
		logerror("usb controller 0 register %s write %08X\n", usbregnames[offset], data);
#endif
	if (offset == HcRhStatus) {
		if (data & CRWE)
			ohcist.hc_regs[HcRhStatus] &= ~DRWE;
		if (data & OCIC)
			ohcist.hc_regs[HcRhStatus] &= ~OCI;
		if (data & LPSC)
			ohcist.hc_regs[HcRhStatus] &= ~LPS;
		return;
	}
	if (offset == HcControl) {
		int hcfs;

		hcfs = (data >> 6) & 3; // HostControllerFunctionalState
		if (hcfs == UsbOperational) {
			ohcist.timer->enable();
			ohcist.timer->adjust(attotime::from_msec(1), 0, attotime::from_msec(1));
			ohcist.writebackdonehadcounter = 7;
			// need to load the FrameRemaining field of HcFmRemaining with the value of the FrameInterval field in HcFmInterval
		}
		else
			ohcist.timer->enable(false);
		ohcist.interruptbulkratio = (data & 3) + 1;
		if ((hcfs != UsbReset) && (ohcist.state == UsbReset))
		{
			ohcist.hc_regs[HcInterruptStatus] |= RootHubStatusChange;
			usb_ohci_interrupts();
		}
		ohcist.state = hcfs;
	}
	if (offset == HcCommandStatus) {
		if (data & 1) // HostControllerReset
			ohcist.hc_regs[HcControl] |= 3 << 6;
		ohcist.hc_regs[HcCommandStatus] |= data;
		return;
	}
	if (offset == HcInterruptStatus) {
		ohcist.hc_regs[HcInterruptStatus] &= ~data;
		usb_ohci_interrupts();
		return;
	}
	if (offset == HcInterruptEnable) {
		ohcist.hc_regs[HcInterruptEnable] |= data;
		usb_ohci_interrupts();
		return;
	}
	if (offset == HcInterruptDisable) {
		ohcist.hc_regs[HcInterruptEnable] &= ~data;
		usb_ohci_interrupts();
		return;
	}
	if (offset >= HcRhPortStatus1) {
		int port = offset - HcRhPortStatus1 + 1; // port 0 not used
												 // bit 0  R:CurrentConnectStatus           W:ClearPortEnable: 1 clears PortEnableStatus
		if (data & CCS) {
			ohcist.hc_regs[offset] &= ~PES;
			ohcist.address[ohcist.ports[port].address].port = -1;
		}
		// bit 1  R:PortEnableStatus               W:SetPortEnable: 1 sets PortEnableStatus
		if (data & PES) {
			ohcist.hc_regs[offset] |= PES;
			// the port is enabled, so the device connected to it can communicate on the bus
			ohcist.address[ohcist.ports[port].address].function = ohcist.ports[port].function;
			ohcist.address[ohcist.ports[port].address].port = port;
		}
		// bit 2  R:PortSuspendStatus              W:SetPortSuspend: 1 sets PortSuspendStatus
		if (data & PSS) {
			ohcist.hc_regs[offset] |= PSS;
		}
		// bit 3  R:PortOverCurrentIndicator       W:ClearSuspendStatus: 1 clears PortSuspendStatus
		if (data & POCI) {
			ohcist.hc_regs[offset] &= ~PSS;
		}
		// bit 4  R: PortResetStatus               W:SetPortReset: 1 sets PortResetStatus
		if (data & PRS) {
			ohcist.hc_regs[offset] |= PRS;
			if (ohcist.ports[port].address >= 0)
				ohcist.address[ohcist.ports[port].address].port = -1;
			ohcist.ports[port].address = 0;
			if (ohcist.hc_regs[offset] & PES)
			{
				ohcist.address[0].function = ohcist.ports[port].function;
				ohcist.address[0].port = port;
			}
			ohcist.ports[port].function->execute_reset();
			// after 10ms set PortResetStatusChange and clear PortResetStatus and set PortEnableStatus
			ohcist.ports[port].delay = 10;
		}
		// bit 8  R:PortPowerStatus                W:SetPortPower: 1 sets PortPowerStatus
		if (data & PPS) {
			ohcist.hc_regs[offset] |= PPS;
		}
		// bit 9  R:LowSpeedDeviceAttached         W:ClearPortPower: 1 clears PortPowerStatus
		if (data & LSDA) {
			ohcist.hc_regs[offset] &= ~PPS;
		}
		// bit 16 R:ConnectStatusChange            W: 1 clears ConnectStatusChange
		if (data & CSC) {
			ohcist.hc_regs[offset] &= ~CSC;
		}
		// bit 17 R:PortEnableStatusChange         W: 1 clears PortEnableStatusChange
		if (data & PESC) {
			ohcist.hc_regs[offset] &= ~PESC;
		}
		// bit 18 R:PortSuspendStatusChange        W: 1 clears PortSuspendStatusChange
		if (data & PSSC) {
			ohcist.hc_regs[offset] &= ~PSSC;
		}
		// bit 19 R:PortOverCurrentIndicatorChange W: 1 clears PortOverCurrentIndicatorChange
		if (data & POCIC) {
			ohcist.hc_regs[offset] &= ~POCIC;
		}
		// bit 20 R:PortResetStatusChange          W: 1 clears PortResetStatusChange
		if (data & PRSC) {
			ohcist.hc_regs[offset] &= ~PRSC;
		}
		if (ohcist.hc_regs[offset] != old)
			ohcist.hc_regs[HcInterruptStatus] |= RootHubStatusChange;
		usb_ohci_interrupts();
		return;
	}
	ohcist.hc_regs[offset] = data;
}

void ohci_usb_controller::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
{
	UINT32 hcca;
	UINT32 plh;
	int changed = 0;
	int list = 1;
	bool cont = false;
	bool retire = false;
	int pid, remain, mps, done;

	hcca = ohcist.hc_regs[HcHCCA];
	if (ohcist.state == UsbOperational) {
		// increment frame number
		ohcist.framenumber = (ohcist.framenumber + 1) & 0xffff;
		ohcist.space->write_dword(hcca + 0x80, ohcist.framenumber);
		ohcist.hc_regs[HcFmNumber] = ohcist.framenumber;
	}
	// port reset delay
	for (int p = 1; p <= 4; p++) {
		if (ohcist.ports[p].delay > 0) {
			ohcist.ports[p].delay--;
			if (ohcist.ports[p].delay == 0) {
				ohcist.hc_regs[HcRhPortStatus1 + p - 1] = (ohcist.hc_regs[HcRhPortStatus1 + p - 1] & ~PRS) | PRSC | PES;
				ohcist.address[ohcist.ports[p].address].function = ohcist.ports[p].function;
				ohcist.address[ohcist.ports[p].address].port = p;
				changed = 1;
			}
		}
	}
	if (ohcist.state == UsbOperational) {
		while (list >= 0)
		{
			// select list, do transfer
			if (list == 0) {
				if (ohcist.hc_regs[HcControl] & PLE) {
					// periodic list
					plh = ohcist.space->read_dword(hcca + (ohcist.framenumber & 0x1f) * 4);
					cont = true;
					while (cont == true) {
						if (plh != 0) {
							usb_ohci_read_endpoint_descriptor(plh);
							// if this an isochronous endpoint and isochronous list not enabled, stop list processing
							if (((ohcist.hc_regs[HcControl] & IE) == 0) && (ohcist.endpoint_descriptor.f == 1))
								cont = false;
						}
						else
							cont = false;
						if (cont == false)
							break;
						// service endpoint descriptor
						// only if it is not halted and not to be skipped
						if (!(ohcist.endpoint_descriptor.h | ohcist.endpoint_descriptor.k)) {
							// compare the Endpoint Descriptor TailPointer and NextTransferDescriptor fields.
							if (ohcist.endpoint_descriptor.headp != ohcist.endpoint_descriptor.tailp) {
								UINT32 a, b;
								int R = 0;

								// service transfer descriptor
								if (ohcist.endpoint_descriptor.f != 1) {
									usb_ohci_read_transfer_descriptor(ohcist.endpoint_descriptor.headp);
									// get pid
									if (ohcist.endpoint_descriptor.d == 1)
										pid = OutPid; // out
									else if (ohcist.endpoint_descriptor.d == 2)
										pid = InPid; // in
									else {
										pid = ohcist.transfer_descriptor.dp; // 0 setup 1 out 2 in
									}
									a = ohcist.transfer_descriptor.be;
									b = ohcist.transfer_descriptor.cbp;
								}
								else {
									usb_ohci_read_isochronous_transfer_descriptor(ohcist.endpoint_descriptor.headp);
									// get pid
									if (ohcist.endpoint_descriptor.d == 1)
										pid = OutPid; // out
									else if (ohcist.endpoint_descriptor.d == 2)
										pid = InPid; // in
									else
										pid = InPid; // in
									R = (int)ohcist.framenumber - (int)ohcist.isochronous_transfer_descriptor.sf;
									//if ((R < 0) || (R > (int)ohcist.isochronous_transfer_descriptor.fc))
									//	; // greater than fc should be an error
									if (R == (int)ohcist.isochronous_transfer_descriptor.fc)
										a = ohcist.isochronous_transfer_descriptor.be;
									else {
										a = ohcist.isochronous_transfer_descriptor.offset[R + 1] - 1;
										if (a & (1 << 12))
											a = (ohcist.isochronous_transfer_descriptor.be & 0xfffff000) | (a & 0xfff);
										else
											a = ohcist.isochronous_transfer_descriptor.bp0 | (a & 0xfff);
									}
									b = ohcist.isochronous_transfer_descriptor.offset[R];
									if (b & (1 << 12))
										b = (ohcist.isochronous_transfer_descriptor.be & 0xfffff000) | (b & 0xfff);
									else
										b = ohcist.isochronous_transfer_descriptor.bp0 | (b & 0xfff);
								}
								if ((a ^ b) & 0xfffff000)
									remain = ((a | 0x1000) & 0x1fff) - (b & 0xfff) + 1;
								else
									remain = a - b + 1;
								mps = ohcist.endpoint_descriptor.mps;
								if (remain < mps)
									mps = remain;
								// if sending ...
								if (pid != InPid) {
									// ... get mps bytes
									for (int c = 0; c < remain; c++) {
										ohcist.buffer[c] = ohcist.space->read_byte(b);
										b++;
										if ((b & 0xfff) == 0)
											b = ohcist.transfer_descriptor.be & 0xfffff000;
									}
								}
								// should check for time available
								// execute transaction
								done = ohcist.address[ohcist.endpoint_descriptor.fa].function->execute_transfer(ohcist.endpoint_descriptor.en, pid, ohcist.buffer, mps);
								// if receiving ...
								if (pid == InPid) {
									// ... store done bytes
									for (int c = 0; c < done; c++) {
										ohcist.space->write_byte(b, ohcist.buffer[c]);
										b++;
										if ((b & 0xfff) == 0)
											b = a & 0xfffff000;
									}
								}
								if (ohcist.endpoint_descriptor.f != 1) {
									// status writeback (CompletionCode field, DataToggleControl field, CurrentBufferPointer field, ErrorCount field)
									ohcist.transfer_descriptor.cc = NoError;
									ohcist.transfer_descriptor.t = (ohcist.transfer_descriptor.t ^ 1) | 2;
									// if all data is transferred (or there was no data to transfer) cbp must be 0, otherwise it must be updated
									if (done == remain)
										b = 0;
									ohcist.transfer_descriptor.cbp = b;
									ohcist.transfer_descriptor.ec = 0;
									retire = false;
									if ((done == mps) && (done == remain)) {
										retire = true;
									}
									if ((done != mps) && (done <= remain))
										retire = true;
									if (done == 0)
										retire = true;
									if (retire == true) {
										// retire transfer descriptor
										a = ohcist.endpoint_descriptor.headp;
										ohcist.endpoint_descriptor.headp = ohcist.transfer_descriptor.nexttd;
										ohcist.transfer_descriptor.nexttd = ohcist.hc_regs[HcDoneHead];
										ohcist.hc_regs[HcDoneHead] = a;
										ohcist.endpoint_descriptor.c = ohcist.transfer_descriptor.t & 1;
										if (ohcist.transfer_descriptor.di != 7) {
											if (ohcist.transfer_descriptor.di < ohcist.writebackdonehadcounter)
												ohcist.writebackdonehadcounter = ohcist.transfer_descriptor.di;
										}
										usb_ohci_writeback_transfer_descriptor(a);
										usb_ohci_writeback_endpoint_descriptor(plh);
									}
									else {
										usb_ohci_writeback_transfer_descriptor(ohcist.endpoint_descriptor.headp);
									}
								}
								else
								{
									// status writeback
									ohcist.isochronous_transfer_descriptor.cc = NoError;
									if (done == remain)
										b = 0;
									ohcist.isochronous_transfer_descriptor.offset[R] = b;
									retire = false;
									if ((done == mps) && (done == remain)) {
										retire = true;
									}
									if ((done != mps) && (done <= remain))
										retire = true;
									if (done == 0)
										retire = true;
									if (retire == true) {
										// retire transfer descriptor
									}
									else {
										usb_ohci_writeback_isochronous_transfer_descriptor(ohcist.endpoint_descriptor.headp);
									}
								}
							}
						}
						// go to next endpoint
						if (ohcist.endpoint_descriptor.nexted != 0)
						{
							plh = ohcist.endpoint_descriptor.nexted;
						}
						else
							cont = false;
					}
				}
				list = -1;
			}
			if (list == 1) {
				// control list
				// check if control list active
				if (ohcist.hc_regs[HcControl] & CLE) {
					cont = true;
					while (cont == true) {
						// if current endpoint descriptor is not 0 use it, otherwise ...
						if (ohcist.hc_regs[HcControlCurrentED] == 0) {
							// ... check the filled bit ...
							if (ohcist.hc_regs[HcCommandStatus] & (1 << 1)) {
								// ... if 1 start processing from the head of the list
								ohcist.hc_regs[HcControlCurrentED] = ohcist.hc_regs[HcControlHeadED];
								// clear CLF (ControlListFilled)
								ohcist.hc_regs[HcCommandStatus] &= ~(1 << 1);
								// but if the list is empty, go to the next list
								if (ohcist.hc_regs[HcControlCurrentED] == 0)
									cont = false;
								else
									cont = true;
							}
							else
								cont = false;
						}
						else
							cont = true;
						if (cont == false)
							break;
						// service endpoint descriptor
						usb_ohci_read_endpoint_descriptor(ohcist.hc_regs[HcControlCurrentED]);
						// only if it is not halted and not to be skipped
						if (!(ohcist.endpoint_descriptor.h | ohcist.endpoint_descriptor.k)) {
							// compare the Endpoint Descriptor TailPointer and NextTransferDescriptor fields.
							if (ohcist.endpoint_descriptor.headp != ohcist.endpoint_descriptor.tailp) {
								UINT32 a, b;
								// set CLF (ControlListFilled)
								ohcist.hc_regs[HcCommandStatus] |= (1 << 1);
								// service transfer descriptor
								usb_ohci_read_transfer_descriptor(ohcist.endpoint_descriptor.headp);
								// get pid
								if (ohcist.endpoint_descriptor.d == 1)
									pid = OutPid; // out
								else if (ohcist.endpoint_descriptor.d == 2)
									pid = InPid; // in
								else {
									pid = ohcist.transfer_descriptor.dp; // 0 setup 1 out 2 in
								}
								// determine how much data to transfer
								// setup pid must be 8 bytes
								a = ohcist.transfer_descriptor.be & 0xfff;
								b = ohcist.transfer_descriptor.cbp & 0xfff;
								if ((ohcist.transfer_descriptor.be ^ ohcist.transfer_descriptor.cbp) & 0xfffff000)
									a |= 0x1000;
								remain = a - b + 1;
								mps = ohcist.endpoint_descriptor.mps;
								if ((pid == InPid) || (pid == OutPid)) {
									if (remain < mps)
										mps = remain;
								}
								if (ohcist.transfer_descriptor.cbp == 0) {
									remain = 0;
									mps = 0;
								}
								b = ohcist.transfer_descriptor.cbp;
								// if sending ...
								if (pid != InPid) {
									// ... get mps bytes
									for (int c = 0; c < remain; c++) {
										ohcist.buffer[c] = ohcist.space->read_byte(b);
										b++;
										if ((b & 0xfff) == 0)
											b = ohcist.transfer_descriptor.be & 0xfffff000;
									}
								}
								// should check for time available
								// execute transaction
								done = ohcist.address[ohcist.endpoint_descriptor.fa].function->execute_transfer(ohcist.endpoint_descriptor.en, pid, ohcist.buffer, mps);
								// if receiving ...
								if (pid == InPid) {
									// ... store done bytes
									for (int c = 0; c < done; c++) {
										ohcist.space->write_byte(b, ohcist.buffer[c]);
										b++;
										if ((b & 0xfff) == 0)
											b = ohcist.transfer_descriptor.be & 0xfffff000;
									}
								}
								// status writeback (CompletionCode field, DataToggleControl field, CurrentBufferPointer field, ErrorCount field)
								ohcist.transfer_descriptor.cc = NoError;
								ohcist.transfer_descriptor.t = (ohcist.transfer_descriptor.t ^ 1) | 2;
								// if all data is transferred (or there was no data to transfer) cbp must be 0, otherwise it must be updated
								if ((done == remain) || (pid == SetupPid))
									b = 0;
								ohcist.transfer_descriptor.cbp = b;
								ohcist.transfer_descriptor.ec = 0;
								retire = false;
								if ((done == mps) && (done == remain)) {
									retire = true;
								}
								if ((done != mps) && (done <= remain))
									retire = true;
								if (done == 0)
									retire = true;
								if (retire == true) {
									// retire transfer descriptor
									a = ohcist.endpoint_descriptor.headp;
									ohcist.endpoint_descriptor.headp = ohcist.transfer_descriptor.nexttd;
									ohcist.transfer_descriptor.nexttd = ohcist.hc_regs[HcDoneHead];
									ohcist.hc_regs[HcDoneHead] = a;
									ohcist.endpoint_descriptor.c = ohcist.transfer_descriptor.t & 1;
									if (ohcist.transfer_descriptor.di != 7) {
										if (ohcist.transfer_descriptor.di < ohcist.writebackdonehadcounter)
											ohcist.writebackdonehadcounter = ohcist.transfer_descriptor.di;
									}
									usb_ohci_writeback_transfer_descriptor(a);
									usb_ohci_writeback_endpoint_descriptor(ohcist.hc_regs[HcControlCurrentED]);
								}
								else {
									usb_ohci_writeback_transfer_descriptor(ohcist.endpoint_descriptor.headp);
								}
							}
							else {
								// no transfer descriptors for this endpoint, so go to next endpoint
								ohcist.hc_regs[HcControlCurrentED] = ohcist.endpoint_descriptor.nexted;
							}
						}
						else {
							// not enabled, so go to next endpoint
							ohcist.hc_regs[HcControlCurrentED] = ohcist.endpoint_descriptor.nexted;
						}
						// one bulk every n control transfers
						ohcist.interruptbulkratio--;
						if (ohcist.interruptbulkratio <= 0) {
							ohcist.interruptbulkratio = (ohcist.hc_regs[HcControl] & 3) + 1; // ControlBulkServiceRatio
							cont = false;
						}
					}
				}
				list = 2;
			}
			if (list == 2) {
				// bulk list
				// check if bulk list active
				if (ohcist.hc_regs[HcControl] & BLE) {
					// if current endpoint descriptor is not 0 use it, otherwise ...
					if (ohcist.hc_regs[HcBulkCurrentED] == 0) {
						// ... check the filled bit ...
						if (ohcist.hc_regs[HcCommandStatus] & (1 << 2)) {
							// ... if 1 start processing from the head of the list
							ohcist.hc_regs[HcBulkCurrentED] = ohcist.hc_regs[HcBulkHeadED];
							// clear BLF (BulkListFilled)
							ohcist.hc_regs[HcCommandStatus] &= ~(1 << 2);
							// but if the list is empty, go to the next list
							if (ohcist.hc_regs[HcBulkCurrentED] == 0)
								cont = false;
							else
								cont = true;
						}
						else
							cont = false;
					}
					else
						cont = true;
					if (cont == true) {
						// service endpoint descriptor
						usb_ohci_read_endpoint_descriptor(ohcist.hc_regs[HcBulkCurrentED]);
						// only if it is not halted and not to be skipped
						if (!(ohcist.endpoint_descriptor.h | ohcist.endpoint_descriptor.k)) {
							// compare the Endpoint Descriptor TailPointer and NextTransferDescriptor fields.
							if (ohcist.endpoint_descriptor.headp != ohcist.endpoint_descriptor.tailp) {
								UINT32 a, b;
								// set BLF (BulkListFilled)
								ohcist.hc_regs[HcCommandStatus] |= (1 << 2);
								// service transfer descriptor
								usb_ohci_read_transfer_descriptor(ohcist.endpoint_descriptor.headp);
								// get pid
								if (ohcist.endpoint_descriptor.d == 1)
									pid = OutPid; // out
								else if (ohcist.endpoint_descriptor.d == 2)
									pid = InPid; // in
								else {
									pid = ohcist.transfer_descriptor.dp; // 0 setup 1 out 2 in
								}
								// determine how much data to transfer
								a = ohcist.transfer_descriptor.be & 0xfff;
								b = ohcist.transfer_descriptor.cbp & 0xfff;
								if ((ohcist.transfer_descriptor.be ^ ohcist.transfer_descriptor.cbp) & 0xfffff000)
									a |= 0x1000;
								remain = a - b + 1;
								mps = ohcist.endpoint_descriptor.mps;
								if (remain < mps)
									mps = remain;
								b = ohcist.transfer_descriptor.cbp;
								// if sending ...
								if (pid != InPid) {
									// ... get mps bytes
									for (int c = 0; c < remain; c++) {
										ohcist.buffer[c] = ohcist.space->read_byte(b);
										b++;
										if ((b & 0xfff) == 0)
											b = ohcist.transfer_descriptor.be & 0xfffff000;
									}
								}
								// should check for time available
								// execute transaction
								done = ohcist.address[ohcist.endpoint_descriptor.fa].function->execute_transfer(ohcist.endpoint_descriptor.en, pid, ohcist.buffer, mps);
								// if receiving ...
								if (pid == InPid) {
									// ... store done bytes
									for (int c = 0; c < done; c++) {
										ohcist.space->write_byte(b, ohcist.buffer[c]);
										b++;
										if ((b & 0xfff) == 0)
											b = ohcist.transfer_descriptor.be & 0xfffff000;
									}
								}
								// status writeback (CompletionCode field, DataToggleControl field, CurrentBufferPointer field, ErrorCount field)
								ohcist.transfer_descriptor.cc = NoError;
								ohcist.transfer_descriptor.t = (ohcist.transfer_descriptor.t ^ 1) | 2;
								// if all data is transferred (or there was no data to transfer) cbp must be 0, otherwise it must be updated
								if (done == remain)
									b = 0;
								ohcist.transfer_descriptor.cbp = b;
								ohcist.transfer_descriptor.ec = 0;
								retire = false;
								if ((done == mps) && (done == remain)) {
									retire = true;
								}
								if ((done != mps) && (done <= remain))
									retire = true;
								if (done == 0)
									retire = true;
								if (retire == true) {
									// retire transfer descriptor
									a = ohcist.endpoint_descriptor.headp;
									ohcist.endpoint_descriptor.headp = ohcist.transfer_descriptor.nexttd;
									ohcist.transfer_descriptor.nexttd = ohcist.hc_regs[HcDoneHead];
									ohcist.hc_regs[HcDoneHead] = a;
									ohcist.endpoint_descriptor.c = ohcist.transfer_descriptor.t & 1;
									if (ohcist.transfer_descriptor.di != 7) {
										if (ohcist.transfer_descriptor.di < ohcist.writebackdonehadcounter)
											ohcist.writebackdonehadcounter = ohcist.transfer_descriptor.di;
									}
									usb_ohci_writeback_transfer_descriptor(a);
									usb_ohci_writeback_endpoint_descriptor(ohcist.hc_regs[HcBulkCurrentED]);
								}
								else {
									usb_ohci_writeback_transfer_descriptor(ohcist.endpoint_descriptor.headp);
								}
							}
							else {
								// no transfer descriptors for this endpoint, so go to next endpoint
								ohcist.hc_regs[HcBulkCurrentED] = ohcist.endpoint_descriptor.nexted;
							}
						}
						else {
							// not enabled, so go to next endpoint
							ohcist.hc_regs[HcBulkCurrentED] = ohcist.endpoint_descriptor.nexted;
						}
					}
					// go to the next list
					if ((ohcist.hc_regs[HcCommandStatus] & (1 << 1)) && (ohcist.hc_regs[HcControl] & CLE))
						list = 1; // go to control list if enabled and filled
					else if ((ohcist.hc_regs[HcCommandStatus] & (1 << 2)) && (ohcist.hc_regs[HcControl] & BLE))
						list = 2; // otherwise stay in bulk list if enabled and filled
					else
						list = 0; // if no control or bulk lists, go to periodic list
				}
			}
		}
		if (ohcist.framenumber == 0)
			ohcist.hc_regs[HcInterruptStatus] |= FrameNumberOverflow;
		ohcist.hc_regs[HcInterruptStatus] |= StartofFrame;
		if ((ohcist.writebackdonehadcounter != 0) && (ohcist.writebackdonehadcounter != 7))
			ohcist.writebackdonehadcounter--;
		if ((ohcist.writebackdonehadcounter == 0) && ((ohcist.hc_regs[HcInterruptStatus] & WritebackDoneHead) == 0)) {
			UINT32 b = 0;

			if ((ohcist.hc_regs[HcInterruptStatus] & ohcist.hc_regs[HcInterruptEnable]) != WritebackDoneHead)
				b = 1;
			ohcist.hc_regs[HcInterruptStatus] |= WritebackDoneHead;
			ohcist.space->write_dword(hcca + 0x84, ohcist.hc_regs[HcDoneHead] | b);
			ohcist.hc_regs[HcDoneHead] = 0;
			ohcist.writebackdonehadcounter = 7;
		}
	}
	if (changed != 0) {
		ohcist.hc_regs[HcInterruptStatus] |= RootHubStatusChange;
	}
	usb_ohci_interrupts();
}

void ohci_usb_controller::usb_ohci_plug(int port, ohci_function_device *function)
{
	if ((port > 0) && (port <= 4)) {
		ohcist.ports[port].function = function;
		ohcist.ports[port].address = -1;
		ohcist.hc_regs[HcRhPortStatus1 + port - 1] = CCS | CSC;
		if (ohcist.state != UsbReset)
		{
			ohcist.hc_regs[HcInterruptStatus] |= RootHubStatusChange;
			usb_ohci_interrupts();
		}
	}
}

void ohci_usb_controller::usb_ohci_interrupts()
{
	if (((ohcist.hc_regs[HcInterruptStatus] & ohcist.hc_regs[HcInterruptEnable]) != 0) && ((ohcist.hc_regs[HcInterruptEnable] & MasterInterruptEnable) != 0)) 
	{
		//pic8259_1->ir1_w(1);
		m_interrupt_handler(1);
	} else 
	{
		//pic8259_1->ir1_w(0);
		m_interrupt_handler(0);
	}
}

void ohci_usb_controller::usb_ohci_read_endpoint_descriptor(UINT32 address)
{
	UINT32 w;

	w = ohcist.space->read_dword(address);
	ohcist.endpoint_descriptor.word0 = w;
	ohcist.endpoint_descriptor.fa = w & 0x7f;
	ohcist.endpoint_descriptor.en = (w >> 7) & 15;
	ohcist.endpoint_descriptor.d = (w >> 11) & 3;
	ohcist.endpoint_descriptor.s = (w >> 13) & 1;
	ohcist.endpoint_descriptor.k = (w >> 14) & 1;
	ohcist.endpoint_descriptor.f = (w >> 15) & 1;
	ohcist.endpoint_descriptor.mps = (w >> 16) & 0x7ff;
	ohcist.endpoint_descriptor.tailp = ohcist.space->read_dword(address + 4);
	w = ohcist.space->read_dword(address + 8);
	ohcist.endpoint_descriptor.headp = w & 0xfffffffc;
	ohcist.endpoint_descriptor.h = w & 1;
	ohcist.endpoint_descriptor.c = (w >> 1) & 1;
	ohcist.endpoint_descriptor.nexted = ohcist.space->read_dword(address + 12);
}

void ohci_usb_controller::usb_ohci_writeback_endpoint_descriptor(UINT32 address)
{
	UINT32 w;

	w = ohcist.endpoint_descriptor.word0 & 0xf8000000;
	w = w | (ohcist.endpoint_descriptor.mps << 16) | (ohcist.endpoint_descriptor.f << 15) | (ohcist.endpoint_descriptor.k << 14) | (ohcist.endpoint_descriptor.s << 13) | (ohcist.endpoint_descriptor.d << 11) | (ohcist.endpoint_descriptor.en << 7) | ohcist.endpoint_descriptor.fa;
	ohcist.space->write_dword(address, w);
	w = ohcist.endpoint_descriptor.headp | (ohcist.endpoint_descriptor.c << 1) | ohcist.endpoint_descriptor.h;
	ohcist.space->write_dword(address + 8, w);
}

void ohci_usb_controller::usb_ohci_read_transfer_descriptor(UINT32 address)
{
	UINT32 w;

	w = ohcist.space->read_dword(address);
	ohcist.transfer_descriptor.word0 = w;
	ohcist.transfer_descriptor.cc = (w >> 28) & 15;
	ohcist.transfer_descriptor.ec = (w >> 26) & 3;
	ohcist.transfer_descriptor.t = (w >> 24) & 3;
	ohcist.transfer_descriptor.di = (w >> 21) & 7;
	ohcist.transfer_descriptor.dp = (w >> 19) & 3;
	ohcist.transfer_descriptor.r = (w >> 18) & 1;
	ohcist.transfer_descriptor.cbp = ohcist.space->read_dword(address + 4);
	ohcist.transfer_descriptor.nexttd = ohcist.space->read_dword(address + 8);
	ohcist.transfer_descriptor.be = ohcist.space->read_dword(address + 12);
}

void ohci_usb_controller::usb_ohci_writeback_transfer_descriptor(UINT32 address)
{
	UINT32 w;

	w = ohcist.transfer_descriptor.word0 & 0x0003ffff;
	w = w | (ohcist.transfer_descriptor.cc << 28) | (ohcist.transfer_descriptor.ec << 26) | (ohcist.transfer_descriptor.t << 24) | (ohcist.transfer_descriptor.di << 21) | (ohcist.transfer_descriptor.dp << 19) | (ohcist.transfer_descriptor.r << 18);
	ohcist.space->write_dword(address, w);
	ohcist.space->write_dword(address + 4, ohcist.transfer_descriptor.cbp);
	ohcist.space->write_dword(address + 8, ohcist.transfer_descriptor.nexttd);
}

void ohci_usb_controller::usb_ohci_read_isochronous_transfer_descriptor(UINT32 address)
{
	UINT32 w;

	w = ohcist.space->read_dword(address);
	ohcist.isochronous_transfer_descriptor.word0 = w;
	ohcist.isochronous_transfer_descriptor.cc = (w >> 28) & 15;
	ohcist.isochronous_transfer_descriptor.fc = (w >> 24) & 7;
	ohcist.isochronous_transfer_descriptor.di = (w >> 21) & 7;
	ohcist.isochronous_transfer_descriptor.sf = w & 0xffff;
	w = ohcist.space->read_dword(address + 4);
	ohcist.isochronous_transfer_descriptor.word1 = w;
	ohcist.isochronous_transfer_descriptor.bp0 = w & 0xfffff000;
	ohcist.isochronous_transfer_descriptor.nexttd = ohcist.space->read_dword(address + 8);
	ohcist.isochronous_transfer_descriptor.be = ohcist.space->read_dword(address + 12);
	w = ohcist.space->read_dword(address + 16);
	ohcist.isochronous_transfer_descriptor.offset[0] = w & 0xffff;
	ohcist.isochronous_transfer_descriptor.offset[1] = (w >> 16) & 0xffff;
	w = ohcist.space->read_dword(address + 20);
	ohcist.isochronous_transfer_descriptor.offset[2] = w & 0xffff;
	ohcist.isochronous_transfer_descriptor.offset[3] = (w >> 16) & 0xffff;
	w = ohcist.space->read_dword(address + 24);
	ohcist.isochronous_transfer_descriptor.offset[4] = w & 0xffff;
	ohcist.isochronous_transfer_descriptor.offset[5] = (w >> 16) & 0xffff;
	w = ohcist.space->read_dword(address + 28);
	ohcist.isochronous_transfer_descriptor.offset[6] = w & 0xffff;
	ohcist.isochronous_transfer_descriptor.offset[7] = (w >> 16) & 0xffff;
}

void ohci_usb_controller::usb_ohci_writeback_isochronous_transfer_descriptor(UINT32 address)
{
	UINT32 w;

	w = ohcist.isochronous_transfer_descriptor.word0 & 0x1f0000;
	w = w | (ohcist.isochronous_transfer_descriptor.cc << 28) | (ohcist.isochronous_transfer_descriptor.fc << 24) | (ohcist.isochronous_transfer_descriptor.di << 21) | ohcist.isochronous_transfer_descriptor.sf;
	ohcist.space->write_dword(address, w);
	w = ohcist.isochronous_transfer_descriptor.word1 & 0xfff;
	w = w | ohcist.isochronous_transfer_descriptor.bp0;
	ohcist.space->write_dword(address + 4, w);
	ohcist.space->write_dword(address + 8, ohcist.isochronous_transfer_descriptor.nexttd);
	ohcist.space->write_dword(address + 12, ohcist.isochronous_transfer_descriptor.be);
	w = (ohcist.isochronous_transfer_descriptor.offset[1] << 16) | ohcist.isochronous_transfer_descriptor.offset[0];
	ohcist.space->write_dword(address + 16, w);
	w = (ohcist.isochronous_transfer_descriptor.offset[3] << 16) | ohcist.isochronous_transfer_descriptor.offset[2];
	ohcist.space->write_dword(address + 20, w);
	w = (ohcist.isochronous_transfer_descriptor.offset[5] << 16) | ohcist.isochronous_transfer_descriptor.offset[4];
	ohcist.space->write_dword(address + 24, w);
	w = (ohcist.isochronous_transfer_descriptor.offset[7] << 16) | ohcist.isochronous_transfer_descriptor.offset[6];
	ohcist.space->write_dword(address + 28, w);
}

void ohci_usb_controller::usb_ohci_device_address_changed(int old_address, int new_address)
{
	ohcist.address[new_address].function = ohcist.address[old_address].function;
	ohcist.address[new_address].port = ohcist.address[old_address].port;
	ohcist.address[old_address].port = -1;
}

/*
* ohci device base class
*/

ohci_function_device::ohci_function_device()
{
}

void ohci_function_device::initialize(running_machine &machine, ohci_usb_controller *usb_bus_manager)
{
	busmanager = usb_bus_manager;
	state = DefaultState;
	descriptors = auto_alloc_array(machine, UINT8, 1024);
	descriptors_pos = 0;
	address = 0;
	newaddress = 0;
	for (int e = 0; e < 256;e++) {
		endpoints[e].type = -1;
		endpoints[e].controldirection = 0;
		endpoints[e].controltype = 0;
		endpoints[e].controlrecipient = 0;
		endpoints[e].remain = 0;
		endpoints[e].position = nullptr;
	}
	endpoints[0].type = ControlEndpoint;
	wantstatuscallback = false;
	settingaddress = false;
	configurationvalue = 0;
	selected_configuration = nullptr;
	latest_configuration = nullptr;
	latest_alternate = nullptr;
}

void ohci_function_device::add_device_descriptor(const USBStandardDeviceDescriptor &descriptor)
{
	UINT8 *p = descriptors + descriptors_pos;

	p[0] = descriptor.bLength;
	p[1] = descriptor.bDescriptorType;
	p[2] = descriptor.bcdUSB & 255;
	p[3] = descriptor.bcdUSB >> 8;
	p[4] = descriptor.bDeviceClass;
	p[5] = descriptor.bDeviceSubClass;
	p[6] = descriptor.bDeviceProtocol;
	p[7] = descriptor.bMaxPacketSize0;
	p[8] = descriptor.idVendor & 255;
	p[9] = descriptor.idVendor >> 8;
	p[10] = descriptor.idProduct & 255;
	p[11] = descriptor.idProduct >> 8;
	p[12] = descriptor.bcdDevice & 255;
	p[13] = descriptor.bcdDevice >> 8;
	p[14] = descriptor.iManufacturer;
	p[15] = descriptor.iProduct;
	p[16] = descriptor.iSerialNumber;
	p[17] = descriptor.bNumConfigurations;
	descriptors_pos += descriptor.bLength;
	memcpy(&device_descriptor, &descriptor, sizeof(USBStandardDeviceDescriptor));
}

void ohci_function_device::add_configuration_descriptor(const USBStandardConfigurationDescriptor &descriptor)
{
	usb_device_configuration *c = new usb_device_configuration;
	UINT8 *p = descriptors + descriptors_pos;

	p[0] = descriptor.bLength;
	p[1] = descriptor.bDescriptorType;
	p[2] = descriptor.wTotalLength & 255;
	p[3] = descriptor.wTotalLength >> 8;
	p[4] = descriptor.bNumInterfaces;
	p[5] = descriptor.bConfigurationValue;
	p[6] = descriptor.iConfiguration;
	p[7] = descriptor.bmAttributes;
	p[8] = descriptor.MaxPower;
	c->position = p;
	c->size = descriptor.bLength;
	descriptors_pos += descriptor.bLength;
	memcpy(&c->configuration_descriptor, &descriptor, sizeof(USBStandardConfigurationDescriptor));
	configurations.push_front(c);
	latest_configuration = c;
	latest_alternate = nullptr;
}

void ohci_function_device::add_interface_descriptor(const USBStandardInterfaceDescriptor &descriptor)
{
	usb_device_interface *ii;
	usb_device_interface_alternate *aa;
	UINT8 *p = descriptors + descriptors_pos;

	if (latest_configuration == nullptr)
		return;
	p[0] = descriptor.bLength;
	p[1] = descriptor.bDescriptorType;
	p[2] = descriptor.bInterfaceNumber;
	p[3] = descriptor.bAlternateSetting;
	p[4] = descriptor.bNumEndpoints;
	p[5] = descriptor.bInterfaceClass;
	p[6] = descriptor.bInterfaceSubClass;
	p[7] = descriptor.bInterfaceProtocol;
	p[8] = descriptor.iInterface;
	descriptors_pos += descriptor.bLength;
	latest_configuration->size += descriptor.bLength;
	for (auto i = latest_configuration->interfaces.begin(); i != latest_configuration->interfaces.end(); ++i)
	{
		if ((*i)->alternate_settings.front()->interface_descriptor.bInterfaceNumber == descriptor.bInterfaceNumber)
		{
			(*i)->size += descriptor.bLength;
			latest_configuration->interfaces.front()->size += descriptor.bLength;
			aa = new usb_device_interface_alternate;
			memcpy(&aa->interface_descriptor, &descriptor, sizeof(USBStandardInterfaceDescriptor));
			aa->position = p;
			aa->size = descriptor.bLength;
			(*i)->alternate_settings.push_front(aa);
			latest_alternate = aa;
			return;
		}
	}
	ii = new usb_device_interface;
	aa = new usb_device_interface_alternate;
	memcpy(&aa->interface_descriptor, &descriptor, sizeof(USBStandardInterfaceDescriptor));
	aa->position = p;
	aa->size = descriptor.bLength;
	ii->position = p;
	ii->size = descriptor.bLength;
	ii->selected_alternate = -1;
	ii->alternate_settings.push_front(aa);
	latest_alternate = aa;
	latest_configuration->interfaces.push_front(ii);
}

void ohci_function_device::add_endpoint_descriptor(const USBStandardEndpointDescriptor &descriptor)
{
	UINT8 *p = descriptors + descriptors_pos;

	if (latest_alternate == nullptr)
		return;
	p[0] = descriptor.bLength;
	p[1] = descriptor.bDescriptorType;
	p[2] = descriptor.bEndpointAddress;
	p[3] = descriptor.bmAttributes;
	p[4] = descriptor.wMaxPacketSize & 255;
	p[5] = descriptor.wMaxPacketSize >> 8;
	p[6] = descriptor.bInterval;
	descriptors_pos += descriptor.bLength;
	latest_alternate->endpoint_descriptors.push_front(descriptor);
	latest_alternate->size += descriptor.bLength;
	latest_configuration->interfaces.front()->size += descriptor.bLength;
	latest_configuration->size += descriptor.bLength;
}

void ohci_function_device::add_string_descriptor(const UINT8 *descriptor)
{
	usb_device_string *ss;
	int len = descriptor[0];
	UINT8 *p = descriptors + descriptors_pos;


	ss = new usb_device_string;
	memcpy(p, descriptor, len);
	descriptors_pos += len;
	ss->size = len;
	ss->position = p;
	device_strings.push_front(ss);
	//latest_configuration->size += len;
}

void ohci_function_device::select_configuration(int index)
{
	configurationvalue = index;
	for (auto c = configurations.begin(); c != configurations.end(); ++c)
	{
		if ((*c)->configuration_descriptor.bConfigurationValue == index)
		{
			selected_configuration = *c;
			// by default, activate alternate setting 0 in each interface
			for (auto i = (*c)->interfaces.begin(); i != (*c)->interfaces.end(); ++i)
			{
				(*i)->selected_alternate = 0;
				for (auto a = (*i)->alternate_settings.begin(); a != (*i)->alternate_settings.end(); ++a)
				{
					if ((*a)->interface_descriptor.bAlternateSetting == 0)
					{
						// activate the endpoints in interface i alternate setting 0
						for (auto e = (*a)->endpoint_descriptors.begin(); e != (*a)->endpoint_descriptors.end(); ++e)
						{
							endpoints[e->bEndpointAddress].type = e->bmAttributes & 3;
							endpoints[e->bEndpointAddress].remain = 0;
						}
						break;
					}
				}
			}
			break;
		}
	}
}

void ohci_function_device::select_alternate(int interfacei, int index)
{
	// among all the interfaces in the currently selected configuration, consider interface interfacei
	for (auto i = selected_configuration->interfaces.begin(); i != selected_configuration->interfaces.end(); ++i)
	{
		// deactivate the endpoints in the currently selected alternate setting for interface interfacei
		for (auto a = (*i)->alternate_settings.begin(); a != (*i)->alternate_settings.end(); ++a)
		{
			if (((*a)->interface_descriptor.bInterfaceNumber == interfacei) && ((*a)->interface_descriptor.bAlternateSetting == (*i)->selected_alternate))
			{
				for (auto e = (*a)->endpoint_descriptors.begin(); e != (*a)->endpoint_descriptors.end(); ++e)
				{
					endpoints[e->bEndpointAddress].type = -1;
				}
				break;
			}
		}
		// activate the endpoints in the newly selected alternate setting
		for (auto a = (*i)->alternate_settings.begin(); a != (*i)->alternate_settings.end(); ++a)
		{
			if (((*a)->interface_descriptor.bInterfaceNumber == interfacei) && ((*a)->interface_descriptor.bAlternateSetting == index))
			{
				(*i)->selected_alternate = index;
				for (auto e = (*a)->endpoint_descriptors.begin(); e != (*a)->endpoint_descriptors.end(); ++e)
				{
					endpoints[e->bEndpointAddress].type = e->bmAttributes & 3;
					endpoints[e->bEndpointAddress].remain = 0;
				}
				break;
			}
		}
	}
}

int ohci_function_device::find_alternate(int interfacei)
{
	// find the active alternate setting for interface inteerfacei
	for (auto i = selected_configuration->interfaces.begin(); i != selected_configuration->interfaces.end(); ++i)
	{
		for (auto a = (*i)->alternate_settings.begin(); a != (*i)->alternate_settings.end(); ++a)
		{
			if ((*a)->interface_descriptor.bInterfaceNumber == interfacei)
			{
				return (*i)->selected_alternate;
			}
		}
	}
	return 0;
}

UINT8 *ohci_function_device::position_device_descriptor(int &size)
{
	size = descriptors_pos; // descriptors[0];
	return descriptors;
}

UINT8 *ohci_function_device::position_configuration_descriptor(int index, int &size)
{
	for (auto c = configurations.begin(); c != configurations.end(); ++c)
	{
		if ((*c)->configuration_descriptor.bConfigurationValue == (index + 1))
		{
			size = (*c)->size;
			return (*c)->position;
		}
	}
	size = 0;
	return nullptr;
}

UINT8 *ohci_function_device::position_string_descriptor(int index, int &size)
{
	int i = 0;

	for (auto s = device_strings.begin(); s != device_strings.end(); ++s)
	{
		if (index == i)
		{
			size = (*s)->size;
			return (*s)->position;
		}
		i++;
	}
	size = 0;
	return nullptr;
}

void ohci_function_device::execute_reset()
{
	address = 0;
	newaddress = 0;
}

int ohci_function_device::execute_transfer(int endpoint, int pid, UINT8 *buffer, int size)
{
	int descriptortype, descriptorindex;

	if (pid == SetupPid) {
		USBSetupPacket *p=(USBSetupPacket *)buffer;
		// control transfers are done in 3 stages: first the setup stage, then an optional data stage, then a status stage
		// so there are 3 cases:
		// 1- control transfer with a data stage where the host sends data to the device
		//    in this case the sequence of pids transferred is control pid, data out pid, data in pid
		// 2- control transfer with a data stage where the host receives data from the device
		//    in this case the sequence of pids transferred is control pid, data in pid, data out pid
		// 3- control transfer without a data stage
		//    in this case the sequence of pids transferred is control pid, data in pid
		// define direction 0:host->device 1:device->host
		// direction == 1 -> IN data stage and OUT status stage
		// direction == 0 -> OUT data stage and IN status stage
		// data stage not present -> IN status stage
		endpoints[endpoint].controldirection = (p->bmRequestType & 128) >> 7;
		endpoints[endpoint].controltype = (p->bmRequestType & 0x60) >> 5;
		endpoints[endpoint].controlrecipient = p->bmRequestType & 0x1f;
		wantstatuscallback = false;
		if (endpoint == 0) {
			endpoints[endpoint].position = nullptr;
			// number of byte to transfer in data stage (0 no data stage)
			endpoints[endpoint].remain = p->wLength;
			// if standard device request
			if ((endpoints[endpoint].controltype == StandardType) && (endpoints[endpoint].controlrecipient == DeviceRecipient)) {
				switch (p->bRequest) {
				case GET_STATUS:
					return handle_get_status_request(endpoint, p);
					break;
				case CLEAR_FEATURE:
					return handle_clear_feature_request(endpoint, p);
					break;
				case SET_FEATURE:
					return handle_set_feature_request(endpoint, p);
					break;
				case SET_ADDRESS:
					newaddress = p->wValue;
					settingaddress = true;
					break;
				case GET_DESCRIPTOR:
					descriptortype = p->wValue >> 8;
					descriptorindex = p->wValue & 255;
					if (descriptortype == DEVICE) { // device descriptor
						endpoints[endpoint].position = position_device_descriptor(endpoints[endpoint].remain);
					}
					else if (descriptortype == CONFIGURATION) { // configuration descriptor
						endpoints[endpoint].position = position_configuration_descriptor(descriptorindex, endpoints[endpoint].remain);
					}
					else if (descriptortype == STRING) { // string descriptor
						//p->wIndex; language id
						endpoints[endpoint].position = position_string_descriptor(descriptorindex, endpoints[endpoint].remain);
					}
					else
						endpoints[endpoint].remain = 0;
					if (endpoints[endpoint].remain > p->wLength)
						endpoints[endpoint].remain = p->wLength;
					break;
				case SET_CONFIGURATION:
					if (p->wValue == 0)
						state = AddressState;
					else {
						select_configuration(p->wValue);
						state = ConfiguredState;
					}
					break;
				case SET_INTERFACE:
					select_alternate(p->wIndex, p->wValue);
					break;
				case SET_DESCRIPTOR:
					return handle_set_descriptor_request(endpoint, p);
					break;
				case GET_CONFIGURATION:
					endpoints[endpoint].buffer[0] = (UINT8)configurationvalue;
					endpoints[endpoint].position = endpoints[endpoint].buffer;
					endpoints[endpoint].remain = 1;
					if (p->wLength == 0)
						endpoints[endpoint].remain = 0;
					break;
				case GET_INTERFACE:
					endpoints[endpoint].buffer[0] = (UINT8)find_alternate(p->wIndex);
					endpoints[endpoint].position = endpoints[endpoint].buffer;
					endpoints[endpoint].remain = 1;
					if (p->wLength == 0)
						endpoints[endpoint].remain = 0;
					break;
				case SYNCH_FRAME:
					return handle_synch_frame_request(endpoint, p);
				default:
					return handle_nonstandard_request(endpoint, p);
					break;
				}
			}
			else
				return handle_nonstandard_request(endpoint, p);
			size = 0;
		}
		else
			return handle_nonstandard_request(endpoint, p);
	}
	else if (pid == InPid) {
		if (endpoints[endpoint].type == ControlEndpoint) { //if (endpoint == 0) {
			// if no data has been transferred (except for the setup stage)
			// and the lenght of this IN transaction is 0
			// assume this is the status stage
			if ((endpoints[endpoint].remain == 0) && (size == 0)) {
				if ((endpoint == 0) && (settingaddress == true))
				{
					// set of address is active at end of status stage
					busmanager->usb_ohci_device_address_changed(address, newaddress);
					address = newaddress;
					settingaddress = false;
					state = AddressState;
				}
				if (wantstatuscallback == true)
					handle_status_stage(endpoint);
				wantstatuscallback = false;
				return 0;
			}
			// case ==1, give data
			// case ==0, nothing
			// if device->host, since InPid then this is data stage
			if (endpoints[endpoint].controldirection == DeviceToHost) {
				// data stage
				if (size > endpoints[endpoint].remain)
					size = endpoints[endpoint].remain;
				if (endpoints[endpoint].position != nullptr)
					memcpy(buffer, endpoints[endpoint].position, size);
				endpoints[endpoint].position = endpoints[endpoint].position + size;
				endpoints[endpoint].remain = endpoints[endpoint].remain - size;
			}
			else {
				if (wantstatuscallback == true)
					handle_status_stage(endpoint);
				wantstatuscallback = false;
			}
		}
		else if (endpoints[endpoint].type == BulkEndpoint)
			return handle_bulk_pid(endpoint, pid, buffer, size);
		else if (endpoints[endpoint].type == InterruptEndpoint)
			return handle_interrupt_pid(endpoint, pid, buffer, size);
		else if (endpoints[endpoint].type == IsochronousEndpoint)
			return handle_isochronous_pid(endpoint, pid, buffer, size);
		else
			return -1;
	}
	else if (pid == OutPid) {
		if (endpoints[endpoint].type == ControlEndpoint) {
			// case ==1, nothing
			// case ==0, give data
			// if host->device, since OutPid then this is data stage
			if (endpoints[endpoint].controldirection == HostToDevice) {
				// data stage
				if (size > endpoints[endpoint].remain)
					size = endpoints[endpoint].remain;
				if (endpoints[endpoint].position != nullptr)
					memcpy(endpoints[endpoint].position, buffer, size);
				endpoints[endpoint].position = endpoints[endpoint].position + size;
				endpoints[endpoint].remain = endpoints[endpoint].remain - size;
			}
			else {
				if (wantstatuscallback == true)
					handle_status_stage(endpoint);
				wantstatuscallback = false;
			}
		}
		else if (endpoints[endpoint].type == BulkEndpoint)
			return handle_bulk_pid(endpoint, pid, buffer, size);
		else if (endpoints[endpoint].type == InterruptEndpoint)
			return handle_interrupt_pid(endpoint, pid, buffer, size);
		else if (endpoints[endpoint].type == IsochronousEndpoint)
			return handle_isochronous_pid(endpoint, pid, buffer, size);
		else
			return -1;
	}
	return size;
}

INPUT_PORTS_START(xbox_controller)
	PORT_START("ThumbstickLh") // left analog thumbstick horizontal movement
	PORT_BIT(0xff, 0x80, IPT_AD_STICK_X) PORT_NAME("ThumbstickLh") PORT_SENSITIVITY(100) PORT_KEYDELTA(1) PORT_MINMAX(0, 0xff)
		PORT_CODE_DEC(KEYCODE_J) PORT_CODE_INC(KEYCODE_L)
	PORT_START("ThumbstickLv") // left analog thumbstick vertical movement
	PORT_BIT(0xff, 0x80, IPT_AD_STICK_Y) PORT_NAME("ThumbstickLv") PORT_SENSITIVITY(100) PORT_KEYDELTA(1) PORT_MINMAX(0, 0xff)
		PORT_CODE_DEC(KEYCODE_K) PORT_CODE_INC(KEYCODE_I)

	PORT_START("ThumbstickRh") // right analog thumbstick horizontal movement
	PORT_BIT(0xff, 0x80, IPT_AD_STICK_X) PORT_NAME("ThumbstickRh") PORT_SENSITIVITY(100) PORT_KEYDELTA(1) PORT_MINMAX(0, 0xff)
		PORT_CODE_DEC(KEYCODE_4_PAD) PORT_CODE_INC(KEYCODE_6_PAD)
	PORT_START("ThumbstickRv") // right analog thumbstick vertical movement
	PORT_BIT(0xff, 0x80, IPT_AD_STICK_Y) PORT_NAME("ThumbstickRv") PORT_SENSITIVITY(100) PORT_KEYDELTA(1) PORT_MINMAX(0, 0xff)
		PORT_CODE_DEC(KEYCODE_2_PAD) PORT_CODE_INC(KEYCODE_8_PAD)

	PORT_START("DPad") // pressure sensitive directional pad
	PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP) PORT_NAME("DPad Up")
	PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN) PORT_NAME("DPad Down")
	PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT) PORT_NAME("DPad Left")
	PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT) PORT_NAME("DPad Right")

	PORT_START("TriggerL") // analog trigger
	PORT_BIT(0xff, 0x00, IPT_PEDAL) PORT_NAME("TriggerL") PORT_SENSITIVITY(100) PORT_KEYDELTA(1) PORT_MINMAX(0, 0xff)
		PORT_CODE_DEC(KEYCODE_1_PAD) PORT_CODE_INC(KEYCODE_7_PAD)

	PORT_START("TriggerR") // analog trigger
	PORT_BIT(0xff, 0x00, IPT_PEDAL) PORT_NAME("TriggerR") PORT_SENSITIVITY(100) PORT_KEYDELTA(1) PORT_MINMAX(0, 0xff)
		PORT_CODE_DEC(KEYCODE_3_PAD) PORT_CODE_INC(KEYCODE_9_PAD)

	PORT_START("Buttons") // digital buttons
	PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_BUTTON2) PORT_NAME("Start") // Start button
	PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_BUTTON1) PORT_NAME("Back") // Back button

	PORT_START("AGreen") // analog button
	PORT_BIT(0xff, 0x00, IPT_PEDAL) PORT_NAME("A-Green") PORT_SENSITIVITY(100) PORT_KEYDELTA(32)  PORT_MINMAX(0, 0xff)
		PORT_CODE_DEC(KEYCODE_A) PORT_CODE_INC(KEYCODE_Q)

	PORT_START("BRed") // analog button
	PORT_BIT(0xff, 0x00, IPT_PEDAL) PORT_NAME("B-Red") PORT_SENSITIVITY(100) PORT_KEYDELTA(32) PORT_MINMAX(0, 0xff)
		PORT_CODE_DEC(KEYCODE_S) PORT_CODE_INC(KEYCODE_W)

	PORT_START("XBlue") // analog button
	PORT_BIT(0xff, 0x00, IPT_PEDAL) PORT_NAME("X-Blue") PORT_SENSITIVITY(100) PORT_KEYDELTA(32) PORT_MINMAX(0, 0xff)
		PORT_CODE_DEC(KEYCODE_D) PORT_CODE_INC(KEYCODE_E)

	PORT_START("YYellow") // analog button
	PORT_BIT(0xff, 0x00, IPT_PEDAL) PORT_NAME("Y-Yellow") PORT_SENSITIVITY(100) PORT_KEYDELTA(32) PORT_MINMAX(0, 0xff)
		PORT_CODE_DEC(KEYCODE_F) PORT_CODE_INC(KEYCODE_R)

	PORT_START("Black") // analog button
	PORT_BIT(0xff, 0x00, IPT_PEDAL) PORT_NAME("Black") PORT_SENSITIVITY(100) PORT_KEYDELTA(32) PORT_MINMAX(0, 0xff)
		PORT_CODE_DEC(KEYCODE_G) PORT_CODE_INC(KEYCODE_T)

	PORT_START("White") // analog button
	PORT_BIT(0xff, 0x00, IPT_PEDAL) PORT_NAME("White") PORT_SENSITIVITY(100) PORT_KEYDELTA(32) PORT_MINMAX(0, 0xff)
		PORT_CODE_DEC(KEYCODE_H) PORT_CODE_INC(KEYCODE_Y)
INPUT_PORTS_END

const USBStandardDeviceDescriptor ohci_game_controller_device::devdesc = { 18,1,0x110,0x00,0x00,0x00,64,0x45e,0x202,0x100,0,0,0,1 };
const USBStandardConfigurationDescriptor ohci_game_controller_device::condesc = { 9,2,0x20,1,1,0,0x80,50 };
const USBStandardInterfaceDescriptor ohci_game_controller_device::intdesc = { 9,4,0,0,2,0x58,0x42,0,0 };
const USBStandardEndpointDescriptor ohci_game_controller_device::enddesc82 = { 7,5,0x82,3,0x20,4 };
const USBStandardEndpointDescriptor ohci_game_controller_device::enddesc02 = { 7,5,0x02,3,0x20,4 };

const device_type OHCI_GAME_CONTROLLER = &device_creator<ohci_game_controller_device>;

ohci_game_controller_device::ohci_game_controller_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) :
	device_t(mconfig, OHCI_GAME_CONTROLLER, "OHCI Game Controller", tag, owner, clock, "ohci_gc", __FILE__),
	ohci_function_device(),
	m_ThumbstickLh(*this, "ThumbstickLh"),
	m_ThumbstickLv(*this, "ThumbstickLv"),
	m_ThumbstickRh(*this, "ThumbstickRh"),
	m_ThumbstickRv(*this, "ThumbstickRv"),
	m_DPad(*this, "DPad"),
	m_TriggerL(*this, "TriggerL"),
	m_TriggerR(*this, "TriggerR"),
	m_Buttons(*this, "Buttons"),
	m_AGreen(*this, "AGreen"),
	m_BRed(*this, "BRed"),
	m_XBlue(*this, "XBlue"),
	m_YYellow(*this, "YYellow"),
	m_Black(*this, "Black"),
	m_White(*this, "White")
{
}

void ohci_game_controller_device::initialize(running_machine &machine, ohci_usb_controller *usb_bus_manager)
{
	ohci_function_device::initialize(machine, usb_bus_manager);
	add_device_descriptor(devdesc);
	add_configuration_descriptor(condesc);
	add_interface_descriptor(intdesc);
	add_endpoint_descriptor(enddesc82);
	add_endpoint_descriptor(enddesc02);
}

int ohci_game_controller_device::handle_nonstandard_request(int endpoint, USBSetupPacket *setup)
{
	//                                    >=8  ==42  !=0  !=0  1,3       2<20 <=20
	static const UINT8 reportinfo[16] = { 0x10,0x42 ,0x32,0x43,1   ,0x65,0x14,0x20,0x98,0xa9,0xba,0xcb,0xdc,0xed,0xfe };

	if (endpoint != 0)
		return -1;
	if ((endpoints[endpoint].controltype == VendorType) && (endpoints[endpoint].controlrecipient == InterfaceRecipient))
	{
		if ((setup->bRequest == GET_DESCRIPTOR) && (setup->wValue == 0x4200))
		{
			endpoints[endpoint].position = (UINT8 *)reportinfo;
			endpoints[endpoint].remain = 16;
			return 0;
		}
	}
	if ((endpoints[endpoint].controltype == ClassType) && (endpoints[endpoint].controlrecipient == InterfaceRecipient))
	{
		if ((setup->bRequest == 1) && (setup->wValue == 0x0100))
		{
			endpoints[endpoint].position = endpoints[endpoint].buffer;
			endpoints[endpoint].remain = setup->wLength;
			for (int n = 0; n < setup->wLength; n++)
				endpoints[endpoint].buffer[n] = 0x10 ^ n;
			endpoints[endpoint].buffer[2] = 0;
			return 0;
		}
	}
	if ((endpoints[endpoint].controltype == VendorType) && (endpoints[endpoint].controlrecipient == InterfaceRecipient))
	{
		if ((setup->bRequest == 1) && (setup->wValue == 0x0200))
		{
			endpoints[endpoint].position = endpoints[endpoint].buffer;
			endpoints[endpoint].remain = setup->wLength;
			for (int n = 0; n < setup->wLength; n++)
				endpoints[endpoint].buffer[n] = 0x20 ^ n;
			return 0;
		}
	}
	if ((endpoints[endpoint].controltype == VendorType) && (endpoints[endpoint].controlrecipient == InterfaceRecipient))
	{
		if ((setup->bRequest == 1) && (setup->wValue == 0x0100))
		{
			endpoints[endpoint].position = endpoints[endpoint].buffer;
			endpoints[endpoint].remain = setup->wLength;
			for (int n = 0; n < setup->wLength; n++)
				endpoints[endpoint].buffer[n] = 0x30 ^ n;
			return 0;
		}
	}
	return -1;
}

int ohci_game_controller_device::handle_interrupt_pid(int endpoint, int pid, UINT8 *buffer, int size)
{
	if ((endpoint == 2) && (pid == InPid)) {
		int v;

		buffer[0] = 0;
		buffer[1] = 20;
		v = m_DPad->read();
		v = v | (m_Buttons->read() << 4);
		buffer[2] = (UINT8)v;
		buffer[3] = 0;
		buffer[4] = m_AGreen->read();
		buffer[5] = m_BRed->read();
		buffer[6] = m_XBlue->read();
		buffer[7] = m_YYellow->read();
		buffer[8] = m_Black->read();
		buffer[9] = m_White->read();
		buffer[10] = m_TriggerL->read();
		buffer[11] = m_TriggerR->read();
		v = m_ThumbstickLh->read();
		v = (v - 128) * 256;
		buffer[12] = (UINT16)v & 255;
		buffer[13] = (UINT16)v >> 8;
		v = m_ThumbstickLv->read();
		v = (v - 128) * 256;
		buffer[14] = (UINT16)v & 255;
		buffer[15] = (UINT16)v >> 8;
		v = m_ThumbstickRh->read();
		v = (v - 128) * 256;
		buffer[16] = (UINT16)v & 255;
		buffer[17] = (UINT16)v >> 8;
		v = m_ThumbstickRv->read();
		v = (v - 128) * 256;
		buffer[18] = (UINT16)v & 255;
		buffer[19] = (UINT16)v >> 8;
		return size;
	}
	return -1;
}

void ohci_game_controller_device::device_start()
{
}

ioport_constructor ohci_game_controller_device::device_input_ports() const
{
	return INPUT_PORTS_NAME(xbox_controller);
}

WRITE_LINE_MEMBER(xbox_base_state::xbox_ohci_usb_interrupt_changed)
{
	xbox_base_devs.pic8259_1->ir1_w(state);
}

/*
 * Audio
 */

READ32_MEMBER(xbox_base_state::audio_apu_r)
{
#ifdef LOG_AUDIO
	logerror("Audio_APU: read from %08X mask %08X\n", 0xfe800000 + offset * 4, mem_mask);
#endif
	if (offset == 0x20010 / 4) // some kind of internal counter or state value
		return 0x20 + 4 + 8 + 0x48 + 0x80;
	return apust.memory[offset];
}

WRITE32_MEMBER(xbox_base_state::audio_apu_w)
{
	//UINT32 old;
	UINT32 v;

#ifdef LOG_AUDIO
	logerror("Audio_APU: write at %08X mask %08X value %08X\n", 0xfe800000 + offset * 4, mem_mask, data);
#endif
	//old = apust.memory[offset];
	apust.memory[offset] = data;
	if (offset == 0x02040 / 4) // address of memory area with scatter-gather info (gpdsp scratch dma)
		apust.gpdsp_sgaddress = data;
	if (offset == 0x020d4 / 4) { // block count (gpdsp)
		apust.gpdsp_sgblocks = data;
		apust.gpdsp_address = apust.space->read_dword(apust.gpdsp_sgaddress); // memory address of first block
		apust.timer->enable();
		apust.timer->adjust(attotime::from_msec(1), 0, attotime::from_msec(1));
	}
	if (offset == 0x02048 / 4) // (epdsp scratch dma)
		apust.epdsp_sgaddress = data;
	if (offset == 0x020dc / 4) // (epdsp)
		apust.epdsp_sgblocks = data;
	if (offset == 0x0204c / 4) // address of memory area with information about blocks
		apust.unknown_sgaddress = data;
	if (offset == 0x020e0 / 4) // block count - 1
		apust.unknown_sgblocks = data;
	if (offset == 0x0202c / 4) { // address of memory area with 0x80 bytes for each voice
		apust.voicedata_address = data;
		return;
	}
	if (offset == 0x04024 / 4) // offset in memory area indicated by 0x204c (analog output ?)
		return;
	if (offset == 0x04034 / 4) // size
		return;
	if (offset == 0x04028 / 4) // offset in memory area indicated by 0x204c (digital output ?)
		return;
	if (offset == 0x04038 / 4) // size
		return;
	if (offset == 0x20804 / 4) { // block number for scatter-gather heap that stores sampled audio to be played
		if (data >= 1024) {
			logerror("Audio_APU: sg block number too high, increase size of voices_heap_blockaddr\n");
			apust.memory[offset] = 1023;
		}
		return;
	}
	if (offset == 0x20808 / 4) { // block address for scatter-gather heap that stores sampled audio to be played
		apust.voices_heap_blockaddr[apust.memory[0x20804 / 4]] = data;
		return;
	}
	if (offset == 0x202f8 / 4) { // voice number for parameters ?
		apust.voice_number = data;
		return;
	}
	if (offset == 0x202fc / 4) // 1 when accessing voice parameters 0 otherwise
		return;
	if (offset == 0x20304 / 4) { // format
		/*
		bits 28-31 sample format:
		0  8-bit pcm
		5  16-bit pcm
		10 adpcm ?
		14 24-bit pcm
		15 32-bit pcm
		bits 16-20 number of channels - 1:
		0  mono
		1  stereo
		*/
		return;
	}
	if (offset == 0x2037c / 4) { // value related to sample rate
		INT16 v0 = (INT16)(data >> 16); // upper 16 bits as a signed 16 bit value
		float vv = ((float)v0) / 4096.0f; // divide by 4096
		float vvv = powf(2, vv); // two to the vv
		int f = vvv*48000.0f; // sample rate
		apust.voices_frequency[apust.voice_number] = f;
		return;
	}
	if (offset == 0x203a0 / 4) // start offset of data in scatter-gather heap
		return;
	if (offset == 0x203a4 / 4) { // first sample to play
		apust.voices_position_start[apust.voice_number] = data * 1000;
		return;
	}
	if (offset == 0x203dc / 4) { // last sample to play
		apust.voices_position_end[apust.voice_number] = data * 1000;
		return;
	}
	if (offset == 0x2010c / 4) // voice processor 0 idle 1 not idle ?
		return;
	if (offset == 0x20124 / 4) { // voice number to activate ?
		v = apust.voice_number;
		apust.voices_active[v >> 6] |= ((UINT64)1 << (v & 63));
		apust.voices_position[v] = apust.voices_position_start[apust.voice_number];
		apust.voices_position_increment[apust.voice_number] = apust.voices_frequency[apust.voice_number];
		return;
	}
	if (offset == 0x20128 / 4) { // voice number to deactivate ?
		v = apust.voice_number;
		apust.voices_active[v >> 6] &= ~(1 << (v & 63));
		return;
	}
	if (offset == 0x20140 / 4) // voice number to ?
		return;
	if ((offset >= 0x20200 / 4) && (offset < 0x20280 / 4)) // headroom for each of the 32 mixbins
		return;
	if (offset == 0x20280 / 4) // hrtf headroom ?
		return;
}

READ32_MEMBER(xbox_base_state::audio_ac93_r)
{
	UINT32 ret = 0;

#ifdef LOG_AUDIO
	logerror("Audio_AC3: read from %08X mask %08X\n", 0xfec00000 + offset * 4, mem_mask);
#endif
	if (offset < 0x80 / 4)
	{
		ret = ac97st.mixer_regs[offset];
	}
	if ((offset >= 0x100 / 4) && (offset <= 0x138 / 4))
	{
		offset = offset - 0x100 / 4;
		if (offset == 0x18 / 4)
		{
			ac97st.controller_regs[offset] &= ~0x02000000; // REGRST: register reset
		}
		if (offset == 0x30 / 4)
		{
			ac97st.controller_regs[offset] |= 0x100; // PCRDY: primary codec ready
		}
		if (offset == 0x34 / 4)
		{
			ac97st.controller_regs[offset] &= ~1; // CAS: codec access semaphore
		}
		ret = ac97st.controller_regs[offset];
	}
	return ret;
}

WRITE32_MEMBER(xbox_base_state::audio_ac93_w)
{
#ifdef LOG_AUDIO
	logerror("Audio_AC3: write at %08X mask %08X value %08X\n", 0xfec00000 + offset * 4, mem_mask, data);
#endif
	if (offset < 0x80 / 4)
	{
		COMBINE_DATA(ac97st.mixer_regs + offset);
	}
	if ((offset >= 0x100 / 4) && (offset <= 0x138 / 4))
	{
		offset = offset - 0x100 / 4;
		COMBINE_DATA(ac97st.controller_regs + offset);
	}
}

TIMER_CALLBACK_MEMBER(xbox_base_state::audio_apu_timer)
{
	int cmd;
	int bb, b, v;
	UINT64 bv;
	UINT32 phys;

	cmd = apust.space->read_dword(apust.gpdsp_address + 0x800 + 0x10);
	if (cmd == 3)
		apust.space->write_dword(apust.gpdsp_address + 0x800 + 0x10, 0);
	/*else
	logerror("Audio_APU: unexpected value at address %d\n",apust.gpdsp_address+0x800+0x10);*/
	for (b = 0; b < 4; b++) {
		bv = 1;
		for (bb = 0; bb < 64; bb++) {
			if (apust.voices_active[b] & bv) {
				v = bb + (b << 6);
				apust.voices_position[v] += apust.voices_position_increment[v];
				while (apust.voices_position[v] >= apust.voices_position_end[v])
					apust.voices_position[v] = apust.voices_position_start[v] + apust.voices_position[v] - apust.voices_position_end[v] - 1000;
				phys = apust.voicedata_address + 0x80 * v;
				apust.space->write_dword(phys + 0x58, apust.voices_position[v] / 1000);
			}
			bv = bv << 1;
		}
	}
}

static UINT32 pcibridghostbridg_pci_r(device_t *busdevice, device_t *device, int function, int reg, UINT32 mem_mask)
{
#ifdef LOG_PCI
	busdevice->logerror("  bus:0 function:%d register:%d mask:%08X\n",function,reg,mem_mask);
#endif
	if ((function == 3) && (reg == 0x6c))
		return 0x08800044;
	return 0;
}

static void pcibridghostbridg_pci_w(device_t *busdevice, device_t *device, int function, int reg, UINT32 data, UINT32 mem_mask)
{
#ifdef LOG_PCI
	busdevice->logerror("  bus:0 function:%d register:%d data:%08X mask:%08X\n", function, reg, data, mem_mask);
#endif
}

static UINT32 hubintisabridg_pci_r(device_t *busdevice, device_t *device, int function, int reg, UINT32 mem_mask)
{
#ifdef LOG_PCI
	busdevice->logerror("  bus:0 function:%d register:%d mask:%08X\n",function,reg,mem_mask);
#endif
	if ((function == 0) && (reg == 8))
		return 0xb4; // 0:1:0 revision id must be at least 0xb4, otherwise usb will require a hub
	return 0;
}

static void hubintisabridg_pci_w(device_t *busdevice, device_t *device, int function, int reg, UINT32 data, UINT32 mem_mask)
{
#ifdef LOG_PCI
	busdevice->logerror("  bus:0 function:%d register:%d data:%08X mask:%08X\n", function, reg, data, mem_mask);
#endif
}

/*
 * dummy for non connected devices
 */

static UINT32 dummy_pci_r(device_t *busdevice, device_t *device, int function, int reg, UINT32 mem_mask)
{
#ifdef LOG_PCI
	busdevice->logerror("  bus:0 function:%d register:%d mask:%08X\n",function,reg,mem_mask);
#endif
	return 0;
}

static void dummy_pci_w(device_t *busdevice, device_t *device, int function, int reg, UINT32 data, UINT32 mem_mask)
{
#ifdef LOG_PCI
	busdevice->logerror("  bus:0 function:%d register:%d data:%08X mask:%08X\n", function, reg, data, mem_mask);
#endif
}

READ32_MEMBER(xbox_base_state::dummy_r)
{
	return 0;
}

WRITE32_MEMBER(xbox_base_state::dummy_w)
{
}

/*
 * PIC & PIT
 */

WRITE_LINE_MEMBER(xbox_base_state::xbox_pic8259_1_set_int_line)
{
	m_maincpu->set_input_line(0, state ? HOLD_LINE : CLEAR_LINE);
}

READ8_MEMBER(xbox_base_state::get_slave_ack)
{
	if (offset == 2) { // IRQ = 2
		return xbox_base_devs.pic8259_2->acknowledge();
	}
	return 0x00;
}

IRQ_CALLBACK_MEMBER(xbox_base_state::irq_callback)
{
	int r = 0;
	r = xbox_base_devs.pic8259_1->acknowledge();
	if (debug_irq_active)
		debug_generate_irq(debug_irq_number, false);
	return r;
}

WRITE_LINE_MEMBER(xbox_base_state::xbox_pit8254_out0_changed)
{
	if (xbox_base_devs.pic8259_1)
	{
		xbox_base_devs.pic8259_1->ir0_w(state);
	}
}

WRITE_LINE_MEMBER(xbox_base_state::xbox_pit8254_out2_changed)
{
	//xbox_speaker_set_input( state ? 1 : 0 );
}

/*
 * SMbus devices
 */

int smbus_callback_pic16lc(xbox_base_state &chs, int command, int rw, int data)
{
	return chs.smbus_pic16lc(command, rw, data);
}

int xbox_base_state::smbus_pic16lc(int command, int rw, int data)
{
	if (rw == 1) { // read
		if (command == 0) {
			if (pic16lc_buffer[0] == 'D')
				pic16lc_buffer[0] = 'X';
			else if (pic16lc_buffer[0] == 'X')
				pic16lc_buffer[0] = 'B';
			else if (pic16lc_buffer[0] == 'B')
				pic16lc_buffer[0] = 'D';
		}
		logerror("pic16lc: %d %d %d\n", command, rw, pic16lc_buffer[command]);
		return pic16lc_buffer[command];
	}
	else
		if (command == 0)
			pic16lc_buffer[0] = 'B';
		else
			pic16lc_buffer[command] = (UINT8)data;
	logerror("pic16lc: %d %d %d\n", command, rw, data);
	return 0;
}

int smbus_callback_cx25871(xbox_base_state &chs, int command, int rw, int data)
{
	return chs.smbus_cx25871(command, rw, data);
}

int xbox_base_state::smbus_cx25871(int command, int rw, int data)
{
	logerror("cx25871: %d %d %d\n", command, rw, data);
	return 0;
}

// let's try to fake the missing eeprom
static int dummyeeprom[256] = { 0x94,0x18,0x10,0x59,0x83,0x58,0x15,0xDA,0xDF,0xCC,0x1D,0x78,0x20,0x8A,0x61,0xB8,0x08,0xB4,0xD6,0xA8,
0x9E,0x77,0x9C,0xEB,0xEA,0xF8,0x93,0x6E,0x3E,0xD6,0x9C,0x49,0x6B,0xB5,0x6E,0xAB,0x6D,0xBC,0xB8,0x80,0x68,0x9D,0xAA,0xCD,0x0B,0x83,
0x17,0xEC,0x2E,0xCE,0x35,0xA8,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x61,0x62,0x63,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF,0x00,0x00,
0x4F,0x6E,0x6C,0x69,0x6E,0x65,0x6B,0x65,0x79,0x69,0x6E,0x76,0x61,0x6C,0x69,0x64,0x00,0x03,0x80,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,
0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };

int smbus_callback_eeprom(xbox_base_state &chs, int command, int rw, int data)
{
	return chs.smbus_eeprom(command, rw, data);
}

int xbox_base_state::smbus_eeprom(int command, int rw, int data)
{
	if (command >= 112)
		return 0;
	if (rw == 1) { // if reading
		// hack to avoid hanging if eeprom contents are not correct
		// this would need dumping the serial eeprom on the xbox board
		if (command == 0) {
			hack_eeprom();
		}
		data = dummyeeprom[command] + dummyeeprom[command + 1] * 256;
		logerror("eeprom: %d %d %d\n", command, rw, data);
		return data;
	}
	logerror("eeprom: %d %d %d\n", command, rw, data);
	dummyeeprom[command] = data;
	return 0;
}

/*
 * SMbus controller
 */

void xbox_base_state::smbus_register_device(int address, int(*handler)(xbox_base_state &chs, int command, int rw, int data))
{
	if (address < 128)
		smbusst.devices[address] = handler;
}

READ32_MEMBER(xbox_base_state::smbus_r)
{
	if ((offset == 0) && (mem_mask == 0xff)) // 0 smbus status
		smbusst.words[offset] = (smbusst.words[offset] & ~mem_mask) | ((smbusst.status << 0) & mem_mask);
	if ((offset == 1) && ((mem_mask == 0x00ff0000) || (mem_mask == 0xffff0000))) // 6 smbus data
		smbusst.words[offset] = (smbusst.words[offset] & ~mem_mask) | ((smbusst.data << 16) & mem_mask);
	return smbusst.words[offset];
}

WRITE32_MEMBER(xbox_base_state::smbus_w)
{
	COMBINE_DATA(smbusst.words);
	if ((offset == 0) && (mem_mask == 0xff)) // 0 smbus status
	{
		if (!((smbusst.status ^ data) & 0x10)) // clearing interrupt
			xbox_base_devs.pic8259_2->ir3_w(0); // IRQ 11
		smbusst.status &= ~data;
	}
	if ((offset == 0) && (mem_mask == 0xff0000)) // 2 smbus control
	{
		data = data >> 16;
		smbusst.control = data;
		int cycletype = smbusst.control & 7;
		if (smbusst.control & 8) { // start
			if ((cycletype & 6) == 2)
			{
				if (smbusst.devices[smbusst.address])
					if (smbusst.rw == 0)
						smbusst.devices[smbusst.address](*this, smbusst.command, smbusst.rw, smbusst.data);
					else
						smbusst.data = smbusst.devices[smbusst.address](*this, smbusst.command, smbusst.rw, smbusst.data);
				else
					logerror("SMBUS: access to missing device at address %d\n", smbusst.address);
				smbusst.status |= 0x10;
				if (smbusst.control & 0x10)
				{
					xbox_base_devs.pic8259_2->ir3_w(1); // IRQ 11
				}
			}
		}
	}
	if ((offset == 1) && (mem_mask == 0xff)) // 4 smbus address
	{
		smbusst.address = data >> 1;
		smbusst.rw = data & 1;
	}
	if ((offset == 1) && ((mem_mask == 0x00ff0000) || (mem_mask == 0xffff0000))) // 6 smbus data
	{
		data = data >> 16;
		smbusst.data = data;
	}
	if ((offset == 2) && (mem_mask == 0xff)) // 8 smbus command
		smbusst.command = data;
}

/*
 * SuperIO
 */
READ8_MEMBER(xbox_base_state::superio_read)
{
	if (superiost.configuration_mode == false)
		return 0;
	if (offset == 0) // index port 0x2e
		return superiost.index;
	if (offset == 1)
	{
		// data port 0x2f
		if (superiost.index < 0x30)
			return superiost.registers[0][superiost.index];
		return superiost.registers[superiost.selected][superiost.index];
	}
	return 0;
}

WRITE8_MEMBER(xbox_base_state::superio_write)
{
	if (superiost.configuration_mode == false)
	{
		// config port 0x2e
		if ((offset == 0) && (data == 0x55))
			superiost.configuration_mode = true;
		return;
	}
	if ((offset == 0) && (data == 0xaa))
	{
		// config port 0x2e
		superiost.configuration_mode = false;
		return;
	}
	if (offset == 0)
	{
		// index port 0x2e
		superiost.index = data;
	}
	if (offset == 1)
	{
		// data port 0x2f
		if (superiost.index < 0x30)
		{
			superiost.registers[0][superiost.index] = data;
			superiost.selected = superiost.registers[0][7];
		} else
		{
			superiost.registers[superiost.selected][superiost.index] = data;
			//if ((superiost.selected == 4) && (superiost.index == 0x30) && (data != 0))
			//  ; // add handlers 0x3f8- +7
		}
	}
}

READ8_MEMBER(xbox_base_state::superiors232_read)
{
	if (offset == 5)
		return 0x20;
	return 0;
}

WRITE8_MEMBER(xbox_base_state::superiors232_write)
{
	if (offset == 0)
	{
		printf("%c", data);
	}
}

ADDRESS_MAP_START(xbox_base_map, AS_PROGRAM, 32, xbox_base_state)
	AM_RANGE(0x00000000, 0x07ffffff) AM_RAM AM_SHARE("nv2a_share") // 128 megabytes
	AM_RANGE(0xf0000000, 0xf7ffffff) AM_RAM AM_SHARE("nv2a_share") // 3d accelerator wants this
	AM_RANGE(0xfd000000, 0xfdffffff) AM_RAM AM_READWRITE(geforce_r, geforce_w)
	AM_RANGE(0xfed00000, 0xfed003ff) AM_DEVREADWRITE("ohci_usb", ohci_usb_controller, read, write)
	AM_RANGE(0xfe800000, 0xfe85ffff) AM_READWRITE(audio_apu_r, audio_apu_w)
	AM_RANGE(0xfec00000, 0xfec001ff) AM_READWRITE(audio_ac93_r, audio_ac93_w)
	AM_RANGE(0xff000000, 0xff0fffff) AM_ROM AM_REGION("bios", 0) AM_MIRROR(0x00f80000)
ADDRESS_MAP_END

ADDRESS_MAP_START(xbox_base_map_io, AS_IO, 32, xbox_base_state)
	AM_RANGE(0x0020, 0x0023) AM_DEVREADWRITE8("pic8259_1", pic8259_device, read, write, 0xffffffff)
	AM_RANGE(0x002c, 0x002f) AM_READWRITE8(superio_read, superio_write, 0xffff0000)
	AM_RANGE(0x0040, 0x0043) AM_DEVREADWRITE8("pit8254", pit8254_device, read, write, 0xffffffff)
	AM_RANGE(0x00a0, 0x00a3) AM_DEVREADWRITE8("pic8259_2", pic8259_device, read, write, 0xffffffff)
	AM_RANGE(0x01f0, 0x01f7) AM_DEVREADWRITE("ide", bus_master_ide_controller_device, read_cs0, write_cs0)
	AM_RANGE(0x03f8, 0x03ff) AM_READWRITE8(superiors232_read, superiors232_write, 0xffffffff)
	AM_RANGE(0x0cf8, 0x0cff) AM_DEVREADWRITE("pcibus", pci_bus_legacy_device, read, write)
	AM_RANGE(0x8000, 0x80ff) AM_READWRITE(dummy_r, dummy_w)
	AM_RANGE(0xc000, 0xc0ff) AM_READWRITE(smbus_r, smbus_w)
	AM_RANGE(0xff60, 0xff67) AM_DEVREADWRITE("ide", bus_master_ide_controller_device, bmdma_r, bmdma_w)
ADDRESS_MAP_END

void xbox_base_state::machine_start()
{
	ohci_game_controller_device *usb_device;

	nvidia_nv2a = std::make_unique<nv2a_renderer>(machine());
	memset(pic16lc_buffer, 0, sizeof(pic16lc_buffer));
	pic16lc_buffer[0] = 'B';
	pic16lc_buffer[4] = 0; // A/V connector, 2=vga
	smbus_register_device(0x10, smbus_callback_pic16lc);
	smbus_register_device(0x45, smbus_callback_cx25871);
	smbus_register_device(0x54, smbus_callback_eeprom);
	xbox_base_devs.pic8259_1 = machine().device<pic8259_device>("pic8259_1");
	xbox_base_devs.pic8259_2 = machine().device<pic8259_device>("pic8259_2");
	xbox_base_devs.ide = machine().device<bus_master_ide_controller_device>("ide");
	memset(apust.memory, 0, sizeof(apust.memory));
	memset(apust.voices_heap_blockaddr, 0, sizeof(apust.voices_heap_blockaddr));
	memset(apust.voices_active, 0, sizeof(apust.voices_active));
	memset(apust.voices_position, 0, sizeof(apust.voices_position));
	memset(apust.voices_position_start, 0, sizeof(apust.voices_position_start));
	memset(apust.voices_position_end, 0, sizeof(apust.voices_position_end));
	memset(apust.voices_position_increment, 0, sizeof(apust.voices_position_increment));
	apust.space = &m_maincpu->space();
	apust.timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(xbox_base_state::audio_apu_timer), this), (void *)"APU Timer");
	apust.timer->enable(false);
	if (machine().debug_flags & DEBUG_FLAG_ENABLED)
		debug_console_register_command(machine(), "xbox", CMDFLAG_NONE, 0, 1, 4, xbox_debug_commands);
	// PIC challenge handshake data
	pic16lc_buffer[0x1c] = 0x0c;
	pic16lc_buffer[0x1d] = 0x0d;
	pic16lc_buffer[0x1e] = 0x0e;
	pic16lc_buffer[0x1f] = 0x0f;
	// usb
	ohci_usb = machine().device<ohci_usb_controller>("ohci_usb");
	usb_device = machine().device<ohci_game_controller_device>("ohci_gamepad");
	usb_device->initialize(machine(), ohci_usb);
	ohci_usb->usb_ohci_plug(3, usb_device); // connect to root hub port 3, chihiro needs to use 1 and 2
	// super-io
	memset(&superiost, 0, sizeof(superiost));
	superiost.configuration_mode = false;
	superiost.registers[0][0x26] = 0x2e; // Configuration port address byte 0
	// savestates
	save_item(NAME(debug_irq_active));
	save_item(NAME(debug_irq_number));
	save_item(NAME(smbusst.status));
	save_item(NAME(smbusst.control));
	save_item(NAME(smbusst.address));
	save_item(NAME(smbusst.data));
	save_item(NAME(smbusst.command));
	save_item(NAME(smbusst.rw));
	save_item(NAME(smbusst.words));
	save_item(NAME(pic16lc_buffer));
	nvidia_nv2a->set_interrupt_device(xbox_base_devs.pic8259_1);
	nvidia_nv2a->start(&m_maincpu->space());
	nvidia_nv2a->savestate_items();
}

MACHINE_CONFIG_START(xbox_base, xbox_base_state)

	/* basic machine hardware */
	MCFG_CPU_ADD("maincpu", PENTIUM3, 733333333) /* Wrong! family 6 model 8 stepping 10 */
	MCFG_CPU_PROGRAM_MAP(xbox_base_map)
	MCFG_CPU_IO_MAP(xbox_base_map_io)
	MCFG_CPU_IRQ_ACKNOWLEDGE_DRIVER(xbox_base_state, irq_callback)

	MCFG_QUANTUM_TIME(attotime::from_hz(6000))

	MCFG_PCI_BUS_LEGACY_ADD("pcibus", 0)
	MCFG_PCI_BUS_LEGACY_DEVICE(0, "PCI Bridge Device - Host Bridge", pcibridghostbridg_pci_r, pcibridghostbridg_pci_w)
	MCFG_PCI_BUS_LEGACY_DEVICE(1, "HUB Interface - ISA Bridge", hubintisabridg_pci_r, hubintisabridg_pci_w)
	MCFG_PCI_BUS_LEGACY_DEVICE(2, "OHCI USB Controller 1", dummy_pci_r, dummy_pci_w)
	MCFG_PCI_BUS_LEGACY_DEVICE(3, "OHCI USB Controller 2", dummy_pci_r, dummy_pci_w)
	MCFG_PCI_BUS_LEGACY_DEVICE(4, "MCP Networking Adapter", dummy_pci_r, dummy_pci_w)
	MCFG_PCI_BUS_LEGACY_DEVICE(5, "MCP APU", dummy_pci_r, dummy_pci_w)
	MCFG_PCI_BUS_LEGACY_DEVICE(6, "AC`97 Audio Codec Interface", dummy_pci_r, dummy_pci_w)
	MCFG_PCI_BUS_LEGACY_DEVICE(9, "IDE Controller", dummy_pci_r, dummy_pci_w)
	MCFG_PCI_BUS_LEGACY_DEVICE(30, "AGP Host to PCI Bridge", dummy_pci_r, dummy_pci_w)
	MCFG_PCI_BUS_LEGACY_ADD("agpbus", 1)
	MCFG_PCI_BUS_LEGACY_SIBLING("pcibus")
	MCFG_PCI_BUS_LEGACY_DEVICE(0, "NV2A GeForce 3MX Integrated GPU/Northbridge", geforce_pci_r, geforce_pci_w)
	MCFG_PIC8259_ADD("pic8259_1", WRITELINE(xbox_base_state, xbox_pic8259_1_set_int_line), VCC, READ8(xbox_base_state, get_slave_ack))
	MCFG_PIC8259_ADD("pic8259_2", DEVWRITELINE("pic8259_1", pic8259_device, ir2_w), GND, NOOP)

	MCFG_DEVICE_ADD("pit8254", PIT8254, 0)
	MCFG_PIT8253_CLK0(1125000) /* heartbeat IRQ */
	MCFG_PIT8253_OUT0_HANDLER(WRITELINE(xbox_base_state, xbox_pit8254_out0_changed))
	MCFG_PIT8253_CLK1(1125000) /* (unused) dram refresh */
	MCFG_PIT8253_CLK2(1125000) /* (unused) pio port c pin 4, and speaker polling enough */
	MCFG_PIT8253_OUT2_HANDLER(WRITELINE(xbox_base_state, xbox_pit8254_out2_changed))

	MCFG_DEVICE_ADD("ide", BUS_MASTER_IDE_CONTROLLER, 0)
	MCFG_ATA_INTERFACE_IRQ_HANDLER(DEVWRITELINE("pic8259_2", pic8259_device, ir6_w))
	MCFG_BUS_MASTER_IDE_CONTROLLER_SPACE("maincpu", AS_PROGRAM)

	// next line is temporary
	MCFG_OHCI_USB_CONTROLLER_ADD("ohci_usb")
	MCFG_OHCI_USB_CONTROLLER_INTERRUPT_HANDLER(WRITELINE(xbox_base_state, xbox_ohci_usb_interrupt_changed))
	MCFG_DEVICE_ADD("ohci_gamepad", OHCI_GAME_CONTROLLER, 0)

	/* video hardware */
	MCFG_SCREEN_ADD("screen", RASTER)
	MCFG_SCREEN_REFRESH_RATE(60)
	MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500))  /* not accurate */
	MCFG_SCREEN_SIZE(640, 480)
	MCFG_SCREEN_VISIBLE_AREA(0, 639, 0, 479)
	MCFG_SCREEN_UPDATE_DRIVER(xbox_base_state, screen_update_callback)
	MCFG_SCREEN_VBLANK_DRIVER(xbox_base_state, vblank_callback)
MACHINE_CONFIG_END