summaryrefslogtreecommitdiff
path: root/sys/dev/usb/ehci.c
blob: d46fa003ba0867a01dc834a95df5c0c16ef64a3a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
/*	$OpenBSD: ehci.c,v 1.170 2014/11/18 02:37:30 tedu Exp $ */
/*	$NetBSD: ehci.c,v 1.66 2004/06/30 03:11:56 mycroft Exp $	*/

/*
 * Copyright (c) 2004-2008 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Lennart Augustsson (lennart@augustsson.net), Charles M. Hannum and
 * Jeremy Morse (jeremy.morse@gmail.com).
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * TODO:
 * 1) The hub driver needs to handle and schedule the transaction translator,
 *    to assign place in frame where different devices get to go. See chapter
 *    on hubs in USB 2.0 for details.
 *
 * 2) Command failures are not recovered correctly.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/rwlock.h>
#include <sys/malloc.h>
#include <sys/device.h>
#include <sys/queue.h>
#include <sys/timeout.h>
#include <sys/pool.h>

#include <machine/bus.h>
#include <machine/endian.h>

#include <dev/usb/usb.h>
#include <dev/usb/usbdi.h>
#include <dev/usb/usbdivar.h>
#include <dev/usb/usb_mem.h>

#include <dev/usb/ehcireg.h>
#include <dev/usb/ehcivar.h>

struct cfdriver ehci_cd = {
	NULL, "ehci", DV_DULL
};

#ifdef EHCI_DEBUG
#define DPRINTF(x)	do { if (ehcidebug) printf x; } while(0)
#define DPRINTFN(n,x)	do { if (ehcidebug>(n)) printf x; } while (0)
int ehcidebug = 0;
#define bitmask_snprintf(q,f,b,l) snprintf((b), (l), "%b", (q), (f))
#else
#define DPRINTF(x)
#define DPRINTFN(n,x)
#endif

struct pool *ehcixfer;

struct ehci_pipe {
	struct usbd_pipe pipe;

	struct ehci_soft_qh *sqh;
	union {
		/* Control pipe */
		struct {
			struct usb_dma reqdma;
		} ctl;
		/* Iso pipe */
		struct {
			u_int next_frame;
			u_int cur_xfers;
		} isoc;
	} u;
};

u_int8_t		ehci_reverse_bits(u_int8_t, int);

usbd_status	ehci_open(struct usbd_pipe *);
int		ehci_setaddr(struct usbd_device *, int);
void		ehci_poll(struct usbd_bus *);
void		ehci_softintr(void *);
int		ehci_intr1(struct ehci_softc *);
void		ehci_waitintr(struct ehci_softc *, struct usbd_xfer *);
void		ehci_check_intr(struct ehci_softc *, struct usbd_xfer *);
void		ehci_check_qh_intr(struct ehci_softc *, struct usbd_xfer *);
void		ehci_check_itd_intr(struct ehci_softc *, struct usbd_xfer *);
void		ehci_idone(struct usbd_xfer *);
void		ehci_timeout(void *);
void		ehci_timeout_task(void *);
void		ehci_intrlist_timeout(void *);

struct usbd_xfer *ehci_allocx(struct usbd_bus *);
void		ehci_freex(struct usbd_bus *, struct usbd_xfer *);

usbd_status	ehci_root_ctrl_transfer(struct usbd_xfer *);
usbd_status	ehci_root_ctrl_start(struct usbd_xfer *);
void		ehci_root_ctrl_abort(struct usbd_xfer *);
void		ehci_root_ctrl_close(struct usbd_pipe *);
void		ehci_root_ctrl_done(struct usbd_xfer *);

usbd_status	ehci_root_intr_transfer(struct usbd_xfer *);
usbd_status	ehci_root_intr_start(struct usbd_xfer *);
void		ehci_root_intr_abort(struct usbd_xfer *);
void		ehci_root_intr_close(struct usbd_pipe *);
void		ehci_root_intr_done(struct usbd_xfer *);

usbd_status	ehci_device_ctrl_transfer(struct usbd_xfer *);
usbd_status	ehci_device_ctrl_start(struct usbd_xfer *);
void		ehci_device_ctrl_abort(struct usbd_xfer *);
void		ehci_device_ctrl_close(struct usbd_pipe *);
void		ehci_device_ctrl_done(struct usbd_xfer *);

usbd_status	ehci_device_bulk_transfer(struct usbd_xfer *);
usbd_status	ehci_device_bulk_start(struct usbd_xfer *);
void		ehci_device_bulk_abort(struct usbd_xfer *);
void		ehci_device_bulk_close(struct usbd_pipe *);
void		ehci_device_bulk_done(struct usbd_xfer *);

usbd_status	ehci_device_intr_transfer(struct usbd_xfer *);
usbd_status	ehci_device_intr_start(struct usbd_xfer *);
void		ehci_device_intr_abort(struct usbd_xfer *);
void		ehci_device_intr_close(struct usbd_pipe *);
void		ehci_device_intr_done(struct usbd_xfer *);

usbd_status	ehci_device_isoc_transfer(struct usbd_xfer *);
usbd_status	ehci_device_isoc_start(struct usbd_xfer *);
void		ehci_device_isoc_abort(struct usbd_xfer *);
void		ehci_device_isoc_close(struct usbd_pipe *);
void		ehci_device_isoc_done(struct usbd_xfer *);

void		ehci_device_clear_toggle(struct usbd_pipe *pipe);

void		ehci_pcd(struct ehci_softc *, struct usbd_xfer *);
void		ehci_disown(struct ehci_softc *, int, int);

struct ehci_soft_qh *ehci_alloc_sqh(struct ehci_softc *);
void		ehci_free_sqh(struct ehci_softc *, struct ehci_soft_qh *);

struct ehci_soft_qtd *ehci_alloc_sqtd(struct ehci_softc *);
void		ehci_free_sqtd(struct ehci_softc *, struct ehci_soft_qtd *);
usbd_status	ehci_alloc_sqtd_chain(struct ehci_softc *, u_int,
		    struct usbd_xfer *, struct ehci_soft_qtd **, struct ehci_soft_qtd **);
void		ehci_free_sqtd_chain(struct ehci_softc *, struct ehci_xfer *);

struct ehci_soft_itd *ehci_alloc_itd(struct ehci_softc *sc);
void		ehci_free_itd(struct ehci_softc *sc, struct ehci_soft_itd *itd);
void		ehci_rem_free_itd_chain(struct ehci_softc *sc,
		    struct ehci_xfer *);
void		ehci_abort_isoc_xfer(struct usbd_xfer *xfer,
		    usbd_status status);

usbd_status	ehci_device_request(struct usbd_xfer *xfer);

usbd_status	ehci_device_setintr(struct ehci_softc *, struct ehci_soft_qh *,
			    int ival);

void		ehci_add_qh(struct ehci_soft_qh *, struct ehci_soft_qh *);
void		ehci_rem_qh(struct ehci_softc *, struct ehci_soft_qh *);
void		ehci_set_qh_qtd(struct ehci_soft_qh *, struct ehci_soft_qtd *);
void		ehci_sync_hc(struct ehci_softc *);

void		ehci_close_pipe(struct usbd_pipe *);
void		ehci_abort_xfer(struct usbd_xfer *, usbd_status);

#ifdef EHCI_DEBUG
void		ehci_dump_regs(struct ehci_softc *);
void		ehci_dump(void);
struct ehci_softc *theehci;
void		ehci_dump_link(ehci_link_t, int);
void		ehci_dump_sqtds(struct ehci_soft_qtd *);
void		ehci_dump_sqtd(struct ehci_soft_qtd *);
void		ehci_dump_qtd(struct ehci_qtd *);
void		ehci_dump_sqh(struct ehci_soft_qh *);
#if notyet
void		ehci_dump_sitd(struct ehci_soft_itd *itd);
void		ehci_dump_itd(struct ehci_soft_itd *);
#endif
#ifdef DIAGNOSTIC
void		ehci_dump_exfer(struct ehci_xfer *);
#endif
#endif

#define EHCI_INTR_ENDPT 1

#define ehci_add_intr_list(sc, ex) \
	TAILQ_INSERT_TAIL(&(sc)->sc_intrhead, (ex), inext);
#define ehci_del_intr_list(sc, ex) \
	do { \
		TAILQ_REMOVE(&sc->sc_intrhead, (ex), inext); \
		(ex)->inext.tqe_prev = NULL; \
	} while (0)
#define ehci_active_intr_list(ex) ((ex)->inext.tqe_prev != NULL)

struct usbd_bus_methods ehci_bus_methods = {
	.open_pipe = ehci_open,
	.dev_setaddr = ehci_setaddr,
	.soft_intr = ehci_softintr,
	.do_poll = ehci_poll,
	.allocx = ehci_allocx,
	.freex = ehci_freex,
};

struct usbd_pipe_methods ehci_root_ctrl_methods = {
	.transfer = ehci_root_ctrl_transfer,
	.start = ehci_root_ctrl_start,
	.abort = ehci_root_ctrl_abort,
	.close = ehci_root_ctrl_close,
	.done = ehci_root_ctrl_done,
};

struct usbd_pipe_methods ehci_root_intr_methods = {
	.transfer = ehci_root_intr_transfer,
	.start = ehci_root_intr_start,
	.abort = ehci_root_intr_abort,
	.close = ehci_root_intr_close,
	.done = ehci_root_intr_done,
};

struct usbd_pipe_methods ehci_device_ctrl_methods = {
	.transfer = ehci_device_ctrl_transfer,
	.start = ehci_device_ctrl_start,
	.abort = ehci_device_ctrl_abort,
	.close = ehci_device_ctrl_close,
	.done = ehci_device_ctrl_done,
};

struct usbd_pipe_methods ehci_device_intr_methods = {
	.transfer = ehci_device_intr_transfer,
	.start = ehci_device_intr_start,
	.abort = ehci_device_intr_abort,
	.close = ehci_device_intr_close,
	.cleartoggle = ehci_device_clear_toggle,
	.done = ehci_device_intr_done,
};

struct usbd_pipe_methods ehci_device_bulk_methods = {
	.transfer = ehci_device_bulk_transfer,
	.start = ehci_device_bulk_start,
	.abort = ehci_device_bulk_abort,
	.close = ehci_device_bulk_close,
	.cleartoggle = ehci_device_clear_toggle,
	.done = ehci_device_bulk_done,
};

struct usbd_pipe_methods ehci_device_isoc_methods = {
	.transfer = ehci_device_isoc_transfer,
	.start = ehci_device_isoc_start,
	.abort = ehci_device_isoc_abort,
	.close = ehci_device_isoc_close,
	.done = ehci_device_isoc_done,
};

/*
 * Reverse a number with nbits bits.  Used to evenly distribute lower-level
 * interrupt heads in the periodic schedule.
 * Suitable for use with EHCI_IPOLLRATES <= 9.
 */
u_int8_t
ehci_reverse_bits(u_int8_t c, int nbits)
{
	c = ((c >> 1) & 0x55) | ((c << 1) & 0xaa);
	c = ((c >> 2) & 0x33) | ((c << 2) & 0xcc);
	c = ((c >> 4) & 0x0f) | ((c << 4) & 0xf0);

	return c >> (8 - nbits);
}

usbd_status
ehci_init(struct ehci_softc *sc)
{
	u_int32_t sparams, cparams, hcr;
	u_int i, j;
	usbd_status err;
	struct ehci_soft_qh *sqh;

#ifdef EHCI_DEBUG
	u_int32_t vers;
	theehci = sc;

	DPRINTF(("ehci_init: start\n"));

	vers = EREAD2(sc, EHCI_HCIVERSION);
	DPRINTF(("%s: EHCI version %x.%x\n", sc->sc_bus.bdev.dv_xname,
	    vers >> 8, vers & 0xff));
#endif

	sc->sc_offs = EREAD1(sc, EHCI_CAPLENGTH);

	sparams = EREAD4(sc, EHCI_HCSPARAMS);
	DPRINTF(("ehci_init: sparams=0x%x\n", sparams));
	sc->sc_noport = EHCI_HCS_N_PORTS(sparams);
	cparams = EREAD4(sc, EHCI_HCCPARAMS);
	DPRINTF(("ehci_init: cparams=0x%x\n", cparams));

	/* MUST clear segment register if 64 bit capable. */
	if (EHCI_HCC_64BIT(cparams))
		EWRITE4(sc, EHCI_CTRLDSSEGMENT, 0);

	sc->sc_bus.usbrev = USBREV_2_0;

	DPRINTF(("%s: resetting\n", sc->sc_bus.bdev.dv_xname));
	err = ehci_reset(sc);
	if (err)
		return (err);

	if (ehcixfer == NULL) {
		ehcixfer = malloc(sizeof(struct pool), M_DEVBUF, M_NOWAIT);
		if (ehcixfer == NULL) {
			printf("%s: unable to allocate pool descriptor\n",
			    sc->sc_bus.bdev.dv_xname);
			return (ENOMEM);
		}
		pool_init(ehcixfer, sizeof(struct ehci_xfer), 0, 0, 0,
		    "ehcixfer", NULL);
		pool_setipl(ehcixfer, IPL_SOFTUSB);
	}

	/* frame list size at default, read back what we got and use that */
	switch (EHCI_CMD_FLS(EOREAD4(sc, EHCI_USBCMD))) {
	case 0:
		sc->sc_flsize = 1024;
		break;
	case 1:
		sc->sc_flsize = 512;
		break;
	case 2:
		sc->sc_flsize = 256;
		break;
	case 3:
		return (USBD_IOERROR);
	}
	err = usb_allocmem(&sc->sc_bus, sc->sc_flsize * sizeof(ehci_link_t),
	    EHCI_FLALIGN_ALIGN, &sc->sc_fldma);
	if (err)
		return (err);
	DPRINTF(("%s: flsize=%d\n", sc->sc_bus.bdev.dv_xname,sc->sc_flsize));
	sc->sc_flist = KERNADDR(&sc->sc_fldma, 0);

	for (i = 0; i < sc->sc_flsize; i++)
		sc->sc_flist[i] = htole32(EHCI_LINK_TERMINATE);

	EOWRITE4(sc, EHCI_PERIODICLISTBASE, DMAADDR(&sc->sc_fldma, 0));

	sc->sc_softitds = malloc(sc->sc_flsize * sizeof(struct ehci_soft_itd *),
	    M_USB, M_NOWAIT | M_ZERO);
	if (sc->sc_softitds == NULL)
		return (ENOMEM);
	LIST_INIT(&sc->sc_freeitds);
	TAILQ_INIT(&sc->sc_intrhead);

	/* Set up the bus struct. */
	sc->sc_bus.methods = &ehci_bus_methods;
	sc->sc_bus.pipe_size = sizeof(struct ehci_pipe);

	sc->sc_eintrs = EHCI_NORMAL_INTRS;

	/*
	 * Allocate the interrupt dummy QHs. These are arranged to give poll
	 * intervals that are powers of 2 times 1ms.
	 */
	for (i = 0; i < EHCI_INTRQHS; i++) {
		sqh = ehci_alloc_sqh(sc);
		if (sqh == NULL) {
			err = USBD_NOMEM;
			goto bad1;
		}
		sc->sc_islots[i].sqh = sqh;
	}
	for (i = 0; i < EHCI_INTRQHS; i++) {
		sqh = sc->sc_islots[i].sqh;
		if (i == 0) {
			/* The last (1ms) QH terminates. */
			sqh->qh.qh_link = htole32(EHCI_LINK_TERMINATE);
			sqh->next = NULL;
		} else {
			/* Otherwise the next QH has half the poll interval */
			sqh->next = sc->sc_islots[(i + 1) / 2 - 1].sqh;
			sqh->qh.qh_link = htole32(sqh->next->physaddr |
			    EHCI_LINK_QH);
		}
		sqh->qh.qh_endp = htole32(EHCI_QH_SET_EPS(EHCI_QH_SPEED_HIGH));
		sqh->qh.qh_endphub = htole32(EHCI_QH_SET_MULT(1));
		sqh->qh.qh_curqtd = htole32(EHCI_LINK_TERMINATE);
		sqh->qh.qh_qtd.qtd_next = htole32(EHCI_LINK_TERMINATE);
		sqh->qh.qh_qtd.qtd_altnext = htole32(EHCI_LINK_TERMINATE);
		sqh->qh.qh_qtd.qtd_status = htole32(EHCI_QTD_HALTED);
		sqh->sqtd = NULL;
		usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
	}
	/* Point the frame list at the last level (128ms). */
	for (i = 0; i < (1 << (EHCI_IPOLLRATES - 1)); i++)
		for (j = i; j < sc->sc_flsize; j += 1 << (EHCI_IPOLLRATES - 1))
			sc->sc_flist[j] = htole32(EHCI_LINK_QH | sc->sc_islots[
			    EHCI_IQHIDX(EHCI_IPOLLRATES - 1, ehci_reverse_bits(
			    i, EHCI_IPOLLRATES - 1))].sqh->physaddr);
	usb_syncmem(&sc->sc_fldma, 0, sc->sc_flsize * sizeof(ehci_link_t),
	    BUS_DMASYNC_PREWRITE);

	/* Allocate dummy QH that starts the async list. */
	sqh = ehci_alloc_sqh(sc);
	if (sqh == NULL) {
		err = USBD_NOMEM;
		goto bad1;
	}
	/* Fill the QH */
	sqh->qh.qh_endp =
	    htole32(EHCI_QH_SET_EPS(EHCI_QH_SPEED_HIGH) | EHCI_QH_HRECL);
	sqh->qh.qh_link =
	    htole32(sqh->physaddr | EHCI_LINK_QH);
	sqh->qh.qh_curqtd = htole32(EHCI_LINK_TERMINATE);
	sqh->prev = sqh; /*It's a circular list.. */
	sqh->next = sqh;
	/* Fill the overlay qTD */
	sqh->qh.qh_qtd.qtd_next = htole32(EHCI_LINK_TERMINATE);
	sqh->qh.qh_qtd.qtd_altnext = htole32(EHCI_LINK_TERMINATE);
	sqh->qh.qh_qtd.qtd_status = htole32(EHCI_QTD_HALTED);
	sqh->sqtd = NULL;
	usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
#ifdef EHCI_DEBUG
	if (ehcidebug)
		ehci_dump_sqh(sqh);
#endif

	/* Point to async list */
	sc->sc_async_head = sqh;
	EOWRITE4(sc, EHCI_ASYNCLISTADDR, sqh->physaddr | EHCI_LINK_QH);

	timeout_set(&sc->sc_tmo_intrlist, ehci_intrlist_timeout, sc);

	rw_init(&sc->sc_doorbell_lock, "ehcidb");

	/* Turn on controller */
	EOWRITE4(sc, EHCI_USBCMD,
	    EHCI_CMD_ITC_2 | /* 2 microframes interrupt delay */
	    (EOREAD4(sc, EHCI_USBCMD) & EHCI_CMD_FLS_M) |
	    EHCI_CMD_ASE |
	    EHCI_CMD_PSE |
	    EHCI_CMD_RS);

	/* Take over port ownership */
	EOWRITE4(sc, EHCI_CONFIGFLAG, EHCI_CONF_CF);

	for (i = 0; i < 100; i++) {
		usb_delay_ms(&sc->sc_bus, 1);
		hcr = EOREAD4(sc, EHCI_USBSTS) & EHCI_STS_HCH;
		if (!hcr)
			break;
	}
	if (hcr) {
		printf("%s: run timeout\n", sc->sc_bus.bdev.dv_xname);
		return (USBD_IOERROR);
	}

	/* Enable interrupts */
	DPRINTFN(1,("ehci_init: enabling\n"));
	EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs);

	return (USBD_NORMAL_COMPLETION);

#if 0
 bad2:
	ehci_free_sqh(sc, sc->sc_async_head);
#endif
 bad1:
	usb_freemem(&sc->sc_bus, &sc->sc_fldma);
	return (err);
}

int
ehci_intr(void *v)
{
	struct ehci_softc *sc = v;

	if (sc == NULL || sc->sc_bus.dying)
		return (0);

	/* If we get an interrupt while polling, then just ignore it. */
	if (sc->sc_bus.use_polling) {
		u_int32_t intrs = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS));

		if (intrs)
			EOWRITE4(sc, EHCI_USBSTS, intrs); /* Acknowledge */
		return (0);
	}

	return (ehci_intr1(sc));
}

int
ehci_intr1(struct ehci_softc *sc)
{
	u_int32_t intrs, eintrs;

	DPRINTFN(20,("ehci_intr1: enter\n"));

	/* In case the interrupt occurs before initialization has completed. */
	if (sc == NULL) {
#ifdef DIAGNOSTIC
		printf("ehci_intr1: sc == NULL\n");
#endif
		return (0);
	}

	intrs = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS));
	if (intrs == 0xffffffff) {
		sc->sc_bus.dying = 1;
		return (0);
	}
	if (!intrs)
		return (0);

	eintrs = intrs & sc->sc_eintrs;
	DPRINTFN(7, ("ehci_intr1: sc=%p intrs=0x%x(0x%x) eintrs=0x%x\n",
	     sc, (u_int)intrs, EOREAD4(sc, EHCI_USBSTS), (u_int)eintrs));
	if (!eintrs)
		return (0);

	EOWRITE4(sc, EHCI_USBSTS, intrs); /* Acknowledge */
	sc->sc_bus.intr_context++;
	sc->sc_bus.no_intrs++;
	if (eintrs & EHCI_STS_HSE) {
		printf("%s: unrecoverable error, controller halted\n",
		       sc->sc_bus.bdev.dv_xname);
		sc->sc_bus.dying = 1;
		sc->sc_bus.intr_context--;
		return (1);
	}
	if (eintrs & EHCI_STS_IAA) {
		DPRINTF(("ehci_intr1: door bell\n"));
		wakeup(&sc->sc_async_head);
		eintrs &= ~EHCI_STS_IAA;
	}
	if (eintrs & (EHCI_STS_INT | EHCI_STS_ERRINT)) {
		DPRINTFN(5,("ehci_intr1: %s %s\n",
			    eintrs & EHCI_STS_INT ? "INT" : "",
			    eintrs & EHCI_STS_ERRINT ? "ERRINT" : ""));
		usb_schedsoftintr(&sc->sc_bus);
		eintrs &= ~(EHCI_STS_INT | EHCI_STS_ERRINT);
	}
	if (eintrs & EHCI_STS_PCD) {
		ehci_pcd(sc, sc->sc_intrxfer);
		eintrs &= ~EHCI_STS_PCD;
	}

	sc->sc_bus.intr_context--;

	if (eintrs != 0) {
		/* Block unprocessed interrupts. */
		sc->sc_eintrs &= ~eintrs;
		EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs);
		printf("%s: blocking intrs 0x%x\n",
		       sc->sc_bus.bdev.dv_xname, eintrs);
	}

	return (1);
}

void
ehci_pcd(struct ehci_softc *sc, struct usbd_xfer *xfer)
{
	u_char *p;
	int i, m;

	if (xfer == NULL) {
		/* Just ignore the change. */
		return;
	}

	p = KERNADDR(&xfer->dmabuf, 0);
	m = min(sc->sc_noport, xfer->length * 8 - 1);
	memset(p, 0, xfer->length);
	for (i = 1; i <= m; i++) {
		/* Pick out CHANGE bits from the status reg. */
		if (EOREAD4(sc, EHCI_PORTSC(i)) & EHCI_PS_CLEAR)
			p[i/8] |= 1 << (i%8);
	}
	DPRINTF(("ehci_pcd: change=0x%02x\n", *p));
	xfer->actlen = xfer->length;
	xfer->status = USBD_NORMAL_COMPLETION;

	usb_transfer_complete(xfer);
}

/*
 * Work around the half configured control (default) pipe when setting
 * the address of a device.
 *
 * Because a single QH is setup per endpoint in ehci_open(), and the
 * control pipe is configured before we could have set the address
 * of the device or read the wMaxPacketSize of the endpoint, we have
 * to re-open the pipe twice here.
 */
int
ehci_setaddr(struct usbd_device *dev, int addr)
{
	/* Root Hub */
	if (dev->depth == 0)
		return (0);

	/* Re-establish the default pipe with the new max packet size. */
	ehci_close_pipe(dev->default_pipe);
	if (ehci_open(dev->default_pipe))
		return (EINVAL);

	if (usbd_set_address(dev, addr))
		return (1);

	dev->address = addr;

	/* Re-establish the default pipe with the new address. */
	ehci_close_pipe(dev->default_pipe);
	if (ehci_open(dev->default_pipe))
		return (EINVAL);

	return (0);
}

void
ehci_softintr(void *v)
{
	struct ehci_softc *sc = v;
	struct ehci_xfer *ex, *nextex;

	DPRINTFN(10,("%s: ehci_softintr (%d)\n", sc->sc_bus.bdev.dv_xname,
		     sc->sc_bus.intr_context));

	if (sc->sc_bus.dying)
		return;

	sc->sc_bus.intr_context++;

	/*
	 * The only explanation I can think of for why EHCI is as brain dead
	 * as UHCI interrupt-wise is that Intel was involved in both.
	 * An interrupt just tells us that something is done, we have no
	 * clue what, so we need to scan through all active transfers. :-(
	 */
	for (ex = TAILQ_FIRST(&sc->sc_intrhead); ex; ex = nextex) {
		nextex = TAILQ_NEXT(ex, inext);
		ehci_check_intr(sc, &ex->xfer);
	}

	/* Schedule a callout to catch any dropped transactions. */
	if ((sc->sc_flags & EHCIF_DROPPED_INTR_WORKAROUND) &&
	    !TAILQ_EMPTY(&sc->sc_intrhead)) {
		timeout_add_sec(&sc->sc_tmo_intrlist, 1);
	}

	if (sc->sc_softwake) {
		sc->sc_softwake = 0;
		wakeup(&sc->sc_softwake);
	}

	sc->sc_bus.intr_context--;
}

/* Check for an interrupt. */
void
ehci_check_intr(struct ehci_softc *sc, struct usbd_xfer *xfer)
{
	int attr;

	DPRINTFN(2, ("%s: xfer=%p\n", __func__, xfer));

	attr = xfer->pipe->endpoint->edesc->bmAttributes;
	if (UE_GET_XFERTYPE(attr) == UE_ISOCHRONOUS)
		ehci_check_itd_intr(sc, xfer);
	else
		ehci_check_qh_intr(sc, xfer);

	return;
}

void
ehci_check_qh_intr(struct ehci_softc *sc, struct usbd_xfer *xfer)
{
	struct ehci_xfer *ex = (struct ehci_xfer *)xfer;
	struct ehci_soft_qtd *sqtd, *lsqtd;
	uint32_t status;

	if (ex->sqtdstart == NULL) {
		printf("ehci_check_qh_intr: not valid sqtd\n");
		return;
	}

	lsqtd = ex->sqtdend;
#ifdef DIAGNOSTIC
	if (lsqtd == NULL) {
		printf("ehci_check_qh_intr: lsqtd==0\n");
		return;
	}
#endif
	/*
	 * If the last TD is still active we need to check whether there
	 * is a an error somewhere in the middle, or whether there was a
	 * short packet (SPD and not ACTIVE).
	 */
	usb_syncmem(&lsqtd->dma,
	    lsqtd->offs + offsetof(struct ehci_qtd, qtd_status),
	    sizeof(lsqtd->qtd.qtd_status),
	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
	if (letoh32(lsqtd->qtd.qtd_status) & EHCI_QTD_ACTIVE) {
		DPRINTFN(12, ("ehci_check_intr: active ex=%p\n", ex));
		for (sqtd = ex->sqtdstart; sqtd != lsqtd; sqtd=sqtd->nextqtd) {
			usb_syncmem(&sqtd->dma,
			    sqtd->offs + offsetof(struct ehci_qtd, qtd_status),
			    sizeof(sqtd->qtd.qtd_status),
			    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
			status = letoh32(sqtd->qtd.qtd_status);
			usb_syncmem(&sqtd->dma,
			    sqtd->offs + offsetof(struct ehci_qtd, qtd_status),
			    sizeof(sqtd->qtd.qtd_status), BUS_DMASYNC_PREREAD);
			/* If there's an active QTD the xfer isn't done. */
			if (status & EHCI_QTD_ACTIVE)
				break;
			/* Any kind of error makes the xfer done. */
			if (status & EHCI_QTD_HALTED)
				goto done;
			/* We want short packets, and it is short: it's done */
			if (EHCI_QTD_GET_BYTES(status) != 0)
				goto done;
		}
		DPRINTFN(12, ("ehci_check_intr: ex=%p std=%p still active\n",
			      ex, ex->sqtdstart));
		usb_syncmem(&lsqtd->dma,
		    lsqtd->offs + offsetof(struct ehci_qtd, qtd_status),
		    sizeof(lsqtd->qtd.qtd_status), BUS_DMASYNC_PREREAD);
		return;
	}
 done:
	DPRINTFN(12, ("ehci_check_intr: ex=%p done\n", ex));
	timeout_del(&xfer->timeout_handle);
	usb_rem_task(xfer->pipe->device, &xfer->abort_task);
	ehci_idone(xfer);
}

void
ehci_check_itd_intr(struct ehci_softc *sc, struct usbd_xfer *xfer)
{
	struct ehci_xfer *ex = (struct ehci_xfer *)xfer;
	struct ehci_soft_itd *itd;
	int i;

	if (xfer != SIMPLEQ_FIRST(&xfer->pipe->queue))
		return;

	if (ex->itdstart == NULL) {
		printf("ehci_check_itd_intr: not valid itd\n");
		return;
	}

	itd = ex->itdend;
#ifdef DIAGNOSTIC
	if (itd == NULL) {
		printf("ehci_check_itd_intr: itdend == 0\n");
		return;
	}
#endif

	/*
	 * check no active transfers in last itd, meaning we're finished
	 */

	usb_syncmem(&itd->dma, itd->offs + offsetof(struct ehci_itd, itd_ctl),
	    sizeof(itd->itd.itd_ctl), BUS_DMASYNC_POSTWRITE |
	    BUS_DMASYNC_POSTREAD);

	for (i = 0; i < 8; i++) {
		if (letoh32(itd->itd.itd_ctl[i]) & EHCI_ITD_ACTIVE)
			break;
	}

	if (i == 8) {
		goto done; /* All 8 descriptors inactive, it's done */
	}

	DPRINTFN(12, ("ehci_check_itd_intr: ex %p itd %p still active\n", ex,
	    ex->itdstart));
	return;
done:
	DPRINTFN(12, ("ehci_check_itd_intr: ex=%p done\n", ex));
	timeout_del(&xfer->timeout_handle);
	usb_rem_task(xfer->pipe->device, &xfer->abort_task);
	ehci_idone(xfer);
}

void
ehci_idone(struct usbd_xfer *xfer)
{
	struct ehci_xfer *ex = (struct ehci_xfer *)xfer;
#ifdef EHCI_DEBUG
	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
#endif
	struct ehci_soft_qtd *sqtd;
	u_int32_t status = 0, nstatus = 0;
	int actlen, cerr;

	DPRINTFN(/*12*/2, ("ehci_idone: ex=%p\n", ex));
#ifdef DIAGNOSTIC
	{
		int s = splhigh();
		if (ex->isdone) {
			splx(s);
#ifdef EHCI_DEBUG
			printf("ehci_idone: ex is done!\n   ");
			ehci_dump_exfer(ex);
#else
			printf("ehci_idone: ex=%p is done!\n", ex);
#endif
			return;
		}
		ex->isdone = 1;
		splx(s);
	}
#endif
	if (xfer->status == USBD_CANCELLED ||
	    xfer->status == USBD_TIMEOUT) {
		DPRINTF(("ehci_idone: aborted xfer=%p\n", xfer));
		return;
	}

#ifdef EHCI_DEBUG
	DPRINTFN(/*10*/2, ("ehci_idone: xfer=%p, pipe=%p ready\n", xfer, epipe));
	if (ehcidebug > 10)
		ehci_dump_sqtds(ex->sqtdstart);
#endif

	/* The transfer is done, compute actual length and status. */

	if (UE_GET_XFERTYPE(xfer->pipe->endpoint->edesc->bmAttributes)
	    == UE_ISOCHRONOUS) {
		/* Isoc transfer */
		struct ehci_soft_itd *itd;
		int i, nframes, len, uframes;

		nframes = 0;
		actlen = 0;

		switch (xfer->pipe->endpoint->edesc->bInterval) {
		case 0:
			panic("ehci: isoc xfer suddenly has 0 bInterval, "
			    "invalid");
		case 1:
			uframes = 1;
			break;
		case 2:
			uframes = 2;
			break;
		case 3:
			uframes = 4;
			break;
		default:
			uframes = 8;
			break;
		}

		for (itd = ex->itdstart; itd != NULL; itd = itd->xfer_next) {
			usb_syncmem(&itd->dma,
			    itd->offs + offsetof(struct ehci_itd, itd_ctl),
			    sizeof(itd->itd.itd_ctl), BUS_DMASYNC_POSTWRITE |
			    BUS_DMASYNC_POSTREAD);

			for (i = 0; i < 8; i += uframes) {
				/* XXX - driver didn't fill in the frame full
				 *   of uframes. This leads to scheduling
				 *   inefficiencies, but working around
				 *   this doubles complexity of tracking
				 *   an xfer.
				 */
				if (nframes >= xfer->nframes)
					break;

				status = letoh32(itd->itd.itd_ctl[i]);
				len = EHCI_ITD_GET_LEN(status);
				if (EHCI_ITD_GET_STATUS(status) != 0)
					len = 0; /*No valid data on error*/

				xfer->frlengths[nframes++] = len;
				actlen += len;
			}

			if (nframes >= xfer->nframes)
				break;
		}

		xfer->actlen = actlen;
		xfer->status = USBD_NORMAL_COMPLETION;

		goto end;
	}

	/* Continue processing xfers using queue heads */

	actlen = 0;
	for (sqtd = ex->sqtdstart; sqtd != NULL; sqtd = sqtd->nextqtd) {
		usb_syncmem(&sqtd->dma, sqtd->offs, sizeof(sqtd->qtd),
		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
		nstatus = letoh32(sqtd->qtd.qtd_status);
		if (nstatus & EHCI_QTD_ACTIVE)
			break;

		status = nstatus;
		/* halt is ok if descriptor is last, and complete */
		if (sqtd->qtd.qtd_next == htole32(EHCI_LINK_TERMINATE) &&
		    EHCI_QTD_GET_BYTES(status) == 0)
			status &= ~EHCI_QTD_HALTED;
		if (EHCI_QTD_GET_PID(status) !=	EHCI_QTD_PID_SETUP)
			actlen += sqtd->len - EHCI_QTD_GET_BYTES(status);
	}

	cerr = EHCI_QTD_GET_CERR(status);
	DPRINTFN(/*10*/2, ("ehci_idone: len=%d, actlen=%d, cerr=%d, "
	    "status=0x%x\n", xfer->length, actlen, cerr, status));
	xfer->actlen = actlen;
	if ((status & EHCI_QTD_HALTED) != 0) {
#ifdef EHCI_DEBUG
		char sbuf[128];

		bitmask_snprintf((u_int32_t)status,
		    "\20\7HALTED\6BUFERR\5BABBLE\4XACTERR"
		    "\3MISSED\2SPLIT\1PING", sbuf, sizeof(sbuf));

		DPRINTFN(2,
			 ("ehci_idone: error, addr=%d, endpt=0x%02x, "
			  "status 0x%s\n",
			  xfer->device->address,
			  xfer->pipe->endpoint->edesc->bEndpointAddress,
			  sbuf));
		if (ehcidebug > 2) {
			ehci_dump_sqh(epipe->sqh);
			ehci_dump_sqtds(ex->sqtdstart);
		}
#endif
		if ((status & EHCI_QTD_BABBLE) == 0 && cerr > 0)
			xfer->status = USBD_STALLED;
		else
			xfer->status = USBD_IOERROR; /* more info XXX */
	} else
		xfer->status = USBD_NORMAL_COMPLETION;
	end:
	/* XXX transfer_complete memcpys out transfer data (for in endpoints)
	 * during this call, before methods->done is called: dma sync required
	 * beforehand? */
	usb_transfer_complete(xfer);
	DPRINTFN(/*12*/2, ("ehci_idone: ex=%p done\n", ex));
}

/*
 * Wait here until controller claims to have an interrupt.
 * Then call ehci_intr and return.  Use timeout to avoid waiting
 * too long.
 */
void
ehci_waitintr(struct ehci_softc *sc, struct usbd_xfer *xfer)
{
	int timo;
	u_int32_t intrs;

	xfer->status = USBD_IN_PROGRESS;
	for (timo = xfer->timeout; timo >= 0; timo--) {
		usb_delay_ms(&sc->sc_bus, 1);
		if (sc->sc_bus.dying)
			break;
		intrs = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS)) &
			sc->sc_eintrs;
		DPRINTFN(15,("ehci_waitintr: 0x%04x\n", intrs));
#ifdef EHCI_DEBUG
		if (ehcidebug > 15)
			ehci_dump_regs(sc);
#endif
		if (intrs) {
			ehci_intr1(sc);
			if (xfer->status != USBD_IN_PROGRESS)
				return;
		}
	}

	/* Timeout */
	DPRINTF(("ehci_waitintr: timeout\n"));
	xfer->status = USBD_TIMEOUT;
	usb_transfer_complete(xfer);
	/* XXX should free TD */
}

void
ehci_poll(struct usbd_bus *bus)
{
	struct ehci_softc *sc = (struct ehci_softc *)bus;
#ifdef EHCI_DEBUG
	static int last;
	int new;
	new = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS));
	if (new != last) {
		DPRINTFN(10,("ehci_poll: intrs=0x%04x\n", new));
		last = new;
	}
#endif

	if (EOREAD4(sc, EHCI_USBSTS) & sc->sc_eintrs)
		ehci_intr1(sc);
}

int
ehci_detach(struct device *self, int flags)
{
	struct ehci_softc *sc = (struct ehci_softc *)self;
	int rv;

	rv = config_detach_children(self, flags);
	if (rv != 0)
		return (rv);

	timeout_del(&sc->sc_tmo_intrlist);

	ehci_reset(sc);

	usb_delay_ms(&sc->sc_bus, 300); /* XXX let stray task complete */

	/* XXX free other data structures XXX */

	return (rv);
}


int
ehci_activate(struct device *self, int act)
{
	struct ehci_softc *sc = (struct ehci_softc *)self;
	u_int32_t cmd, hcr, cparams;
	int i, rv = 0;

	switch (act) {
	case DVACT_SUSPEND:
		rv = config_activate_children(self, act);
		sc->sc_bus.use_polling++;

		for (i = 1; i <= sc->sc_noport; i++) {
			cmd = EOREAD4(sc, EHCI_PORTSC(i));
			if ((cmd & (EHCI_PS_PO|EHCI_PS_PE)) == EHCI_PS_PE)
				EOWRITE4(sc, EHCI_PORTSC(i),
				    cmd | EHCI_PS_SUSP);
		}

		/*
		 * First tell the host to stop processing Asynchronous
		 * and Periodic schedules.
		 */
		cmd = EOREAD4(sc, EHCI_USBCMD) & ~(EHCI_CMD_ASE | EHCI_CMD_PSE);
		EOWRITE4(sc, EHCI_USBCMD, cmd);
		for (i = 0; i < 100; i++) {
			usb_delay_ms(&sc->sc_bus, 1);
			hcr = EOREAD4(sc, EHCI_USBSTS) &
			    (EHCI_STS_ASS | EHCI_STS_PSS);
			if (hcr == 0)
				break;
		}
		if (hcr != 0)
			printf("%s: disable schedules timeout\n",
			    sc->sc_bus.bdev.dv_xname);

		/*
		 * Then reset the host as if it was a shutdown.
		 *
		 * All USB devices are disconnected/reconnected during
		 * a suspend/resume cycle so keep it simple.
		 */
		ehci_reset(sc);

		sc->sc_bus.use_polling--;
		break;
	case DVACT_RESUME:
		sc->sc_bus.use_polling++;

		ehci_reset(sc);

		cparams = EREAD4(sc, EHCI_HCCPARAMS);
		/* MUST clear segment register if 64 bit capable. */
		if (EHCI_HCC_64BIT(cparams))
			EWRITE4(sc, EHCI_CTRLDSSEGMENT, 0);

		EOWRITE4(sc, EHCI_PERIODICLISTBASE, DMAADDR(&sc->sc_fldma, 0));
		EOWRITE4(sc, EHCI_ASYNCLISTADDR,
	  	    sc->sc_async_head->physaddr | EHCI_LINK_QH);

		hcr = 0;
		for (i = 1; i <= sc->sc_noport; i++) {
			cmd = EOREAD4(sc, EHCI_PORTSC(i));
			if ((cmd & (EHCI_PS_PO|EHCI_PS_SUSP)) == EHCI_PS_SUSP) {
				EOWRITE4(sc, EHCI_PORTSC(i), cmd | EHCI_PS_FPR);
				hcr = 1;
			}
		}

		if (hcr) {
			usb_delay_ms(&sc->sc_bus, USB_RESUME_WAIT);
			for (i = 1; i <= sc->sc_noport; i++) {
				cmd = EOREAD4(sc, EHCI_PORTSC(i));
				if ((cmd & (EHCI_PS_PO|EHCI_PS_SUSP)) ==
				   EHCI_PS_SUSP)
					EOWRITE4(sc, EHCI_PORTSC(i),
					   cmd & ~EHCI_PS_FPR);
			}
		}

		/* Turn on controller */
		EOWRITE4(sc, EHCI_USBCMD,
		    EHCI_CMD_ITC_2 | /* 2 microframes interrupt delay */
		    (EOREAD4(sc, EHCI_USBCMD) & EHCI_CMD_FLS_M) |
		    EHCI_CMD_ASE |
		    EHCI_CMD_PSE |
		    EHCI_CMD_RS);

		/* Take over port ownership */
		EOWRITE4(sc, EHCI_CONFIGFLAG, EHCI_CONF_CF);
		for (i = 0; i < 100; i++) {
			usb_delay_ms(&sc->sc_bus, 1);
			hcr = EOREAD4(sc, EHCI_USBSTS) & EHCI_STS_HCH;
			if (!hcr)
				break;
		}

		if (hcr) {
			printf("%s: run timeout\n", sc->sc_bus.bdev.dv_xname);
			/* XXX should we bail here? */
		}

		EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs);

		usb_delay_ms(&sc->sc_bus, USB_RESUME_WAIT);

		sc->sc_bus.use_polling--;
		rv = config_activate_children(self, act);
		break;
	case DVACT_POWERDOWN:
		rv = config_activate_children(self, act);
		ehci_reset(sc);
		break;
	default:
		rv = config_activate_children(self, act);
		break;
	}
	return (rv);
}

usbd_status
ehci_reset(struct ehci_softc *sc)
{
	u_int32_t hcr;
	int i;

	DPRINTF(("%s: stopping the HC\n", __func__));
	EOWRITE4(sc, EHCI_USBCMD, 0);	/* Halt controller */
	for (i = 0; i < 100; i++) {
		usb_delay_ms(&sc->sc_bus, 1);
		hcr = EOREAD4(sc, EHCI_USBSTS) & EHCI_STS_HCH;
		if (hcr)
			break;
	}

	if (!hcr)
		printf("%s: halt timeout\n", sc->sc_bus.bdev.dv_xname);

	EOWRITE4(sc, EHCI_USBCMD, EHCI_CMD_HCRESET);
	for (i = 0; i < 100; i++) {
		usb_delay_ms(&sc->sc_bus, 1);
		hcr = EOREAD4(sc, EHCI_USBCMD) & EHCI_CMD_HCRESET;
		if (!hcr)
			break;
	}

	if (hcr) {
		printf("%s: reset timeout\n", sc->sc_bus.bdev.dv_xname);
		return (USBD_IOERROR);
	}

	return (USBD_NORMAL_COMPLETION);
}

struct usbd_xfer *
ehci_allocx(struct usbd_bus *bus)
{
	struct ehci_xfer *ex;

	ex = pool_get(ehcixfer, PR_NOWAIT | PR_ZERO);
#ifdef DIAGNOSTIC
	if (ex != NULL)
		ex->isdone = 1;
#endif
	return ((struct usbd_xfer *)ex);
}

void
ehci_freex(struct usbd_bus *bus, struct usbd_xfer *xfer)
{
	struct ehci_xfer *ex = (struct ehci_xfer*)xfer;

#ifdef DIAGNOSTIC
	if (!ex->isdone) {
		printf("%s: !isdone\n", __func__);
		return;
	}
#endif
	pool_put(ehcixfer, ex);
}

void
ehci_device_clear_toggle(struct usbd_pipe *pipe)
{
	struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;

	DPRINTF(("ehci_device_clear_toggle: epipe=%p status=0x%x\n",
	    epipe, epipe->sqh->qh.qh_qtd.qtd_status));
#if defined(EHCI_DEBUG) && defined(USB_DEBUG)
	if (ehcidebug)
		usbd_dump_pipe(pipe);
#endif
#ifdef DIAGNOSTIC
	if ((epipe->sqh->qh.qh_qtd.qtd_status & htole32(EHCI_QTD_ACTIVE)) != 0)
		panic("ehci_device_clear_toggle: queue active");
#endif
	epipe->sqh->qh.qh_qtd.qtd_status &= htole32(~EHCI_QTD_TOGGLE_MASK);
}

#ifdef EHCI_DEBUG
void
ehci_dump_regs(struct ehci_softc *sc)
{
	int i;

	printf("cmd=0x%08x, sts=0x%08x, ien=0x%08x\n",
	    EOREAD4(sc, EHCI_USBCMD),
	    EOREAD4(sc, EHCI_USBSTS),
	    EOREAD4(sc, EHCI_USBINTR));
	printf("frindex=0x%08x ctrdsegm=0x%08x periodic=0x%08x async=0x%08x\n",
	    EOREAD4(sc, EHCI_FRINDEX),
	    EOREAD4(sc, EHCI_CTRLDSSEGMENT),
	    EOREAD4(sc, EHCI_PERIODICLISTBASE),
	    EOREAD4(sc, EHCI_ASYNCLISTADDR));
	for (i = 1; i <= sc->sc_noport; i++)
		printf("port %d status=0x%08x\n", i,
		    EOREAD4(sc, EHCI_PORTSC(i)));
}

/*
 * Unused function - this is meant to be called from a kernel
 * debugger.
 */
void
ehci_dump(void)
{
	ehci_dump_regs(theehci);
}

void
ehci_dump_link(ehci_link_t link, int type)
{
	link = letoh32(link);
	printf("0x%08x", link);
	if (link & EHCI_LINK_TERMINATE)
		printf("<T>");
	else {
		printf("<");
		if (type) {
			switch (EHCI_LINK_TYPE(link)) {
			case EHCI_LINK_ITD:
				printf("ITD");
				break;
			case EHCI_LINK_QH:
				printf("QH");
				break;
			case EHCI_LINK_SITD:
				printf("SITD");
				break;
			case EHCI_LINK_FSTN:
				printf("FSTN");
				break;
			}
		}
		printf(">");
	}
}

void
ehci_dump_sqtds(struct ehci_soft_qtd *sqtd)
{
	int i;
	u_int32_t stop;

	stop = 0;
	for (i = 0; sqtd && i < 20 && !stop; sqtd = sqtd->nextqtd, i++) {
		ehci_dump_sqtd(sqtd);
		usb_syncmem(&sqtd->dma,
		    sqtd->offs + offsetof(struct ehci_qtd, qtd_next),
		    sizeof(sqtd->qtd),
		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
		stop = sqtd->qtd.qtd_next & htole32(EHCI_LINK_TERMINATE);
		usb_syncmem(&sqtd->dma,
		    sqtd->offs + offsetof(struct ehci_qtd, qtd_next),
		    sizeof(sqtd->qtd), BUS_DMASYNC_PREREAD);
	}
	if (!stop)
		printf("dump aborted, too many TDs\n");
}

void
ehci_dump_sqtd(struct ehci_soft_qtd *sqtd)
{
	usb_syncmem(&sqtd->dma, sqtd->offs, 
	    sizeof(sqtd->qtd), BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
	printf("QTD(%p) at 0x%08x:\n", sqtd, sqtd->physaddr);
	ehci_dump_qtd(&sqtd->qtd);
	usb_syncmem(&sqtd->dma, sqtd->offs, 
	    sizeof(sqtd->qtd), BUS_DMASYNC_PREREAD);
}

void
ehci_dump_qtd(struct ehci_qtd *qtd)
{
	u_int32_t s;
	char sbuf[128];

	printf("  next="); ehci_dump_link(qtd->qtd_next, 0);
	printf(" altnext="); ehci_dump_link(qtd->qtd_altnext, 0);
	printf("\n");
	s = letoh32(qtd->qtd_status);
	bitmask_snprintf(EHCI_QTD_GET_STATUS(s), "\20\10ACTIVE\7HALTED"
	    "\6BUFERR\5BABBLE\4XACTERR\3MISSED\2SPLIT\1PING",
	    sbuf, sizeof(sbuf));
	printf("  status=0x%08x: toggle=%d bytes=0x%x ioc=%d c_page=0x%x\n",
	    s, EHCI_QTD_GET_TOGGLE(s), EHCI_QTD_GET_BYTES(s),
	    EHCI_QTD_GET_IOC(s), EHCI_QTD_GET_C_PAGE(s));
	printf("    cerr=%d pid=%d stat=0x%s\n", EHCI_QTD_GET_CERR(s),
	    EHCI_QTD_GET_PID(s), sbuf);
	for (s = 0; s < 5; s++)
		printf("  buffer[%d]=0x%08x\n", s, letoh32(qtd->qtd_buffer[s]));
}

void
ehci_dump_sqh(struct ehci_soft_qh *sqh)
{
	struct ehci_qh *qh = &sqh->qh;
	u_int32_t endp, endphub;

	usb_syncmem(&sqh->dma, sqh->offs,
	    sizeof(sqh->qh), BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
	printf("QH(%p) at 0x%08x:\n", sqh, sqh->physaddr);
	printf("  link="); ehci_dump_link(qh->qh_link, 1); printf("\n");
	endp = letoh32(qh->qh_endp);
	printf("  endp=0x%08x\n", endp);
	printf("    addr=0x%02x inact=%d endpt=%d eps=%d dtc=%d hrecl=%d\n",
	    EHCI_QH_GET_ADDR(endp), EHCI_QH_GET_INACT(endp),
	    EHCI_QH_GET_ENDPT(endp),  EHCI_QH_GET_EPS(endp),
	    EHCI_QH_GET_DTC(endp), EHCI_QH_GET_HRECL(endp));
	printf("    mpl=0x%x ctl=%d nrl=%d\n",
	    EHCI_QH_GET_MPL(endp), EHCI_QH_GET_CTL(endp),
	    EHCI_QH_GET_NRL(endp));
	endphub = letoh32(qh->qh_endphub);
	printf("  endphub=0x%08x\n", endphub);
	printf("    smask=0x%02x cmask=0x%02x huba=0x%02x port=%d mult=%d\n",
	    EHCI_QH_GET_SMASK(endphub), EHCI_QH_GET_CMASK(endphub),
	    EHCI_QH_GET_HUBA(endphub), EHCI_QH_GET_PORT(endphub),
	    EHCI_QH_GET_MULT(endphub));
	printf("  curqtd="); ehci_dump_link(qh->qh_curqtd, 0); printf("\n");
	printf("Overlay qTD:\n");
	ehci_dump_qtd(&qh->qh_qtd);
	usb_syncmem(&sqh->dma, sqh->offs,
	    sizeof(sqh->qh), BUS_DMASYNC_PREREAD);
}

#if notyet
void
ehci_dump_itd(struct ehci_soft_itd *itd)
{
	ehci_isoc_trans_t t;
	ehci_isoc_bufr_ptr_t b, b2, b3;
	int i;

	printf("ITD: next phys=%X\n", itd->itd.itd_next);

	for (i = 0; i < 8;i++) {
		t = letoh32(itd->itd.itd_ctl[i]);
		printf("ITDctl %d: stat=%X len=%X ioc=%X pg=%X offs=%X\n", i,
		    EHCI_ITD_GET_STATUS(t), EHCI_ITD_GET_LEN(t),
		    EHCI_ITD_GET_IOC(t), EHCI_ITD_GET_PG(t),
		    EHCI_ITD_GET_OFFS(t));
	}
	printf("ITDbufr: ");
	for (i = 0; i < 7; i++)
		printf("%X,", EHCI_ITD_GET_BPTR(letoh32(itd->itd.itd_bufr[i])));

	b = letoh32(itd->itd.itd_bufr[0]);
	b2 = letoh32(itd->itd.itd_bufr[1]);
	b3 = letoh32(itd->itd.itd_bufr[2]);
	printf("\nep=%X daddr=%X dir=%d maxpkt=%X multi=%X\n",
	    EHCI_ITD_GET_EP(b), EHCI_ITD_GET_DADDR(b), EHCI_ITD_GET_DIR(b2),
	    EHCI_ITD_GET_MAXPKT(b2), EHCI_ITD_GET_MULTI(b3));
}

void
ehci_dump_sitd(struct ehci_soft_itd *itd)
{
	printf("SITD %p next=%p prev=%p xfernext=%p physaddr=%X slot=%d\n",
	    itd, itd->u.frame_list.next, itd->u.frame_list.prev,
	    itd->xfer_next, itd->physaddr, itd->slot);
}
#endif

#ifdef DIAGNOSTIC
void
ehci_dump_exfer(struct ehci_xfer *ex)
{
	printf("ehci_dump_exfer: ex=%p sqtdstart=%p end=%p itdstart=%p end=%p "
	    "isdone=%d\n", ex, ex->sqtdstart, ex->sqtdend, ex->itdstart,
	    ex->itdend, ex->isdone);
}
#endif

#endif /* EHCI_DEBUG */

usbd_status
ehci_open(struct usbd_pipe *pipe)
{
	struct usbd_device *dev = pipe->device;
	struct ehci_softc *sc = (struct ehci_softc *)dev->bus;
	usb_endpoint_descriptor_t *ed = pipe->endpoint->edesc;
	u_int8_t addr = dev->address;
	u_int8_t xfertype = ed->bmAttributes & UE_XFERTYPE;
	struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;
	struct ehci_soft_qh *sqh;
	usbd_status err;
	int s;
	int ival, speed, naks;
	int hshubaddr, hshubport;

	DPRINTFN(1, ("ehci_open: pipe=%p, addr=%d, endpt=%d\n",
	    pipe, addr, ed->bEndpointAddress));

	if (sc->sc_bus.dying)
		return (USBD_IOERROR);

	if (dev->myhsport) {
		hshubaddr = dev->myhsport->parent->address;
		hshubport = dev->myhsport->portno;
	} else {
		hshubaddr = 0;
		hshubport = 0;
	}

	/* Root Hub */
	if (pipe->device->depth == 0) {
		switch (ed->bEndpointAddress) {
		case USB_CONTROL_ENDPOINT:
			pipe->methods = &ehci_root_ctrl_methods;
			break;
		case UE_DIR_IN | EHCI_INTR_ENDPT:
			pipe->methods = &ehci_root_intr_methods;
			break;
		default:
			return (USBD_INVAL);
		}
		return (USBD_NORMAL_COMPLETION);
	}

	/* XXX All this stuff is only valid for async. */
	switch (dev->speed) {
	case USB_SPEED_LOW:
		speed = EHCI_QH_SPEED_LOW;
		break;
	case USB_SPEED_FULL:
		speed = EHCI_QH_SPEED_FULL;
		break;
	case USB_SPEED_HIGH:
		speed = EHCI_QH_SPEED_HIGH;
		break;
	default:
		panic("ehci_open: bad device speed %d", dev->speed);
	}
	if (speed != EHCI_QH_SPEED_HIGH && xfertype == UE_ISOCHRONOUS) {
		printf("%s: Error opening low/full speed isoc endpoint.\n"
		    "A low/full speed device is attached to a USB2 hub, and "
		    "transaction translations are not yet supported.\n"
		    "Reattach the device to the root hub instead.\n",
		    sc->sc_bus.bdev.dv_xname);
		DPRINTFN(1,("ehci_open: hshubaddr=%d hshubport=%d\n",
		    hshubaddr, hshubport));
		return (USBD_INVAL);
	}

	naks = 8;		/* XXX */

	/* Allocate sqh for everything, save isoc xfers */
	if (xfertype != UE_ISOCHRONOUS) {
		sqh = ehci_alloc_sqh(sc);
		if (sqh == NULL)
			return (USBD_NOMEM);
		/* qh_link filled when the QH is added */
		sqh->qh.qh_endp = htole32(
		    EHCI_QH_SET_ADDR(addr) |
		    EHCI_QH_SET_ENDPT(UE_GET_ADDR(ed->bEndpointAddress)) |
		    EHCI_QH_SET_EPS(speed) |
		    (xfertype == UE_CONTROL ? EHCI_QH_DTC : 0) |
		    EHCI_QH_SET_MPL(UGETW(ed->wMaxPacketSize)) |
		    (speed != EHCI_QH_SPEED_HIGH && xfertype == UE_CONTROL ?
		    EHCI_QH_CTL : 0) |
		    EHCI_QH_SET_NRL(naks)
		    );
		sqh->qh.qh_endphub = htole32(
		    EHCI_QH_SET_MULT(1) |
		    EHCI_QH_SET_HUBA(hshubaddr) |
		    EHCI_QH_SET_PORT(hshubport) |
		    EHCI_QH_SET_CMASK(0x1c) | /* XXX */
		    EHCI_QH_SET_SMASK(xfertype == UE_INTERRUPT ? 0x01 : 0)
		    );
		sqh->qh.qh_curqtd = htole32(EHCI_LINK_TERMINATE);
		/* Fill the overlay qTD */
		sqh->qh.qh_qtd.qtd_next = htole32(EHCI_LINK_TERMINATE);
		sqh->qh.qh_qtd.qtd_altnext = htole32(EHCI_LINK_TERMINATE);
		sqh->qh.qh_qtd.qtd_status =
		    htole32(EHCI_QTD_SET_TOGGLE(pipe->endpoint->savedtoggle));

		usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
		epipe->sqh = sqh;
	} else {
		sqh = NULL;
	} /*xfertype == UE_ISOC*/

	switch (xfertype) {
	case UE_CONTROL:
		err = usb_allocmem(&sc->sc_bus, sizeof(usb_device_request_t),
		    0, &epipe->u.ctl.reqdma);
#ifdef EHCI_DEBUG
		if (err)
			printf("ehci_open: usb_allocmem()=%d\n", err);
#endif
		if (err)
			goto bad;
		pipe->methods = &ehci_device_ctrl_methods;
		s = splusb();
		ehci_add_qh(sqh, sc->sc_async_head);
		splx(s);
		break;
	case UE_BULK:
		pipe->methods = &ehci_device_bulk_methods;
		s = splusb();
		ehci_add_qh(sqh, sc->sc_async_head);
		splx(s);
		break;
	case UE_INTERRUPT:
		pipe->methods = &ehci_device_intr_methods;
		ival = pipe->interval;
		if (ival == USBD_DEFAULT_INTERVAL)
			ival = ed->bInterval;
		s = splusb();
		err = ehci_device_setintr(sc, sqh, ival);
		splx(s);
		return (err);
	case UE_ISOCHRONOUS:
		pipe->methods = &ehci_device_isoc_methods;
		if (ed->bInterval == 0 || ed->bInterval > 16) {
			printf("ehci: opening pipe with invalid bInterval\n");
			err = USBD_INVAL;
			goto bad;
		}
		if (UGETW(ed->wMaxPacketSize) == 0) {
			printf("ehci: zero length endpoint open request\n");
			err = USBD_INVAL;
			goto bad;
		}
		epipe->u.isoc.next_frame = 0;
		epipe->u.isoc.cur_xfers = 0;
		break;
	default:
		DPRINTF(("ehci: bad xfer type %d\n", xfertype));
		return (USBD_INVAL);
	}
	return (USBD_NORMAL_COMPLETION);

bad:
	if (sqh != NULL)
		ehci_free_sqh(sc, sqh);
	return (err);
}

/*
 * Add an ED to the schedule.  Called at splusb().
 * If in the async schedule, it will always have a next.
 * If in the intr schedule it may not.
 */
void
ehci_add_qh(struct ehci_soft_qh *sqh, struct ehci_soft_qh *head)
{
	SPLUSBCHECK;

	usb_syncmem(&head->dma, head->offs + offsetof(struct ehci_qh, qh_link),
	    sizeof(head->qh.qh_link), BUS_DMASYNC_POSTWRITE);
	sqh->next = head->next;
	sqh->prev = head;
	sqh->qh.qh_link = head->qh.qh_link;
	usb_syncmem(&sqh->dma, sqh->offs + offsetof(struct ehci_qh, qh_link),
	    sizeof(sqh->qh.qh_link), BUS_DMASYNC_PREWRITE);
	head->next = sqh;
	if (sqh->next)
		sqh->next->prev = sqh;
	head->qh.qh_link = htole32(sqh->physaddr | EHCI_LINK_QH);
	usb_syncmem(&head->dma, head->offs + offsetof(struct ehci_qh, qh_link),
	    sizeof(head->qh.qh_link), BUS_DMASYNC_PREWRITE);

#ifdef EHCI_DEBUG
	if (ehcidebug > 5) {
		printf("ehci_add_qh:\n");
		ehci_dump_sqh(sqh);
	}
#endif
}

/*
 * Remove an ED from the schedule.  Called at splusb().
 * Will always have a 'next' if it's in the async list as it's circular.
 */
void
ehci_rem_qh(struct ehci_softc *sc, struct ehci_soft_qh *sqh)
{
	SPLUSBCHECK;
	/* XXX */
	usb_syncmem(&sqh->dma, sqh->offs + offsetof(struct ehci_qh, qh_link),
	    sizeof(sqh->qh.qh_link), BUS_DMASYNC_POSTWRITE);
	sqh->prev->qh.qh_link = sqh->qh.qh_link;
	sqh->prev->next = sqh->next;
	if (sqh->next)
		sqh->next->prev = sqh->prev;
	usb_syncmem(&sqh->prev->dma,
	    sqh->prev->offs + offsetof(struct ehci_qh, qh_link),
	    sizeof(sqh->prev->qh.qh_link), BUS_DMASYNC_PREWRITE);

	ehci_sync_hc(sc);
}

void
ehci_set_qh_qtd(struct ehci_soft_qh *sqh, struct ehci_soft_qtd *sqtd)
{
	int i;
	u_int32_t status;

	/* Save toggle bit and ping status. */
	usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
	status = sqh->qh.qh_qtd.qtd_status &
	    htole32(EHCI_QTD_TOGGLE_MASK |
		EHCI_QTD_SET_STATUS(EHCI_QTD_PINGSTATE));
	/* Set HALTED to make hw leave it alone. */
	sqh->qh.qh_qtd.qtd_status =
	    htole32(EHCI_QTD_SET_STATUS(EHCI_QTD_HALTED));
	usb_syncmem(&sqh->dma,
	    sqh->offs + offsetof(struct ehci_qh, qh_qtd.qtd_status),
	    sizeof(sqh->qh.qh_qtd.qtd_status),
	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
	sqh->qh.qh_curqtd = 0;
	sqh->qh.qh_qtd.qtd_next = htole32(sqtd->physaddr);
	sqh->qh.qh_qtd.qtd_altnext = htole32(EHCI_LINK_TERMINATE);
	for (i = 0; i < EHCI_QTD_NBUFFERS; i++)
		sqh->qh.qh_qtd.qtd_buffer[i] = 0;
	sqh->sqtd = sqtd;
	usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
	/* Set !HALTED && !ACTIVE to start execution, preserve some fields */
	sqh->qh.qh_qtd.qtd_status = status;
	usb_syncmem(&sqh->dma,
	    sqh->offs + offsetof(struct ehci_qh, qh_qtd.qtd_status),
	    sizeof(sqh->qh.qh_qtd.qtd_status),
	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
}

/*
 * Ensure that the HC has released all references to the QH.  We do this
 * by asking for a Async Advance Doorbell interrupt and then we wait for
 * the interrupt.
 * To make this easier we first obtain exclusive use of the doorbell.
 */
void
ehci_sync_hc(struct ehci_softc *sc)
{
	int s, error;
	int tries = 0;

	if (sc->sc_bus.dying) {
		DPRINTFN(2,("ehci_sync_hc: dying\n"));
		return;
	}
	DPRINTFN(2,("ehci_sync_hc: enter\n"));
	/* get doorbell */
	rw_enter_write(&sc->sc_doorbell_lock);
	s = splhardusb();
	do { 
		/* ask for doorbell */
		EOWRITE4(sc, EHCI_USBCMD, EOREAD4(sc, EHCI_USBCMD) |
		    EHCI_CMD_IAAD);
		DPRINTFN(1,("ehci_sync_hc: cmd=0x%08x sts=0x%08x\n",
		    EOREAD4(sc, EHCI_USBCMD), EOREAD4(sc, EHCI_USBSTS)));
		/* bell wait */
		error = tsleep(&sc->sc_async_head, PZERO, "ehcidi", hz / 2);
		DPRINTFN(1,("ehci_sync_hc: cmd=0x%08x sts=0x%08x\n",
		    EOREAD4(sc, EHCI_USBCMD), EOREAD4(sc, EHCI_USBSTS)));
	} while (error && ++tries < 10);
	splx(s);
	/* release doorbell */
	rw_exit_write(&sc->sc_doorbell_lock);
#ifdef DIAGNOSTIC
	if (error)
		printf("ehci_sync_hc: tsleep() = %d\n", error);
#endif
	DPRINTFN(2,("ehci_sync_hc: exit\n"));
}

/*Call at splusb*/
void
ehci_rem_free_itd_chain(struct ehci_softc *sc, struct ehci_xfer *ex)
{
	struct ehci_soft_itd *itd, *prev;

	prev = NULL;

	if (ex->itdstart == NULL || ex->itdend == NULL)
		panic("ehci isoc xfer being freed, but with no itd chain");

	for (itd = ex->itdstart; itd != NULL; itd = itd->xfer_next) {
		prev = itd->u.frame_list.prev;
		/* Unlink itd from hardware chain, or frame array */
		if (prev == NULL) { /* We're at the table head */
			sc->sc_softitds[itd->slot] = itd->u.frame_list.next;
			sc->sc_flist[itd->slot] = itd->itd.itd_next;
			usb_syncmem(&sc->sc_fldma,
			    sizeof(ehci_link_t) * itd->slot,
			    sizeof(ehci_link_t),
			    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);

			if (itd->u.frame_list.next != NULL)
				itd->u.frame_list.next->u.frame_list.prev =
				    NULL;
		} else {
			/* XXX this part is untested... */
			prev->itd.itd_next = itd->itd.itd_next;
			usb_syncmem(&itd->dma,
			    itd->offs + offsetof(struct ehci_itd, itd_next),
			    sizeof(itd->itd.itd_next), BUS_DMASYNC_PREWRITE);

			prev->u.frame_list.next = itd->u.frame_list.next;
			if (itd->u.frame_list.next != NULL)
				itd->u.frame_list.next->u.frame_list.prev =
				    prev;
		}
	}

	prev = NULL;
	for (itd = ex->itdstart; itd != NULL; itd = itd->xfer_next) {
		if (prev != NULL)
			ehci_free_itd(sc, prev);
		prev = itd;
	}
	if (prev)
		ehci_free_itd(sc, prev);
	ex->itdstart = NULL;
	ex->itdend = NULL;
}

/***********/

/*
 * Data structures and routines to emulate the root hub.
 */
usb_device_descriptor_t ehci_devd = {
	USB_DEVICE_DESCRIPTOR_SIZE,
	UDESC_DEVICE,		/* type */
	{0x00, 0x02},		/* USB version */
	UDCLASS_HUB,		/* class */
	UDSUBCLASS_HUB,		/* subclass */
	UDPROTO_HSHUBSTT,	/* protocol */
	64,			/* max packet */
	{0},{0},{0x00,0x01},	/* device id */
	1,2,0,			/* string indicies */
	1			/* # of configurations */
};

usb_device_qualifier_t ehci_odevd = {
	USB_DEVICE_DESCRIPTOR_SIZE,
	UDESC_DEVICE_QUALIFIER,	/* type */
	{0x00, 0x02},		/* USB version */
	UDCLASS_HUB,		/* class */
	UDSUBCLASS_HUB,		/* subclass */
	UDPROTO_FSHUB,		/* protocol */
	64,			/* max packet */
	1,			/* # of configurations */
	0
};

usb_config_descriptor_t ehci_confd = {
	USB_CONFIG_DESCRIPTOR_SIZE,
	UDESC_CONFIG,
	{USB_CONFIG_DESCRIPTOR_SIZE +
	 USB_INTERFACE_DESCRIPTOR_SIZE +
	 USB_ENDPOINT_DESCRIPTOR_SIZE},
	1,
	1,
	0,
	UC_SELF_POWERED,
	0			/* max power */
};

usb_interface_descriptor_t ehci_ifcd = {
	USB_INTERFACE_DESCRIPTOR_SIZE,
	UDESC_INTERFACE,
	0,
	0,
	1,
	UICLASS_HUB,
	UISUBCLASS_HUB,
	UIPROTO_HSHUBSTT,
	0
};

usb_endpoint_descriptor_t ehci_endpd = {
	USB_ENDPOINT_DESCRIPTOR_SIZE,
	UDESC_ENDPOINT,
	UE_DIR_IN | EHCI_INTR_ENDPT,
	UE_INTERRUPT,
	{8, 0},			/* max packet */
	12
};

usb_hub_descriptor_t ehci_hubd = {
	USB_HUB_DESCRIPTOR_SIZE,
	UDESC_HUB,
	0,
	{0,0},
	0,
	0,
	{0},
};

/*
 * Simulate a hardware hub by handling all the necessary requests.
 */
usbd_status
ehci_root_ctrl_transfer(struct usbd_xfer *xfer)
{
	usbd_status err;

	/* Insert last in queue. */
	err = usb_insert_transfer(xfer);
	if (err)
		return (err);

	/* Pipe isn't running, start first */
	return (ehci_root_ctrl_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
}

usbd_status
ehci_root_ctrl_start(struct usbd_xfer *xfer)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	usb_device_request_t *req;
	void *buf = NULL;
	int port, i;
	int s, len, value, index, l, totlen = 0;
	usb_port_status_t ps;
	usb_hub_descriptor_t hubd;
	usbd_status err;
	u_int32_t v;

	if (sc->sc_bus.dying)
		return (USBD_IOERROR);

#ifdef DIAGNOSTIC
	if (!(xfer->rqflags & URQ_REQUEST))
		/* XXX panic */
		return (USBD_INVAL);
#endif
	req = &xfer->request;

	DPRINTFN(4,("ehci_root_ctrl_start: type=0x%02x request=%02x\n",
		    req->bmRequestType, req->bRequest));

	len = UGETW(req->wLength);
	value = UGETW(req->wValue);
	index = UGETW(req->wIndex);

	if (len != 0)
		buf = KERNADDR(&xfer->dmabuf, 0);

#define C(x,y) ((x) | ((y) << 8))
	switch(C(req->bRequest, req->bmRequestType)) {
	case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
	case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
	case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
		/*
		 * DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
		 * for the integrated root hub.
		 */
		break;
	case C(UR_GET_CONFIG, UT_READ_DEVICE):
		if (len > 0) {
			*(u_int8_t *)buf = sc->sc_conf;
			totlen = 1;
		}
		break;
	case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
		DPRINTFN(8,("ehci_root_ctrl_start: wValue=0x%04x\n", value));
		switch(value >> 8) {
		case UDESC_DEVICE:
			if ((value & 0xff) != 0) {
				err = USBD_IOERROR;
				goto ret;
			}
			totlen = l = min(len, USB_DEVICE_DESCRIPTOR_SIZE);
			USETW(ehci_devd.idVendor, sc->sc_id_vendor);
			memcpy(buf, &ehci_devd, l);
			break;
		/*
		 * We can't really operate at another speed, but the spec says
		 * we need this descriptor.
		 */
		case UDESC_DEVICE_QUALIFIER:
			if ((value & 0xff) != 0) {
				err = USBD_IOERROR;
				goto ret;
			}
			totlen = l = min(len, USB_DEVICE_DESCRIPTOR_SIZE);
			memcpy(buf, &ehci_odevd, l);
			break;
		/*
		 * We can't really operate at another speed, but the spec says
		 * we need this descriptor.
		 */
		case UDESC_OTHER_SPEED_CONFIGURATION:
		case UDESC_CONFIG:
			if ((value & 0xff) != 0) {
				err = USBD_IOERROR;
				goto ret;
			}
			totlen = l = min(len, USB_CONFIG_DESCRIPTOR_SIZE);
			memcpy(buf, &ehci_confd, l);
			((usb_config_descriptor_t *)buf)->bDescriptorType =
			    value >> 8;
			buf = (char *)buf + l;
			len -= l;
			l = min(len, USB_INTERFACE_DESCRIPTOR_SIZE);
			totlen += l;
			memcpy(buf, &ehci_ifcd, l);
			buf = (char *)buf + l;
			len -= l;
			l = min(len, USB_ENDPOINT_DESCRIPTOR_SIZE);
			totlen += l;
			memcpy(buf, &ehci_endpd, l);
			break;
		case UDESC_STRING:
			if (len == 0)
				break;
			*(u_int8_t *)buf = 0;
			totlen = 1;
			switch (value & 0xff) {
			case 0: /* Language table */
				totlen = usbd_str(buf, len, "\001");
				break;
			case 1: /* Vendor */
				totlen = usbd_str(buf, len, sc->sc_vendor);
				break;
			case 2: /* Product */
				totlen = usbd_str(buf, len, "EHCI root hub");
				break;
			}
			break;
		default:
			err = USBD_IOERROR;
			goto ret;
		}
		break;
	case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
		if (len > 0) {
			*(u_int8_t *)buf = 0;
			totlen = 1;
		}
		break;
	case C(UR_GET_STATUS, UT_READ_DEVICE):
		if (len > 1) {
			USETW(((usb_status_t *)buf)->wStatus,UDS_SELF_POWERED);
			totlen = 2;
		}
		break;
	case C(UR_GET_STATUS, UT_READ_INTERFACE):
	case C(UR_GET_STATUS, UT_READ_ENDPOINT):
		if (len > 1) {
			USETW(((usb_status_t *)buf)->wStatus, 0);
			totlen = 2;
		}
		break;
	case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
		if (value >= USB_MAX_DEVICES) {
			err = USBD_IOERROR;
			goto ret;
		}
		break;
	case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
		if (value != 0 && value != 1) {
			err = USBD_IOERROR;
			goto ret;
		}
		sc->sc_conf = value;
		break;
	case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
		break;
	case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
	case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
	case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
		err = USBD_IOERROR;
		goto ret;
	case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
		break;
	case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
		break;
	/* Hub requests */
	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
		break;
	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
		DPRINTFN(8, ("ehci_root_ctrl_start: UR_CLEAR_PORT_FEATURE "
		    "port=%d feature=%d\n", index, value));
		if (index < 1 || index > sc->sc_noport) {
			err = USBD_IOERROR;
			goto ret;
		}
		port = EHCI_PORTSC(index);
		v = EOREAD4(sc, port) &~ EHCI_PS_CLEAR;
		switch(value) {
		case UHF_PORT_ENABLE:
			EOWRITE4(sc, port, v &~ EHCI_PS_PE);
			break;
		case UHF_PORT_SUSPEND:
			EOWRITE4(sc, port, v &~ EHCI_PS_SUSP);
			break;
		case UHF_PORT_POWER:
			EOWRITE4(sc, port, v &~ EHCI_PS_PP);
			break;
		case UHF_PORT_TEST:
			DPRINTFN(2,("ehci_root_ctrl_start: "
			    "clear port test %d\n", index));
			break;
		case UHF_PORT_INDICATOR:
			DPRINTFN(2,("ehci_root_ctrl_start: "
			    "clear port index %d\n", index));
			EOWRITE4(sc, port, v &~ EHCI_PS_PIC);
			break;
		case UHF_C_PORT_CONNECTION:
			EOWRITE4(sc, port, v | EHCI_PS_CSC);
			break;
		case UHF_C_PORT_ENABLE:
			EOWRITE4(sc, port, v | EHCI_PS_PEC);
			break;
		case UHF_C_PORT_SUSPEND:
			/* how? */
			break;
		case UHF_C_PORT_OVER_CURRENT:
			EOWRITE4(sc, port, v | EHCI_PS_OCC);
			break;
		case UHF_C_PORT_RESET:
			sc->sc_isreset = 0;
			break;
		default:
			err = USBD_IOERROR;
			goto ret;
		}
		break;
	case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
		if ((value & 0xff) != 0) {
			err = USBD_IOERROR;
			goto ret;
		}
		hubd = ehci_hubd;
		hubd.bNbrPorts = sc->sc_noport;
		v = EREAD4(sc, EHCI_HCSPARAMS);
		USETW(hubd.wHubCharacteristics,
		    (EHCI_HCS_PPC(v) ? UHD_PWR_INDIVIDUAL : UHD_PWR_NO_SWITCH) |
		    (EHCI_HCS_P_INDICATOR(v) ? UHD_PORT_IND : 0));
		hubd.bPwrOn2PwrGood = 200; /* XXX can't find out? */
		for (i = 0, l = sc->sc_noport; l > 0; i++, l -= 8, v >>= 8)
			hubd.DeviceRemovable[i++] = 0; /* XXX can't find out? */
		hubd.bDescLength = USB_HUB_DESCRIPTOR_SIZE + i;
		l = min(len, hubd.bDescLength);
		totlen = l;
		memcpy(buf, &hubd, l);
		break;
	case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
		if (len != 4) {
			err = USBD_IOERROR;
			goto ret;
		}
		memset(buf, 0, len); /* ? XXX */
		totlen = len;
		break;
	case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
		DPRINTFN(8,("ehci_root_ctrl_start: get port status i=%d\n",
		    index));
		if (index < 1 || index > sc->sc_noport) {
			err = USBD_IOERROR;
			goto ret;
		}
		if (len != 4) {
			err = USBD_IOERROR;
			goto ret;
		}
		v = EOREAD4(sc, EHCI_PORTSC(index));
		DPRINTFN(8,("ehci_root_ctrl_start: port status=0x%04x\n", v));
		i = UPS_HIGH_SPEED;
		if (v & EHCI_PS_CS)	i |= UPS_CURRENT_CONNECT_STATUS;
		if (v & EHCI_PS_PE)	i |= UPS_PORT_ENABLED;
		if (v & EHCI_PS_SUSP)	i |= UPS_SUSPEND;
		if (v & EHCI_PS_OCA)	i |= UPS_OVERCURRENT_INDICATOR;
		if (v & EHCI_PS_PR)	i |= UPS_RESET;
		if (v & EHCI_PS_PP)	i |= UPS_PORT_POWER;
		USETW(ps.wPortStatus, i);
		i = 0;
		if (v & EHCI_PS_CSC)	i |= UPS_C_CONNECT_STATUS;
		if (v & EHCI_PS_PEC)	i |= UPS_C_PORT_ENABLED;
		if (v & EHCI_PS_OCC)	i |= UPS_C_OVERCURRENT_INDICATOR;
		if (sc->sc_isreset)	i |= UPS_C_PORT_RESET;
		USETW(ps.wPortChange, i);
		l = min(len, sizeof(ps));
		memcpy(buf, &ps, l);
		totlen = l;
		break;
	case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
		err = USBD_IOERROR;
		goto ret;
	case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
		break;
	case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
		if (index < 1 || index > sc->sc_noport) {
			err = USBD_IOERROR;
			goto ret;
		}
		port = EHCI_PORTSC(index);
		v = EOREAD4(sc, port) &~ EHCI_PS_CLEAR;
		switch(value) {
		case UHF_PORT_ENABLE:
			EOWRITE4(sc, port, v | EHCI_PS_PE);
			break;
		case UHF_PORT_SUSPEND:
			EOWRITE4(sc, port, v | EHCI_PS_SUSP);
			break;
		case UHF_PORT_DISOWN_TO_1_1:
			/* enter to Port Reset State */
			v &= ~EHCI_PS_PE;
			EOWRITE4(sc, port, v | EHCI_PS_PR);
			ehci_disown(sc, index, 0);
			break;
		case UHF_PORT_RESET:
			DPRINTFN(5,("ehci_root_ctrl_start: reset port %d\n",
			    index));
			if (EHCI_PS_IS_LOWSPEED(v)) {
				/* Low speed device, give up ownership. */
				ehci_disown(sc, index, 1);
				break;
			}
			/* Start reset sequence. */
			v &= ~ (EHCI_PS_PE | EHCI_PS_PR);
			EOWRITE4(sc, port, v | EHCI_PS_PR);
			/* Wait for reset to complete. */
			usb_delay_ms(&sc->sc_bus, USB_PORT_ROOT_RESET_DELAY);
			if (sc->sc_bus.dying) {
				err = USBD_IOERROR;
				goto ret;
			}
			/* Terminate reset sequence. */
			v = EOREAD4(sc, port);
			EOWRITE4(sc, port, v & ~EHCI_PS_PR);
			/* Wait for HC to complete reset. */
			usb_delay_ms(&sc->sc_bus, EHCI_PORT_RESET_COMPLETE);
			if (sc->sc_bus.dying) {
				err = USBD_IOERROR;
				goto ret;
			}
			v = EOREAD4(sc, port);
			DPRINTF(("ehci after reset, status=0x%08x\n", v));
			if (v & EHCI_PS_PR) {
				printf("%s: port reset timeout\n",
				    sc->sc_bus.bdev.dv_xname);
				err = USBD_IOERROR;
				goto ret;
			}
			if (!(v & EHCI_PS_PE)) {
				/* Not a high speed device, give up ownership.*/
				ehci_disown(sc, index, 0);
				break;
			}
			sc->sc_isreset = 1;
			DPRINTF(("ehci port %d reset, status = 0x%08x\n",
			    index, v));
			break;
		case UHF_PORT_POWER:
			DPRINTFN(2,("ehci_root_ctrl_start: "
			    "set port power %d\n", index));
			EOWRITE4(sc, port, v | EHCI_PS_PP);
			break;
		case UHF_PORT_TEST:
			DPRINTFN(2,("ehci_root_ctrl_start: "
			    "set port test %d\n", index));
			break;
		case UHF_PORT_INDICATOR:
			DPRINTFN(2,("ehci_root_ctrl_start: "
			    "set port ind %d\n", index));
			EOWRITE4(sc, port, v | EHCI_PS_PIC);
			break;
		default:
			err = USBD_IOERROR;
			goto ret;
		}
		break;
	case C(UR_CLEAR_TT_BUFFER, UT_WRITE_CLASS_OTHER):
	case C(UR_RESET_TT, UT_WRITE_CLASS_OTHER):
	case C(UR_GET_TT_STATE, UT_READ_CLASS_OTHER):
	case C(UR_STOP_TT, UT_WRITE_CLASS_OTHER):
		break;
	default:
		err = USBD_IOERROR;
		goto ret;
	}
	xfer->actlen = totlen;
	err = USBD_NORMAL_COMPLETION;
 ret:
	xfer->status = err;
	s = splusb();
	usb_transfer_complete(xfer);
	splx(s);
	return (USBD_IN_PROGRESS);
}

void
ehci_disown(struct ehci_softc *sc, int index, int lowspeed)
{
	int port;
	u_int32_t v;

	DPRINTF(("ehci_disown: index=%d lowspeed=%d\n", index, lowspeed));

	port = EHCI_PORTSC(index);
	v = EOREAD4(sc, port) &~ EHCI_PS_CLEAR;
	EOWRITE4(sc, port, v | EHCI_PS_PO);
}

/* Abort a root control request. */
void
ehci_root_ctrl_abort(struct usbd_xfer *xfer)
{
	/* Nothing to do, all transfers are synchronous. */
}

/* Close the root pipe. */
void
ehci_root_ctrl_close(struct usbd_pipe *pipe)
{
	DPRINTF(("ehci_root_ctrl_close\n"));
	/* Nothing to do. */
}

void
ehci_root_intr_done(struct usbd_xfer *xfer)
{
}

usbd_status
ehci_root_intr_transfer(struct usbd_xfer *xfer)
{
	usbd_status err;

	/* Insert last in queue. */
	err = usb_insert_transfer(xfer);
	if (err)
		return (err);

	/* Pipe isn't running, start first */
	return (ehci_root_intr_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
}

usbd_status
ehci_root_intr_start(struct usbd_xfer *xfer)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;

	if (sc->sc_bus.dying)
		return (USBD_IOERROR);

	sc->sc_intrxfer = xfer;

	return (USBD_IN_PROGRESS);
}

void
ehci_root_intr_abort(struct usbd_xfer *xfer)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	int s;

	sc->sc_intrxfer = NULL;

	xfer->status = USBD_CANCELLED;
	s = splusb();
	usb_transfer_complete(xfer);
	splx(s);
}

void
ehci_root_intr_close(struct usbd_pipe *pipe)
{
}

void
ehci_root_ctrl_done(struct usbd_xfer *xfer)
{
}

struct ehci_soft_qh *
ehci_alloc_sqh(struct ehci_softc *sc)
{
	struct ehci_soft_qh *sqh = NULL;
	usbd_status err;
	int i, offs;
	struct usb_dma dma;
	int s;

	s = splusb();
	if (sc->sc_freeqhs == NULL) {
		DPRINTFN(2, ("ehci_alloc_sqh: allocating chunk\n"));
		err = usb_allocmem(&sc->sc_bus, EHCI_SQH_SIZE * EHCI_SQH_CHUNK,
		    EHCI_PAGE_SIZE, &dma);
		if (err)
			goto out;
		for (i = 0; i < EHCI_SQH_CHUNK; i++) {
			offs = i * EHCI_SQH_SIZE;
			sqh = KERNADDR(&dma, offs);
			sqh->physaddr = DMAADDR(&dma, offs);
			sqh->dma = dma;
			sqh->offs = offs;
			sqh->next = sc->sc_freeqhs;
			sc->sc_freeqhs = sqh;
		}
	}
	sqh = sc->sc_freeqhs;
	sc->sc_freeqhs = sqh->next;
	memset(&sqh->qh, 0, sizeof(struct ehci_qh));
	sqh->next = NULL;
	sqh->prev = NULL;

out:
	splx(s);
	return (sqh);
}

void
ehci_free_sqh(struct ehci_softc *sc, struct ehci_soft_qh *sqh)
{
	int s;

	s = splusb();
	sqh->next = sc->sc_freeqhs;
	sc->sc_freeqhs = sqh;
	splx(s);
}

struct ehci_soft_qtd *
ehci_alloc_sqtd(struct ehci_softc *sc)
{
	struct ehci_soft_qtd *sqtd = NULL;
	usbd_status err;
	int i, offs;
	struct usb_dma dma;
	int s;

	s = splusb();
	if (sc->sc_freeqtds == NULL) {
		DPRINTFN(2, ("ehci_alloc_sqtd: allocating chunk\n"));
		err = usb_allocmem(&sc->sc_bus, EHCI_SQTD_SIZE*EHCI_SQTD_CHUNK,
		    EHCI_PAGE_SIZE, &dma);
		if (err)
			goto out;
		for(i = 0; i < EHCI_SQTD_CHUNK; i++) {
			offs = i * EHCI_SQTD_SIZE;
			sqtd = KERNADDR(&dma, offs);
			sqtd->physaddr = DMAADDR(&dma, offs);
			sqtd->dma = dma;
			sqtd->offs = offs;
			sqtd->nextqtd = sc->sc_freeqtds;
			sc->sc_freeqtds = sqtd;
		}
	}

	sqtd = sc->sc_freeqtds;
	sc->sc_freeqtds = sqtd->nextqtd;
	memset(&sqtd->qtd, 0, sizeof(struct ehci_qtd));
	sqtd->nextqtd = NULL;

out:
	splx(s);
	return (sqtd);
}

void
ehci_free_sqtd(struct ehci_softc *sc, struct ehci_soft_qtd *sqtd)
{
	int s;

	s = splusb();
	sqtd->nextqtd = sc->sc_freeqtds;
	sc->sc_freeqtds = sqtd;
	splx(s);
}

usbd_status
ehci_alloc_sqtd_chain(struct ehci_softc *sc, u_int alen, struct usbd_xfer *xfer,
    struct ehci_soft_qtd **sp, struct ehci_soft_qtd **ep)
{
	struct ehci_soft_qtd *next, *cur;
	ehci_physaddr_t dataphys, dataphyspage, dataphyslastpage, nextphys;
	u_int32_t qtdstatus;
	u_int len, curlen;
	int mps, i, iscontrol, forceshort;
	int rd = usbd_xfer_isread(xfer);
	struct usb_dma *dma = &xfer->dmabuf;

	DPRINTFN(alen<4*4096,("ehci_alloc_sqtd_chain: start len=%d\n", alen));

	len = alen;
	iscontrol = (xfer->pipe->endpoint->edesc->bmAttributes & UE_XFERTYPE) ==
	    UE_CONTROL;

	dataphys = DMAADDR(dma, 0);
	dataphyslastpage = EHCI_PAGE(dataphys + len - 1);
	qtdstatus = EHCI_QTD_ACTIVE |
	    EHCI_QTD_SET_PID(rd ? EHCI_QTD_PID_IN : EHCI_QTD_PID_OUT) |
	    EHCI_QTD_SET_CERR(3); /* IOC and BYTES set below */
	mps = UGETW(xfer->pipe->endpoint->edesc->wMaxPacketSize);
	forceshort = ((xfer->flags & USBD_FORCE_SHORT_XFER) || len == 0) &&
	    len % mps == 0;
	/*
	 * The control transfer data stage always starts with a toggle of 1.
	 * For other transfers we let the hardware track the toggle state.
	 */
	if (iscontrol)
		qtdstatus |= EHCI_QTD_SET_TOGGLE(1);

	cur = ehci_alloc_sqtd(sc);
	*sp = cur;
	if (cur == NULL)
		goto nomem;

	usb_syncmem(dma, 0, alen,
	    rd ? BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
	for (;;) {
		dataphyspage = EHCI_PAGE(dataphys);
		/* The EHCI hardware can handle at most 5 pages. */
		if (dataphyslastpage - dataphyspage <
		    EHCI_QTD_NBUFFERS * EHCI_PAGE_SIZE) {
			/* we can handle it in this QTD */
			curlen = len;
		} else {
			/* must use multiple TDs, fill as much as possible. */
			curlen = EHCI_QTD_NBUFFERS * EHCI_PAGE_SIZE -
				 EHCI_PAGE_OFFSET(dataphys);
#ifdef DIAGNOSTIC
			if (curlen > len) {
				printf("ehci_alloc_sqtd_chain: curlen=%u "
				    "len=%u offs=0x%x\n", curlen, len,
				    EHCI_PAGE_OFFSET(dataphys));
				printf("lastpage=0x%x page=0x%x phys=0x%x\n",
				    dataphyslastpage, dataphyspage, dataphys);
				curlen = len;
			}
#endif
			/* the length must be a multiple of the max size */
			curlen -= curlen % mps;
			DPRINTFN(1,("ehci_alloc_sqtd_chain: multiple QTDs, "
			    "curlen=%u\n", curlen));
#ifdef DIAGNOSTIC
			if (curlen == 0)
				panic("ehci_alloc_std: curlen == 0");
#endif
		}

		DPRINTFN(4,("ehci_alloc_sqtd_chain: dataphys=0x%08x "
		    "dataphyslastpage=0x%08x len=%u curlen=%u\n",
		    dataphys, dataphyslastpage, len, curlen));
		len -= curlen;

		/*
		 * Allocate another transfer if there's more data left,
		 * or if force last short transfer flag is set and we're
		 * allocating a multiple of the max packet size.
		 */
		if (len != 0 || forceshort) {
			next = ehci_alloc_sqtd(sc);
			if (next == NULL)
				goto nomem;
			nextphys = htole32(next->physaddr);
		} else {
			next = NULL;
			nextphys = htole32(EHCI_LINK_TERMINATE);
		}

		for (i = 0; i * EHCI_PAGE_SIZE <
		    curlen + EHCI_PAGE_OFFSET(dataphys); i++) {
			ehci_physaddr_t a = dataphys + i * EHCI_PAGE_SIZE;
			if (i != 0) /* use offset only in first buffer */
				a = EHCI_PAGE(a);
#ifdef DIAGNOSTIC
			if (i >= EHCI_QTD_NBUFFERS) {
				printf("ehci_alloc_sqtd_chain: i=%d\n", i);
				goto nomem;
			}
#endif
			cur->qtd.qtd_buffer[i] = htole32(a);
			cur->qtd.qtd_buffer_hi[i] = 0;
		}
		cur->nextqtd = next;
		cur->qtd.qtd_next = cur->qtd.qtd_altnext = nextphys;
		cur->qtd.qtd_status = htole32(qtdstatus |
		    EHCI_QTD_SET_BYTES(curlen));
		cur->len = curlen;
		DPRINTFN(10,("ehci_alloc_sqtd_chain: cbp=0x%08x end=0x%08x\n",
		    dataphys, dataphys + curlen));
		DPRINTFN(10,("ehci_alloc_sqtd_chain: curlen=%u\n", curlen));
		if (iscontrol) {
			/*
			 * adjust the toggle based on the number of packets
			 * in this qtd
			 */
			if ((((curlen + mps - 1) / mps) & 1) || curlen == 0)
				qtdstatus ^= EHCI_QTD_TOGGLE_MASK;
		}
		if (len == 0) {
			if (! forceshort)
				break;
			forceshort = 0;
		}
		usb_syncmem(&cur->dma, cur->offs, sizeof(cur->qtd),
		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
		DPRINTFN(10,("ehci_alloc_sqtd_chain: extend chain\n"));
		dataphys += curlen;
		cur = next;
	}
	cur->qtd.qtd_status |= htole32(EHCI_QTD_IOC);
	usb_syncmem(&cur->dma, cur->offs, sizeof(cur->qtd),
	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
	*ep = cur;

	DPRINTFN(10,("ehci_alloc_sqtd_chain: return sqtd=%p sqtdend=%p\n",
	    *sp, *ep));

	return (USBD_NORMAL_COMPLETION);

 nomem:
	/* XXX free chain */
	DPRINTFN(-1,("ehci_alloc_sqtd_chain: no memory\n"));
	return (USBD_NOMEM);
}

void
ehci_free_sqtd_chain(struct ehci_softc *sc, struct ehci_xfer *ex)
{
	struct ehci_pipe *epipe = (struct ehci_pipe *)ex->xfer.pipe;
	struct ehci_soft_qtd *sqtd, *next;

	DPRINTFN(10,("ehci_free_sqtd_chain: sqtd=%p\n", ex->sqtdstart));

	for (sqtd = ex->sqtdstart; sqtd != NULL; sqtd = next) {
		next = sqtd->nextqtd;
		ehci_free_sqtd(sc, sqtd);
	}
	ex->sqtdstart = ex->sqtdend = NULL;
	epipe->sqh->sqtd = NULL;
}

struct ehci_soft_itd *
ehci_alloc_itd(struct ehci_softc *sc)
{
	struct ehci_soft_itd *itd, *freeitd;
	usbd_status err;
	int i, s, offs, frindex, previndex;
	struct usb_dma dma;

	s = splusb();

	/* Find an itd that wasn't freed this frame or last frame. This can
	 * discard itds that were freed before frindex wrapped around
	 * XXX - can this lead to thrashing? Could fix by enabling wrap-around
	 *       interrupt and fiddling with list when that happens */
	frindex = (EOREAD4(sc, EHCI_FRINDEX) + 1) >> 3;
	previndex = (frindex != 0) ? frindex - 1 : sc->sc_flsize;

	freeitd = NULL;
	LIST_FOREACH(itd, &sc->sc_freeitds, u.free_list) {
		if (itd == NULL)
			break;
		if (itd->slot != frindex && itd->slot != previndex) {
			freeitd = itd;
			break;
		}
	}

	if (freeitd == NULL) {
		DPRINTFN(2, ("ehci_alloc_itd allocating chunk\n"));
		err = usb_allocmem(&sc->sc_bus, EHCI_ITD_SIZE * EHCI_ITD_CHUNK,
		    EHCI_PAGE_SIZE, &dma);

		if (err) {
			DPRINTF(("ehci_alloc_itd, alloc returned %d\n", err));
			return (NULL);
		}

		for (i = 0; i < EHCI_ITD_CHUNK; i++) {
			offs = i * EHCI_ITD_SIZE;
			itd = KERNADDR(&dma, offs);
			itd->physaddr = DMAADDR(&dma, offs);
			itd->dma = dma;
			itd->offs = offs;
			LIST_INSERT_HEAD(&sc->sc_freeitds, itd, u.free_list);
		}
		freeitd = LIST_FIRST(&sc->sc_freeitds);
	}

	itd = freeitd;
	LIST_REMOVE(itd, u.free_list);
	memset(&itd->itd, 0, sizeof(struct ehci_itd));
	usb_syncmem(&itd->dma, itd->offs + offsetof(struct ehci_itd, itd_next),
	    sizeof(itd->itd.itd_next), BUS_DMASYNC_PREWRITE |
	    BUS_DMASYNC_PREREAD);

	itd->u.frame_list.next = NULL;
	itd->u.frame_list.prev = NULL;
	itd->xfer_next = NULL;
	itd->slot = 0;
	splx(s);

	return (itd);
}

void
ehci_free_itd(struct ehci_softc *sc, struct ehci_soft_itd *itd)
{
	int s;

	s = splusb();
	LIST_INSERT_HEAD(&sc->sc_freeitds, itd, u.free_list);
	splx(s);
}

/****************/

/*
 * Close a reqular pipe.
 * Assumes that there are no pending transactions.
 */
void
ehci_close_pipe(struct usbd_pipe *pipe)
{
	struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;
	struct ehci_softc *sc = (struct ehci_softc *)pipe->device->bus;
	struct ehci_soft_qh *sqh = epipe->sqh;
	int s;

	s = splusb();
	ehci_rem_qh(sc, sqh);
	splx(s);
	pipe->endpoint->savedtoggle =
	    EHCI_QTD_GET_TOGGLE(letoh32(sqh->qh.qh_qtd.qtd_status));
	ehci_free_sqh(sc, epipe->sqh);
}

/*
 * Abort a device request.
 * If this routine is called at splusb() it guarantees that the request
 * will be removed from the hardware scheduling and that the callback
 * for it will be called with USBD_CANCELLED status.
 * It's impossible to guarantee that the requested transfer will not
 * have happened since the hardware runs concurrently.
 * If the transaction has already happened we rely on the ordinary
 * interrupt processing to process it.
 */
void
ehci_abort_xfer(struct usbd_xfer *xfer, usbd_status status)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
	struct ehci_xfer *ex = (struct ehci_xfer*)xfer;
	struct ehci_soft_qh *sqh = epipe->sqh;
	struct ehci_soft_qtd *sqtd;
	int s;

	DPRINTF(("ehci_abort_xfer: xfer=%p pipe=%p\n", xfer, epipe));

	if (sc->sc_bus.dying) {
		/* If we're dying, just do the software part. */
		s = splusb();
		xfer->status = status;	/* make software ignore it */
		timeout_del(&xfer->timeout_handle);
		usb_rem_task(xfer->device, &xfer->abort_task);
#ifdef DIAGNOSTIC
		ex->isdone = 1;
#endif
		usb_transfer_complete(xfer);
		splx(s);
		return;
	}

	if (xfer->device->bus->intr_context)
		panic("ehci_abort_xfer: not in process context");

	/*
	 * If an abort is already in progress then just wait for it to
	 * complete and return.
	 */
	if (ex->ehci_xfer_flags & EHCI_XFER_ABORTING) {
		DPRINTFN(2, ("ehci_abort_xfer: already aborting\n"));
		/* No need to wait if we're aborting from a timeout. */
		if (status == USBD_TIMEOUT)
			return;
		/* Override the status which might be USBD_TIMEOUT. */
		xfer->status = status;
		DPRINTFN(2, ("ehci_abort_xfer: waiting for abort to finish\n"));
		ex->ehci_xfer_flags |= EHCI_XFER_ABORTWAIT;
		while (ex->ehci_xfer_flags & EHCI_XFER_ABORTING)
			tsleep(&ex->ehci_xfer_flags, PZERO, "ehciaw", 0);
		return;
	}

	/*
	 * Step 1: Make interrupt routine and timeouts ignore xfer.
	 */
	s = splusb();
	ex->ehci_xfer_flags |= EHCI_XFER_ABORTING;
	xfer->status = status;	/* make software ignore it */
	timeout_del(&xfer->timeout_handle);
	usb_rem_task(xfer->device, &xfer->abort_task);
	splx(s);

	/*
	 * Step 2: Deactivate all of the qTDs that we will be removing,
	 * otherwise the queue head may go active again.
	 */
	usb_syncmem(&sqh->dma,
	    sqh->offs + offsetof(struct ehci_qh, qh_qtd.qtd_status),
	    sizeof(sqh->qh.qh_qtd.qtd_status),
	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
	sqh->qh.qh_qtd.qtd_status = htole32(EHCI_QTD_HALTED);
	usb_syncmem(&sqh->dma,
	    sqh->offs + offsetof(struct ehci_qh, qh_qtd.qtd_status),
	    sizeof(sqh->qh.qh_qtd.qtd_status),
	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);

	for (sqtd = ex->sqtdstart; sqtd != NULL; sqtd = sqtd->nextqtd) {
		usb_syncmem(&sqtd->dma,
		    sqtd->offs + offsetof(struct ehci_qtd, qtd_status),
		    sizeof(sqtd->qtd.qtd_status),
		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
		sqtd->qtd.qtd_status = htole32(EHCI_QTD_HALTED);
		usb_syncmem(&sqtd->dma,
		    sqtd->offs + offsetof(struct ehci_qtd, qtd_status),
		    sizeof(sqtd->qtd.qtd_status),
		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
	}
	ehci_sync_hc(sc);

	/*
	 * Step 3: Make sure the soft interrupt routine has run. This
	 * should remove any completed items off the queue.
	 * The hardware has no reference to completed items (TDs).
	 * It's safe to remove them at any time.
	 */
	s = splusb();
	sc->sc_softwake = 1;
	usb_schedsoftintr(&sc->sc_bus);
	tsleep(&sc->sc_softwake, PZERO, "ehciab", 0);

#ifdef DIAGNOSTIC
	ex->isdone = 1;
#endif
	/* Do the wakeup first to avoid touching the xfer after the callback. */
	ex->ehci_xfer_flags &= ~EHCI_XFER_ABORTING;
	if (ex->ehci_xfer_flags & EHCI_XFER_ABORTWAIT) {
		ex->ehci_xfer_flags &= ~EHCI_XFER_ABORTWAIT;
		wakeup(&ex->ehci_xfer_flags);
	}
	usb_transfer_complete(xfer);

	splx(s);
}

 void
ehci_abort_isoc_xfer(struct usbd_xfer *xfer, usbd_status status)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	struct ehci_xfer *ex = (struct ehci_xfer *)xfer;
	ehci_isoc_trans_t trans_status;
	struct ehci_soft_itd *itd;
	int s, i, wake;


	DPRINTF(("ehci_abort_isoc_xfer: xfer %p pipe %p\n", xfer, xfer->pipe));

	if (sc->sc_bus.dying) {
		s = splusb();
		xfer->status = status;
		timeout_del(&xfer->timeout_handle);
		usb_rem_task(xfer->device, &xfer->abort_task);
		usb_transfer_complete(xfer);
		splx(s);
		return;
	}

	if (ex->ehci_xfer_flags & EHCI_XFER_ABORTING) {
		DPRINTFN(2, ("ehci_abort_isoc_xfer: already aborting\n"));

#ifdef DIAGNOSTIC
		if (status == USBD_TIMEOUT)
		printf("ehci_abort_xfer: TIMEOUT while aborting\n");
#endif

		xfer->status = status;
		DPRINTFN(2, ("ehci_abort_xfer: waiting for abort to finish\n"));
		ex->ehci_xfer_flags |= EHCI_XFER_ABORTING;
		while (ex->ehci_xfer_flags & EHCI_XFER_ABORTING)
			tsleep(&ex->ehci_xfer_flags, PZERO, "ehciiaw", 0);
		return;
	}
	ex->ehci_xfer_flags |= EHCI_XFER_ABORTING;

	xfer->status = status;
	timeout_del(&xfer->timeout_handle);
	usb_rem_task(xfer->device, &xfer->abort_task);

	s = splusb();
	for (itd = ex->itdstart; itd != NULL; itd = itd->xfer_next) {
		for (i = 0; i < 8; i++) {
			trans_status = letoh32(itd->itd.itd_ctl[i]);
			trans_status &= ~EHCI_ITD_ACTIVE;
			itd->itd.itd_ctl[i] = htole32(trans_status);
		}
	}
	splx(s);

	s = splusb();
	sc->sc_softwake = 1;
	usb_schedsoftintr(&sc->sc_bus);
	tsleep(&sc->sc_softwake, PZERO, "ehciab", 0);
	splx(s);

#ifdef DIAGNOSTIC
	ex->isdone = 1;
#endif
	wake = ex->ehci_xfer_flags & EHCI_XFER_ABORTING;
	ex->ehci_xfer_flags &= ~(EHCI_XFER_ABORTING | EHCI_XFER_ABORTWAIT);
	usb_transfer_complete(xfer);
	if (wake)
		wakeup(&ex->ehci_xfer_flags);

	return;
}

void
ehci_timeout(void *addr)
{
	struct usbd_xfer *xfer = addr;
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;

	if (sc->sc_bus.dying) {
		ehci_timeout_task(addr);
		return;
	}

	usb_init_task(&xfer->abort_task, ehci_timeout_task, addr,
	    USB_TASK_TYPE_ABORT);
	usb_add_task(xfer->device, &xfer->abort_task);
}

void
ehci_timeout_task(void *addr)
{
	struct usbd_xfer *xfer = addr;
	int s;

	DPRINTF(("%s: xfer=%p\n", __func__, xfer));

	s = splusb();
	ehci_abort_xfer(xfer, USBD_TIMEOUT);
	splx(s);
}

/*
 * Some EHCI chips from VIA seem to trigger interrupts before writing back the
 * qTD status, or miss signalling occasionally under heavy load.  If the host
 * machine is too fast, we we can miss transaction completion - when we scan
 * the active list the transaction still seems to be active.  This generally
 * exhibits itself as a umass stall that never recovers.
 *
 * We work around this behaviour by setting up this callback after any softintr
 * that completes with transactions still pending, giving us another chance to
 * check for completion after the writeback has taken place.
 */
void
ehci_intrlist_timeout(void *arg)
{
	struct ehci_softc *sc = arg;
	int s;

	if (sc->sc_bus.dying)
		return;

	s = splusb();
	DPRINTFN(1, ("ehci_intrlist_timeout\n"));
	usb_schedsoftintr(&sc->sc_bus);
	splx(s);
}

/************************/

usbd_status
ehci_device_ctrl_transfer(struct usbd_xfer *xfer)
{
	usbd_status err;

	/* Insert last in queue. */
	err = usb_insert_transfer(xfer);
	if (err)
		return (err);

	/* Pipe isn't running, start first */
	return (ehci_device_ctrl_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
}

usbd_status
ehci_device_ctrl_start(struct usbd_xfer *xfer)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	usbd_status err;

	if (sc->sc_bus.dying)
		return (USBD_IOERROR);

#ifdef DIAGNOSTIC
	if (!(xfer->rqflags & URQ_REQUEST)) {
		/* XXX panic */
		printf("ehci_device_ctrl_transfer: not a request\n");
		return (USBD_INVAL);
	}
#endif

	err = ehci_device_request(xfer);
	if (err)
		return (err);

	if (sc->sc_bus.use_polling)
		ehci_waitintr(sc, xfer);

	return (USBD_IN_PROGRESS);
}

void
ehci_device_ctrl_done(struct usbd_xfer *xfer)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	struct ehci_xfer *ex = (struct ehci_xfer *)xfer;

	DPRINTFN(10,("ehci_ctrl_done: xfer=%p\n", xfer));

#ifdef DIAGNOSTIC
	if (!(xfer->rqflags & URQ_REQUEST)) {
		panic("ehci_ctrl_done: not a request");
	}
#endif

	if (xfer->status != USBD_NOMEM && ehci_active_intr_list(ex)) {
		ehci_del_intr_list(sc, ex);	/* remove from active list */
		ehci_free_sqtd_chain(sc, ex);
	}

	DPRINTFN(5, ("ehci_ctrl_done: length=%u\n", xfer->actlen));
}

/* Abort a device control request. */
void
ehci_device_ctrl_abort(struct usbd_xfer *xfer)
{
	DPRINTF(("ehci_device_ctrl_abort: xfer=%p\n", xfer));
	ehci_abort_xfer(xfer, USBD_CANCELLED);
}

/* Close a device control pipe. */
void
ehci_device_ctrl_close(struct usbd_pipe *pipe)
{
	DPRINTF(("ehci_device_ctrl_close: pipe=%p\n", pipe));
	ehci_close_pipe(pipe);
}

usbd_status
ehci_device_request(struct usbd_xfer *xfer)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
	struct ehci_xfer *ex = (struct ehci_xfer *)xfer;
	usb_device_request_t *req = &xfer->request;
	struct ehci_soft_qtd *setup, *stat, *next;
	struct ehci_soft_qh *sqh;
	u_int len = UGETW(req->wLength);
	usbd_status err;
	int s;

	DPRINTFN(3,("ehci_device_request: type=0x%02x, request=0x%02x, "
	    "wValue=0x%04x, wIndex=0x%04x len=%u, addr=%d, endpt=%d\n",
	    req->bmRequestType, req->bRequest, UGETW(req->wValue),
	    UGETW(req->wIndex), UGETW(req->wLength), xfer->device->address,
	    xfer->pipe->endpoint->edesc->bEndpointAddress));

	setup = ehci_alloc_sqtd(sc);
	if (setup == NULL) {
		err = USBD_NOMEM;
		goto bad1;
	}
	stat = ehci_alloc_sqtd(sc);
	if (stat == NULL) {
		err = USBD_NOMEM;
		goto bad2;
	}

	sqh = epipe->sqh;

	/* Set up data transaction */
	if (len != 0) {
		struct ehci_soft_qtd *end;

		err = ehci_alloc_sqtd_chain(sc, len, xfer, &next, &end);
		if (err)
			goto bad3;
		end->qtd.qtd_status &= htole32(~EHCI_QTD_IOC);
		end->nextqtd = stat;
		end->qtd.qtd_next =
		    end->qtd.qtd_altnext = htole32(stat->physaddr);
		usb_syncmem(&end->dma, end->offs, sizeof(end->qtd),
		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
	} else {
		next = stat;
	}

	memcpy(KERNADDR(&epipe->u.ctl.reqdma, 0), req, sizeof(*req));
	usb_syncmem(&epipe->u.ctl.reqdma, 0, sizeof *req, BUS_DMASYNC_PREWRITE);

	/* Clear toggle */
	setup->qtd.qtd_status = htole32(
	    EHCI_QTD_ACTIVE |
	    EHCI_QTD_SET_PID(EHCI_QTD_PID_SETUP) |
	    EHCI_QTD_SET_CERR(3) |
	    EHCI_QTD_SET_TOGGLE(0) |
	    EHCI_QTD_SET_BYTES(sizeof(*req)));
	setup->qtd.qtd_buffer[0] = htole32(DMAADDR(&epipe->u.ctl.reqdma, 0));
	setup->qtd.qtd_buffer_hi[0] = 0;
	setup->nextqtd = next;
	setup->qtd.qtd_next = setup->qtd.qtd_altnext = htole32(next->physaddr);
	setup->len = sizeof(*req);
	usb_syncmem(&setup->dma, setup->offs, sizeof(setup->qtd),
	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);

	stat->qtd.qtd_status = htole32(
	    EHCI_QTD_ACTIVE |
	    EHCI_QTD_SET_PID(usbd_xfer_isread(xfer) ?
		EHCI_QTD_PID_OUT : EHCI_QTD_PID_IN) |
	    EHCI_QTD_SET_CERR(3) |
	    EHCI_QTD_SET_TOGGLE(1) |
	    EHCI_QTD_IOC);
	stat->qtd.qtd_buffer[0] = 0; /* XXX not needed? */
	stat->qtd.qtd_buffer_hi[0] = 0; /* XXX not needed? */
	stat->nextqtd = NULL;
	stat->qtd.qtd_next = stat->qtd.qtd_altnext = htole32(EHCI_LINK_TERMINATE);
	stat->len = 0;
	usb_syncmem(&stat->dma, stat->offs, sizeof(stat->qtd),
	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);

#ifdef EHCI_DEBUG
	if (ehcidebug > 5) {
		DPRINTF(("ehci_device_request:\n"));
		ehci_dump_sqh(sqh);
		ehci_dump_sqtds(setup);
	}
#endif

	ex->sqtdstart = setup;
	ex->sqtdend = stat;
#ifdef DIAGNOSTIC
	if (!ex->isdone) {
		printf("ehci_device_request: not done, ex=%p\n", ex);
	}
	ex->isdone = 0;
#endif

	/* Insert qTD in QH list. */
	s = splusb();
	ehci_set_qh_qtd(sqh, setup);
	if (xfer->timeout && !sc->sc_bus.use_polling) {
		timeout_del(&xfer->timeout_handle);
		timeout_set(&xfer->timeout_handle, ehci_timeout, xfer);
		timeout_add_msec(&xfer->timeout_handle, xfer->timeout);
	}
	ehci_add_intr_list(sc, ex);
	xfer->status = USBD_IN_PROGRESS;
	splx(s);

#ifdef EHCI_DEBUG
	if (ehcidebug > 10) {
		DPRINTF(("ehci_device_request: status=%x\n",
		    EOREAD4(sc, EHCI_USBSTS)));
		delay(10000);
		ehci_dump_regs(sc);
		ehci_dump_sqh(sc->sc_async_head);
		ehci_dump_sqh(sqh);
		ehci_dump_sqtds(setup);
	}
#endif

	return (USBD_NORMAL_COMPLETION);

 bad3:
	ehci_free_sqtd(sc, stat);
 bad2:
	ehci_free_sqtd(sc, setup);
 bad1:
	DPRINTFN(-1,("ehci_device_request: no memory\n"));
	xfer->status = err;
	usb_transfer_complete(xfer);
	return (err);
}

/************************/

usbd_status
ehci_device_bulk_transfer(struct usbd_xfer *xfer)
{
	usbd_status err;

	/* Insert last in queue. */
	err = usb_insert_transfer(xfer);
	if (err)
		return (err);

	/* Pipe isn't running, start first */
	return (ehci_device_bulk_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
}

usbd_status
ehci_device_bulk_start(struct usbd_xfer *xfer)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
	struct ehci_xfer *ex = (struct ehci_xfer *)xfer;
	struct ehci_soft_qtd *data, *dataend;
	struct ehci_soft_qh *sqh;
	usbd_status err;
	int s;

	DPRINTFN(2, ("ehci_device_bulk_start: xfer=%p len=%u flags=%d\n",
	    xfer, xfer->length, xfer->flags));

	if (sc->sc_bus.dying)
		return (USBD_IOERROR);

#ifdef DIAGNOSTIC
	if (xfer->rqflags & URQ_REQUEST)
		panic("ehci_device_bulk_start: a request");
#endif

	sqh = epipe->sqh;

	err = ehci_alloc_sqtd_chain(sc, xfer->length, xfer, &data, &dataend);
	if (err) {
		DPRINTFN(-1,("ehci_device_bulk_start: no memory\n"));
		xfer->status = err;
		usb_transfer_complete(xfer);
		return (err);
	}

#ifdef EHCI_DEBUG
	if (ehcidebug > 5) {
		DPRINTF(("ehci_device_bulk_start: data(1)\n"));
		ehci_dump_sqh(sqh);
		ehci_dump_sqtds(data);
	}
#endif

	/* Set up interrupt info. */
	ex->sqtdstart = data;
	ex->sqtdend = dataend;
#ifdef DIAGNOSTIC
	if (!ex->isdone) {
		printf("ehci_device_bulk_start: not done, ex=%p\n", ex);
	}
	ex->isdone = 0;
#endif

	s = splusb();
	ehci_set_qh_qtd(sqh, data);
	if (xfer->timeout && !sc->sc_bus.use_polling) {
		timeout_del(&xfer->timeout_handle);
		timeout_set(&xfer->timeout_handle, ehci_timeout, xfer);
		timeout_add_msec(&xfer->timeout_handle, xfer->timeout);
	}
	ehci_add_intr_list(sc, ex);
	xfer->status = USBD_IN_PROGRESS;
	splx(s);

#ifdef EHCI_DEBUG
	if (ehcidebug > 10) {
		DPRINTF(("ehci_device_bulk_start: data(2)\n"));
		delay(10000);
		DPRINTF(("ehci_device_bulk_start: data(3)\n"));
		ehci_dump_regs(sc);
#if 0
		printf("async_head:\n");
		ehci_dump_sqh(sc->sc_async_head);
#endif
		printf("sqh:\n");
		ehci_dump_sqh(sqh);
		ehci_dump_sqtds(data);
	}
#endif

	if (sc->sc_bus.use_polling)
		ehci_waitintr(sc, xfer);

	return (USBD_IN_PROGRESS);
}

void
ehci_device_bulk_abort(struct usbd_xfer *xfer)
{
	DPRINTF(("ehci_device_bulk_abort: xfer=%p\n", xfer));
	ehci_abort_xfer(xfer, USBD_CANCELLED);
}

/*
 * Close a device bulk pipe.
 */
void
ehci_device_bulk_close(struct usbd_pipe *pipe)
{
	DPRINTF(("ehci_device_bulk_close: pipe=%p\n", pipe));
	ehci_close_pipe(pipe);
}

void
ehci_device_bulk_done(struct usbd_xfer *xfer)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	struct ehci_xfer *ex = (struct ehci_xfer *)xfer;

	DPRINTFN(10,("ehci_bulk_done: xfer=%p, actlen=%d\n",
	    xfer, xfer->actlen));

	if (xfer->status != USBD_NOMEM && ehci_active_intr_list(ex)) {
		ehci_del_intr_list(sc, ex);	/* remove from active list */
		ehci_free_sqtd_chain(sc, ex);
		usb_syncmem(&xfer->dmabuf, 0, xfer->length,
		    usbd_xfer_isread(xfer) ?
		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
	}

	DPRINTFN(5, ("ehci_bulk_done: length=%d\n", xfer->actlen));
}

/************************/

usbd_status
ehci_device_setintr(struct ehci_softc *sc, struct ehci_soft_qh *sqh, int ival)
{
	struct ehci_soft_islot *isp;
	int islot, lev;

	/* Find a poll rate that is large enough. */
	for (lev = EHCI_IPOLLRATES - 1; lev > 0; lev--)
		if (EHCI_ILEV_IVAL(lev) <= ival)
			break;

	/* Pick an interrupt slot at the right level. */
	/* XXX could do better than picking at random */
	islot = EHCI_IQHIDX(lev, arc4random());

	sqh->islot = islot;
	isp = &sc->sc_islots[islot];
	ehci_add_qh(sqh, isp->sqh);

	return (USBD_NORMAL_COMPLETION);
}

usbd_status
ehci_device_intr_transfer(struct usbd_xfer *xfer)
{
	usbd_status err;

	/* Insert last in queue. */
	err = usb_insert_transfer(xfer);
	if (err)
		return (err);

	/*
	 * Pipe isn't running (otherwise err would be USBD_INPROG),
	 * so start it first.
	 */
	return (ehci_device_intr_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
}

usbd_status
ehci_device_intr_start(struct usbd_xfer *xfer)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	struct ehci_xfer *ex = (struct ehci_xfer *)xfer;
	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
	struct ehci_soft_qtd *data, *dataend;
	struct ehci_soft_qh *sqh;
	usbd_status err;
	int s;

	DPRINTFN(2, ("ehci_device_intr_start: xfer=%p len=%u flags=%d\n",
	    xfer, xfer->length, xfer->flags));

	if (sc->sc_bus.dying)
		return (USBD_IOERROR);

#ifdef DIAGNOSTIC
	if (xfer->rqflags & URQ_REQUEST)
		panic("ehci_device_intr_start: a request");
#endif

	sqh = epipe->sqh;

	err = ehci_alloc_sqtd_chain(sc, xfer->length, xfer, &data, &dataend);
	if (err) {
		DPRINTFN(-1, ("ehci_device_intr_start: no memory\n"));
		xfer->status = err;
		usb_transfer_complete(xfer);
		return (err);
	}

#ifdef EHCI_DEBUG
	if (ehcidebug > 5) {
		DPRINTF(("ehci_device_intr_start: data(1)\n"));
		ehci_dump_sqh(sqh);
		ehci_dump_sqtds(data);
	}
#endif

	/* Set up interrupt info. */
	ex->sqtdstart = data;
	ex->sqtdend = dataend;
#ifdef DIAGNOSTIC
	if (!ex->isdone)
		printf("ehci_device_intr_start: not done, ex=%p\n", ex);
	ex->isdone = 0;
#endif

	s = splusb();
	ehci_set_qh_qtd(sqh, data);
	if (xfer->timeout && !sc->sc_bus.use_polling) {
		timeout_del(&xfer->timeout_handle);
		timeout_set(&xfer->timeout_handle, ehci_timeout, xfer);
		timeout_add_msec(&xfer->timeout_handle, xfer->timeout);
	}
	ehci_add_intr_list(sc, ex);
	xfer->status = USBD_IN_PROGRESS;
	splx(s);

#ifdef EHCI_DEBUG
	if (ehcidebug > 10) {
		DPRINTF(("ehci_device_intr_start: data(2)\n"));
		delay(10000);
		DPRINTF(("ehci_device_intr_start: data(3)\n"));
		ehci_dump_regs(sc);
		printf("sqh:\n");
		ehci_dump_sqh(sqh);
		ehci_dump_sqtds(data);
	}
#endif

	if (sc->sc_bus.use_polling)
		ehci_waitintr(sc, xfer);

	return (USBD_IN_PROGRESS);
}

void
ehci_device_intr_abort(struct usbd_xfer *xfer)
{
	KASSERT(!xfer->pipe->repeat || xfer->pipe->intrxfer == xfer);

	/*
	 * XXX - abort_xfer uses ehci_sync_hc, which syncs via the advance
	 *       async doorbell. That's dependant on the async list, wheras
	 *       intr xfers are periodic, should not use this?
	 */
	ehci_abort_xfer(xfer, USBD_CANCELLED);
}

void
ehci_device_intr_close(struct usbd_pipe *pipe)
{
	DPRINTF(("ehci_device_intr_close: pipe=%p\n", pipe));
	ehci_close_pipe(pipe);
}

void
ehci_device_intr_done(struct usbd_xfer *xfer)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
	struct ehci_xfer *ex = (struct ehci_xfer *)xfer;
	struct ehci_soft_qtd *data, *dataend;
	struct ehci_soft_qh *sqh;
	usbd_status err;
	int s;

	DPRINTFN(10, ("ehci_device_intr_done: xfer=%p, actlen=%d\n",
	    xfer, xfer->actlen));

	if (xfer->pipe->repeat) {
		ehci_free_sqtd_chain(sc, ex);

		usb_syncmem(&xfer->dmabuf, 0, xfer->length,
		    usbd_xfer_isread(xfer) ?
		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
		sqh = epipe->sqh;

		err = ehci_alloc_sqtd_chain(sc, xfer->length, xfer, &data, &dataend);
		if (err) {
			DPRINTFN(-1, ("ehci_device_intr_done: no memory\n"));
			xfer->status = err;
			return;
		}

		/* Set up interrupt info. */
		ex->sqtdstart = data;
		ex->sqtdend = dataend;
#ifdef DIAGNOSTIC
		if (!ex->isdone) {
			printf("ehci_device_intr_done: not done, ex=%p\n",
			    ex);
		}
		ex->isdone = 0;
#endif

		s = splusb();
		ehci_set_qh_qtd(sqh, data);
		if (xfer->timeout && !sc->sc_bus.use_polling) {
			timeout_del(&xfer->timeout_handle);
			timeout_set(&xfer->timeout_handle, ehci_timeout, xfer);
			timeout_add_msec(&xfer->timeout_handle, xfer->timeout);
		}
		splx(s);

		xfer->status = USBD_IN_PROGRESS;
	} else if (xfer->status != USBD_NOMEM && ehci_active_intr_list(ex)) {
		ehci_del_intr_list(sc, ex); /* remove from active list */
		ehci_free_sqtd_chain(sc, ex);
		usb_syncmem(&xfer->dmabuf, 0, xfer->length,
		    usbd_xfer_isread(xfer) ?
		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
	}
}

/************************/

usbd_status
ehci_device_isoc_transfer(struct usbd_xfer *xfer)
{
	usbd_status err;

	err = usb_insert_transfer(xfer);
	if (err && err != USBD_IN_PROGRESS)
		return (err);

	return (ehci_device_isoc_start(xfer));
}

usbd_status
ehci_device_isoc_start(struct usbd_xfer *xfer)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
	struct ehci_xfer *ex = (struct ehci_xfer *)xfer;
	struct ehci_soft_itd *itd, *prev, *start, *stop;
	struct usb_dma *dma_buf;
	int i, j, k, frames, uframes, ufrperframe;
	int s, trans_count, offs;
	int frindex;

	start = NULL;
	prev = NULL;
	itd = NULL;
	trans_count = 0;

	/*
	 * To allow continuous transfers, above we start all transfers
	 * immediately. However, we're still going to get usbd_start_next call
	 * this when another xfer completes. So, check if this is already
	 * in progress or not
	 */

	if (ex->itdstart != NULL)
		return (USBD_IN_PROGRESS);

	DPRINTFN(2, ("ehci_device_isoc_start: xfer %p len %u flags %d\n",
	    xfer, xfer->length, xfer->flags));

	if (sc->sc_bus.dying)
		return (USBD_IOERROR);

	/*
	 * To avoid complication, don't allow a request right now that'll span
	 * the entire frame table. To within 4 frames, to allow some leeway
	 * on either side of where the hc currently is.
	 */
	if ((1 << (xfer->pipe->endpoint->edesc->bInterval - 1)) *
	    xfer->nframes >= (sc->sc_flsize - 4) * 8) {
		printf("ehci: isoc descriptor requested that spans the entire "
		    "frametable, too many frames\n");
		return (USBD_INVAL);
	}

#ifdef DIAGNOSTIC
	if (xfer->rqflags & URQ_REQUEST)
		panic("ehci_device_isoc_start: request");

	if (!ex->isdone)
		printf("ehci_device_isoc_start: not done, ex = %p\n", ex);
	ex->isdone = 0;
#endif

	/*
	 * Step 1: Allocate and initialize itds, how many do we need?
	 * One per transfer if interval >= 8 microframes, fewer if we use
	 * multiple microframes per frame.
	 */

	i = xfer->pipe->endpoint->edesc->bInterval;
	if (i > 16 || i == 0) {
		/* Spec page 271 says intervals > 16 are invalid */
		DPRINTF(("ehci_device_isoc_start: bInvertal %d invalid\n", i));
		return (USBD_INVAL);
	}

	switch (i) {
	case 1:
		ufrperframe = 8;
		break;
	case 2:
		ufrperframe = 4;
		break;
	case 3:
		ufrperframe = 2;
		break;
	default:
		ufrperframe = 1;
		break;
	}
	frames = (xfer->nframes + (ufrperframe - 1)) / ufrperframe;
	uframes = 8 / ufrperframe;

	if (frames == 0) {
		DPRINTF(("ehci_device_isoc_start: frames == 0\n"));
		return (USBD_INVAL);
	}

	dma_buf = &xfer->dmabuf;
	offs = 0;

	for (i = 0; i < frames; i++) {
		int froffs = offs;
		itd = ehci_alloc_itd(sc);

		if (prev != NULL) {
			prev->itd.itd_next =
			    htole32(itd->physaddr | EHCI_LINK_ITD);
			prev->xfer_next = itd;
		} else {
			start = itd;
		}

		/*
		 * Step 1.5, initialize uframes
		 */
		for (j = 0; j < 8; j += uframes) {
			/* Calculate which page in the list this starts in */
			int addr = DMAADDR(dma_buf, froffs);
			addr = EHCI_PAGE_OFFSET(addr);
			addr += (offs - froffs);
			addr = EHCI_PAGE(addr);
			addr /= EHCI_PAGE_SIZE;

			/* This gets the initial offset into the first page,
			 * looks how far further along the current uframe
			 * offset is. Works out how many pages that is.
			 */

			itd->itd.itd_ctl[j] = htole32 ( EHCI_ITD_ACTIVE |
			    EHCI_ITD_SET_LEN(xfer->frlengths[trans_count]) | 
			    EHCI_ITD_SET_PG(addr) |
			    EHCI_ITD_SET_OFFS(EHCI_PAGE_OFFSET(DMAADDR(dma_buf,
			    offs))));

			offs += xfer->frlengths[trans_count];
			trans_count++;

			if (trans_count >= xfer->nframes) { /*Set IOC*/
				itd->itd.itd_ctl[j] |= htole32(EHCI_ITD_IOC);
				break;
			}
		}

		/* Step 1.75, set buffer pointers. To simplify matters, all
		 * pointers are filled out for the next 7 hardware pages in
		 * the dma block, so no need to worry what pages to cover
		 * and what to not.
		 */

		for (j=0; j < 7; j++) {
			/*
			 * Don't try to lookup a page that's past the end
			 * of buffer
			 */
			int page_offs = EHCI_PAGE(froffs +
			    (EHCI_PAGE_SIZE * j));

			if (page_offs >= dma_buf->block->size)
				break;

			long long page = DMAADDR(dma_buf, page_offs);
			page = EHCI_PAGE(page);
			itd->itd.itd_bufr[j] =
			    htole32(EHCI_ITD_SET_BPTR(page));
			itd->itd.itd_bufr_hi[j] =
			    htole32(page >> 32);
		}

		/*
		 * Other special values
		 */

		k = xfer->pipe->endpoint->edesc->bEndpointAddress;
		itd->itd.itd_bufr[0] |=
		    htole32(EHCI_ITD_SET_EP(UE_GET_ADDR(k)) |
		    EHCI_ITD_SET_DADDR(xfer->pipe->device->address));

		k = (UE_GET_DIR(xfer->pipe->endpoint->edesc->bEndpointAddress))
		    ? 1 : 0;
		j = UGETW(xfer->pipe->endpoint->edesc->wMaxPacketSize);
		itd->itd.itd_bufr[1] |= htole32(EHCI_ITD_SET_DIR(k) |
		    EHCI_ITD_SET_MAXPKT(UE_GET_SIZE(j)));

		/* FIXME: handle invalid trans */
		itd->itd.itd_bufr[2] |= 
		    htole32(EHCI_ITD_SET_MULTI(UE_GET_TRANS(j)+1));
		prev = itd;
	} /* End of frame */

	stop = itd;
	stop->xfer_next = NULL;

	/*
	 * Part 2: Transfer descriptors have now been set up, now they must
	 * be scheduled into the period frame list. Erk. Not wanting to
	 * complicate matters, transfer is denied if the transfer spans
	 * more than the period frame list.
	 */

	s = splusb();

	/* Start inserting frames */
	if (epipe->u.isoc.cur_xfers > 0) {
		frindex = epipe->u.isoc.next_frame;
	} else {
		frindex = EOREAD4(sc, EHCI_FRINDEX);
		frindex = frindex >> 3; /* Erase microframe index */
		frindex += 2;
	}

	if (frindex >= sc->sc_flsize)
		frindex &= (sc->sc_flsize - 1);

	/* Whats the frame interval? */
	i = (1 << (xfer->pipe->endpoint->edesc->bInterval - 1));
	if (i / 8 == 0)
		i = 1;
	else
		i /= 8;

	itd = start;
	for (j = 0; j < frames; j++) {
		if (itd == NULL)
			panic("ehci: unexpectedly ran out of isoc itds, "
			    "isoc_start");

		itd->itd.itd_next = sc->sc_flist[frindex];
		if (itd->itd.itd_next == 0)
			/* FIXME: frindex table gets initialized to NULL
			 * or htole32(EHCI_LINK_TERMINATE)? */
			itd->itd.itd_next = htole32(htole32(EHCI_LINK_TERMINATE));

		sc->sc_flist[frindex] = htole32(EHCI_LINK_ITD | itd->physaddr);
		itd->u.frame_list.next = sc->sc_softitds[frindex];
		sc->sc_softitds[frindex] = itd;
		if (itd->u.frame_list.next != NULL)
			itd->u.frame_list.next->u.frame_list.prev = itd;
		itd->slot = frindex;
		itd->u.frame_list.prev = NULL;

		frindex += i;
		if (frindex >= sc->sc_flsize)
			frindex -= sc->sc_flsize;

		itd = itd->xfer_next;
	}

	epipe->u.isoc.cur_xfers++;
	epipe->u.isoc.next_frame = frindex;

	ex->itdstart = start;
	ex->itdend = stop;
	ex->sqtdstart = NULL;
	ex->sqtdend = NULL;

	ehci_add_intr_list(sc, ex);
	xfer->status = USBD_IN_PROGRESS;
	xfer->done = 0;
	splx(s);

	if (sc->sc_bus.use_polling) {
		DPRINTF(("Starting ehci isoc xfer with polling. Bad idea?\n"));
		ehci_waitintr(sc, xfer);
	}

	return (USBD_IN_PROGRESS);
}

void
ehci_device_isoc_abort(struct usbd_xfer *xfer)
{
	DPRINTFN(1, ("ehci_device_isoc_abort: xfer = %p\n", xfer));
	ehci_abort_isoc_xfer(xfer, USBD_CANCELLED);
}

void
ehci_device_isoc_close(struct usbd_pipe *pipe)
{
	DPRINTFN(1, ("ehci_device_isoc_close: nothing in the pipe to free?\n"));
}

void
ehci_device_isoc_done(struct usbd_xfer *xfer)
{
	struct ehci_softc *sc = (struct ehci_softc *)xfer->device->bus;
	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
	struct ehci_xfer *ex = (struct ehci_xfer *)xfer;
	int s;

	s = splusb();
	epipe->u.isoc.cur_xfers--;
	if (xfer->status != USBD_NOMEM && ehci_active_intr_list(ex)) {
		ehci_del_intr_list(sc, ex);
		ehci_rem_free_itd_chain(sc, ex);
	}
	splx(s);
}