summaryrefslogtreecommitdiff
path: root/sys/dev/usb/uhci.c
blob: ca26e0ac29c16f62c0b5fe125312d5c935935107 (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
/*	$OpenBSD: uhci.c,v 1.140 2017/02/02 22:31:05 chl Exp $	*/
/*	$NetBSD: uhci.c,v 1.172 2003/02/23 04:19:26 simonb Exp $	*/
/*	$FreeBSD: src/sys/dev/usb/uhci.c,v 1.33 1999/11/17 22:33:41 n_hibma Exp $	*/

/*
 * Copyright (c) 1998 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Lennart Augustsson (lennart@augustsson.net) at
 * Carlstedt Research & Technology.
 *
 * 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.
 */

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

#include <machine/bus.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/uhcireg.h>
#include <dev/usb/uhcivar.h>

/* Use bandwidth reclamation for control transfers. Some devices choke on it. */
/*#define UHCI_CTL_LOOP */

struct cfdriver uhci_cd = {
	NULL, "uhci", DV_DULL
};

#ifdef UHCI_DEBUG
struct uhci_softc *thesc;
#define DPRINTF(x)	if (uhcidebug) printf x
#define DPRINTFN(n,x)	if (uhcidebug>(n)) printf x
int uhcidebug = 0;
int uhcinoloop = 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 *uhcixfer;

struct uhci_pipe {
	struct usbd_pipe pipe;
	int nexttoggle;

	union {
		/* Control pipe */
		struct {
			struct uhci_soft_qh *sqh;
			struct usb_dma reqdma;
			struct uhci_soft_td *setup, *stat;
			u_int length;
		} ctl;
		/* Interrupt pipe */
		struct {
			int npoll;
			int isread;
			struct uhci_soft_qh **qhs;
		} intr;
		/* Bulk pipe */
		struct {
			struct uhci_soft_qh *sqh;
			u_int length;
			int isread;
		} bulk;
		/* Iso pipe */
		struct iso {
			struct uhci_soft_td **stds;
			int next, inuse;
		} iso;
	} u;
};

void		uhci_globalreset(struct uhci_softc *);
usbd_status	uhci_portreset(struct uhci_softc *, int);
void		uhci_reset(struct uhci_softc *);
usbd_status	uhci_run(struct uhci_softc *, int run);
struct uhci_soft_td *uhci_alloc_std(struct uhci_softc *);
void		uhci_free_std(struct uhci_softc *, struct uhci_soft_td *);
struct uhci_soft_qh *uhci_alloc_sqh(struct uhci_softc *);
void		uhci_free_sqh(struct uhci_softc *, struct uhci_soft_qh *);

void		uhci_free_std_chain(struct uhci_softc *,
		    struct uhci_soft_td *, struct uhci_soft_td *);
usbd_status	uhci_alloc_std_chain(struct uhci_softc *, u_int,
		    struct usbd_xfer *, struct uhci_soft_td **,
		    struct uhci_soft_td **);
void		uhci_poll_hub(void *);
void		uhci_waitintr(struct uhci_softc *, struct usbd_xfer *);
void		uhci_check_intr(struct uhci_softc *, struct usbd_xfer *);
void		uhci_idone(struct usbd_xfer *);

void		uhci_abort_xfer(struct usbd_xfer *, usbd_status status);

void		uhci_timeout(void *);
void		uhci_timeout_task(void *);
void		uhci_add_ls_ctrl(struct uhci_softc *, struct uhci_soft_qh *);
void		uhci_add_hs_ctrl(struct uhci_softc *, struct uhci_soft_qh *);
void		uhci_add_bulk(struct uhci_softc *, struct uhci_soft_qh *);
void		uhci_remove_ls_ctrl(struct uhci_softc *, struct uhci_soft_qh *);
void		uhci_remove_hs_ctrl(struct uhci_softc *, struct uhci_soft_qh *);
void		uhci_remove_bulk(struct uhci_softc *,struct uhci_soft_qh *);
void		uhci_add_loop(struct uhci_softc *sc);
void		uhci_rem_loop(struct uhci_softc *sc);

usbd_status	uhci_setup_isoc(struct usbd_pipe *pipe);
void		uhci_device_isoc_enter(struct usbd_xfer *);

struct usbd_xfer *uhci_allocx(struct usbd_bus *);
void		uhci_freex(struct usbd_bus *, struct usbd_xfer *);

usbd_status	uhci_device_ctrl_transfer(struct usbd_xfer *);
usbd_status	uhci_device_ctrl_start(struct usbd_xfer *);
void		uhci_device_ctrl_abort(struct usbd_xfer *);
void		uhci_device_ctrl_close(struct usbd_pipe *);
void		uhci_device_ctrl_done(struct usbd_xfer *);

usbd_status	uhci_device_intr_transfer(struct usbd_xfer *);
usbd_status	uhci_device_intr_start(struct usbd_xfer *);
void		uhci_device_intr_abort(struct usbd_xfer *);
void		uhci_device_intr_close(struct usbd_pipe *);
void		uhci_device_intr_done(struct usbd_xfer *);

usbd_status	uhci_device_bulk_transfer(struct usbd_xfer *);
usbd_status	uhci_device_bulk_start(struct usbd_xfer *);
void		uhci_device_bulk_abort(struct usbd_xfer *);
void		uhci_device_bulk_close(struct usbd_pipe *);
void		uhci_device_bulk_done(struct usbd_xfer *);

usbd_status	uhci_device_isoc_transfer(struct usbd_xfer *);
usbd_status	uhci_device_isoc_start(struct usbd_xfer *);
void		uhci_device_isoc_abort(struct usbd_xfer *);
void		uhci_device_isoc_close(struct usbd_pipe *);
void		uhci_device_isoc_done(struct usbd_xfer *);

usbd_status	uhci_root_ctrl_transfer(struct usbd_xfer *);
usbd_status	uhci_root_ctrl_start(struct usbd_xfer *);
void		uhci_root_ctrl_abort(struct usbd_xfer *);
void		uhci_root_ctrl_close(struct usbd_pipe *);
void		uhci_root_ctrl_done(struct usbd_xfer *);

usbd_status	uhci_root_intr_transfer(struct usbd_xfer *);
usbd_status	uhci_root_intr_start(struct usbd_xfer *);
void		uhci_root_intr_abort(struct usbd_xfer *);
void		uhci_root_intr_close(struct usbd_pipe *);
void		uhci_root_intr_done(struct usbd_xfer *);

usbd_status	uhci_open(struct usbd_pipe *);
void		uhci_poll(struct usbd_bus *);
void		uhci_softintr(void *);

usbd_status	uhci_device_request(struct usbd_xfer *xfer);

void		uhci_add_intr(struct uhci_softc *, struct uhci_soft_qh *);
void		uhci_remove_intr(struct uhci_softc *, struct uhci_soft_qh *);
usbd_status	uhci_device_setintr(struct uhci_softc *sc,
		    struct uhci_pipe *pipe, int ival);

void		uhci_device_clear_toggle(struct usbd_pipe *pipe);

__inline__ struct uhci_soft_qh *uhci_find_prev_qh(struct uhci_soft_qh *,
		    struct uhci_soft_qh *);

#ifdef UHCI_DEBUG
void		uhci_dump_all(struct uhci_softc *);
void		uhci_dumpregs(struct uhci_softc *);
void		uhci_dump_qhs(struct uhci_soft_qh *);
void		uhci_dump_qh(struct uhci_soft_qh *);
void		uhci_dump_tds(struct uhci_soft_td *);
void		uhci_dump_td(struct uhci_soft_td *);
void		uhci_dump_xfer(struct uhci_xfer *);
void		uhci_dump(void);
#endif

#define UBARR(sc) bus_space_barrier((sc)->iot, (sc)->ioh, 0, (sc)->sc_size, \
			BUS_SPACE_BARRIER_READ|BUS_SPACE_BARRIER_WRITE)
#define UWRITE1(sc, r, x) \
 do { UBARR(sc); bus_space_write_1((sc)->iot, (sc)->ioh, (r), (x)); \
 } while (/*CONSTCOND*/0)
#define UWRITE2(sc, r, x) \
 do { UBARR(sc); bus_space_write_2((sc)->iot, (sc)->ioh, (r), (x)); \
 } while (/*CONSTCOND*/0)
#define UWRITE4(sc, r, x) \
 do { UBARR(sc); bus_space_write_4((sc)->iot, (sc)->ioh, (r), (x)); \
 } while (/*CONSTCOND*/0)

__unused static __inline u_int8_t
UREAD1(struct uhci_softc *sc, bus_size_t r)
{
	UBARR(sc);
	return bus_space_read_1(sc->iot, sc->ioh, r);
}

__unused static __inline u_int16_t
UREAD2(struct uhci_softc *sc, bus_size_t r)
{
	UBARR(sc);
	return bus_space_read_2(sc->iot, sc->ioh, r);
}

__unused static __inline u_int32_t
UREAD4(struct uhci_softc *sc, bus_size_t r)
{
	UBARR(sc);
	return bus_space_read_4(sc->iot, sc->ioh, r);
}

#define UHCICMD(sc, cmd) UWRITE2(sc, UHCI_CMD, cmd)
#define UHCISTS(sc) UREAD2(sc, UHCI_STS)

#define UHCI_RESET_TIMEOUT 100	/* ms, reset timeout */

#define UHCI_CURFRAME(sc) (UREAD2(sc, UHCI_FRNUM) & UHCI_FRNUM_MASK)

#define UHCI_INTR_ENDPT 1

struct usbd_bus_methods uhci_bus_methods = {
	.open_pipe = uhci_open,
	.dev_setaddr = usbd_set_address,
	.soft_intr = uhci_softintr,
	.do_poll = uhci_poll,
	.allocx = uhci_allocx,
	.freex = uhci_freex,
};

struct usbd_pipe_methods uhci_root_ctrl_methods = {
	.transfer = uhci_root_ctrl_transfer,
	.start = uhci_root_ctrl_start,
	.abort = uhci_root_ctrl_abort,
	.close = uhci_root_ctrl_close,
	.done = uhci_root_ctrl_done,
};

struct usbd_pipe_methods uhci_root_intr_methods = {
	.transfer = uhci_root_intr_transfer,
	.start = uhci_root_intr_start,
	.abort = uhci_root_intr_abort,
	.close = uhci_root_intr_close,
	.done = uhci_root_intr_done,
};

struct usbd_pipe_methods uhci_device_ctrl_methods = {
	.transfer = uhci_device_ctrl_transfer,
	.start = uhci_device_ctrl_start,
	.abort = uhci_device_ctrl_abort,
	.close = uhci_device_ctrl_close,
	.done = uhci_device_ctrl_done,
};

struct usbd_pipe_methods uhci_device_intr_methods = {
	.transfer = uhci_device_intr_transfer,
	.start = uhci_device_intr_start,
	.abort = uhci_device_intr_abort,
	.close = uhci_device_intr_close,
	.cleartoggle = uhci_device_clear_toggle,
	.done = uhci_device_intr_done,
};

struct usbd_pipe_methods uhci_device_bulk_methods = {
	.transfer = uhci_device_bulk_transfer,
	.start = uhci_device_bulk_start,
	.abort = uhci_device_bulk_abort,
	.close = uhci_device_bulk_close,
	.cleartoggle = uhci_device_clear_toggle,
	.done = uhci_device_bulk_done,
};

struct usbd_pipe_methods uhci_device_isoc_methods = {
	.transfer = uhci_device_isoc_transfer,
	.start = uhci_device_isoc_start,
	.abort = uhci_device_isoc_abort,
	.close = uhci_device_isoc_close,
	.done = uhci_device_isoc_done,
};

#define uhci_add_intr_list(sc, ex) \
	LIST_INSERT_HEAD(&(sc)->sc_intrhead, (ex), inext)
#define uhci_del_intr_list(ex) \
	do { \
		LIST_REMOVE((ex), inext); \
		(ex)->inext.le_prev = NULL; \
	} while (0)
#define uhci_active_intr_list(ex) ((ex)->inext.le_prev != NULL)

__inline__ struct uhci_soft_qh *
uhci_find_prev_qh(struct uhci_soft_qh *pqh, struct uhci_soft_qh *sqh)
{
	DPRINTFN(15,("uhci_find_prev_qh: pqh=%p sqh=%p\n", pqh, sqh));

	for (; pqh->hlink != sqh; pqh = pqh->hlink) {
#if defined(DIAGNOSTIC) || defined(UHCI_DEBUG)
		if (letoh32(pqh->qh.qh_hlink) & UHCI_PTR_T) {
			printf("uhci_find_prev_qh: QH not found\n");
			return (NULL);
		}
#endif
	}
	return (pqh);
}

void
uhci_globalreset(struct uhci_softc *sc)
{
	UHCICMD(sc, UHCI_CMD_GRESET);	/* global reset */
	usb_delay_ms(&sc->sc_bus, USB_BUS_RESET_DELAY); /* wait a little */
	UHCICMD(sc, 0);			/* do nothing */
}

usbd_status
uhci_init(struct uhci_softc *sc)
{
	usbd_status err;
	int i, j;
	struct uhci_soft_qh *clsqh, *chsqh, *bsqh, *sqh, *lsqh;
	struct uhci_soft_td *std;

	DPRINTFN(1,("uhci_init: start\n"));

#ifdef UHCI_DEBUG
	thesc = sc;

	if (uhcidebug > 2)
		uhci_dumpregs(sc);
#endif

	/* Save SOF over HC reset. */
	sc->sc_saved_sof = UREAD1(sc, UHCI_SOF);

	UWRITE2(sc, UHCI_INTR, 0);		/* disable interrupts */
	uhci_globalreset(sc);			/* reset the controller */
	uhci_reset(sc);

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

	/* Restore saved SOF. */
	UWRITE1(sc, UHCI_SOF, sc->sc_saved_sof);

	/* Allocate and initialize real frame array. */
	err = usb_allocmem(&sc->sc_bus,
		  UHCI_FRAMELIST_COUNT * sizeof(uhci_physaddr_t),
		  UHCI_FRAMELIST_ALIGN, &sc->sc_dma);
	if (err)
		return (err);
	sc->sc_pframes = KERNADDR(&sc->sc_dma, 0);
	UWRITE2(sc, UHCI_FRNUM, 0);		/* set frame number to 0 */
	UWRITE4(sc, UHCI_FLBASEADDR, DMAADDR(&sc->sc_dma, 0)); /* set frame list*/

	/*
	 * Allocate a TD, inactive, that hangs from the last QH.
	 * This is to avoid a bug in the PIIX that makes it run berserk
	 * otherwise.
	 */
	std = uhci_alloc_std(sc);
	if (std == NULL)
		return (USBD_NOMEM);
	std->link.std = NULL;
	std->td.td_link = htole32(UHCI_PTR_T);
	std->td.td_status = htole32(0); /* inactive */
	std->td.td_token = htole32(0);
	std->td.td_buffer = htole32(0);

	/* Allocate the dummy QH marking the end and used for looping the QHs.*/
	lsqh = uhci_alloc_sqh(sc);
	if (lsqh == NULL)
		return (USBD_NOMEM);
	lsqh->hlink = NULL;
	lsqh->qh.qh_hlink = htole32(UHCI_PTR_T);	/* end of QH chain */
	lsqh->elink = std;
	lsqh->qh.qh_elink = htole32(std->physaddr | UHCI_PTR_TD);
	sc->sc_last_qh = lsqh;

	/* Allocate the dummy QH where bulk traffic will be queued. */
	bsqh = uhci_alloc_sqh(sc);
	if (bsqh == NULL)
		return (USBD_NOMEM);
	bsqh->hlink = lsqh;
	bsqh->qh.qh_hlink = htole32(lsqh->physaddr | UHCI_PTR_QH);
	bsqh->elink = NULL;
	bsqh->qh.qh_elink = htole32(UHCI_PTR_T);
	sc->sc_bulk_start = sc->sc_bulk_end = bsqh;

	/* Allocate dummy QH where high speed control traffic will be queued. */
	chsqh = uhci_alloc_sqh(sc);
	if (chsqh == NULL)
		return (USBD_NOMEM);
	chsqh->hlink = bsqh;
	chsqh->qh.qh_hlink = htole32(bsqh->physaddr | UHCI_PTR_QH);
	chsqh->elink = NULL;
	chsqh->qh.qh_elink = htole32(UHCI_PTR_T);
	sc->sc_hctl_start = sc->sc_hctl_end = chsqh;

	/* Allocate dummy QH where control traffic will be queued. */
	clsqh = uhci_alloc_sqh(sc);
	if (clsqh == NULL)
		return (USBD_NOMEM);
	clsqh->hlink = chsqh;
	clsqh->qh.qh_hlink = htole32(chsqh->physaddr | UHCI_PTR_QH);
	clsqh->elink = NULL;
	clsqh->qh.qh_elink = htole32(UHCI_PTR_T);
	sc->sc_lctl_start = sc->sc_lctl_end = clsqh;

	/*
	 * Make all (virtual) frame list pointers point to the interrupt
	 * queue heads and the interrupt queue heads at the control
	 * queue head and point the physical frame list to the virtual.
	 */
	for(i = 0; i < UHCI_VFRAMELIST_COUNT; i++) {
		std = uhci_alloc_std(sc);
		sqh = uhci_alloc_sqh(sc);
		if (std == NULL || sqh == NULL)
			return (USBD_NOMEM);
		std->link.sqh = sqh;
		std->td.td_link = htole32(sqh->physaddr | UHCI_PTR_QH);
		std->td.td_status = htole32(UHCI_TD_IOS); /* iso, inactive */
		std->td.td_token = htole32(0);
		std->td.td_buffer = htole32(0);
		sqh->hlink = clsqh;
		sqh->qh.qh_hlink = htole32(clsqh->physaddr | UHCI_PTR_QH);
		sqh->elink = NULL;
		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
		sc->sc_vframes[i].htd = std;
		sc->sc_vframes[i].etd = std;
		sc->sc_vframes[i].hqh = sqh;
		sc->sc_vframes[i].eqh = sqh;
		for (j = i;
		     j < UHCI_FRAMELIST_COUNT;
		     j += UHCI_VFRAMELIST_COUNT)
			sc->sc_pframes[j] = htole32(std->physaddr);
	}

	LIST_INIT(&sc->sc_intrhead);

	timeout_set(&sc->sc_root_intr, uhci_poll_hub, sc);

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

	sc->sc_suspend = DVACT_RESUME;

	UHCICMD(sc, UHCI_CMD_MAXP); /* Assume 64 byte packets at frame end */

	DPRINTFN(1,("uhci_init: enabling\n"));
	UWRITE2(sc, UHCI_INTR, UHCI_INTR_TOCRCIE | UHCI_INTR_RIE |
		UHCI_INTR_IOCE | UHCI_INTR_SPIE);	/* enable interrupts */

	return (uhci_run(sc, 1));		/* and here we go... */
}

int
uhci_activate(struct device *self, int act)
{
	struct uhci_softc *sc = (struct uhci_softc *)self;
	int cmd, rv = 0;

	switch (act) {
	case DVACT_SUSPEND:
#ifdef UHCI_DEBUG
		if (uhcidebug > 2)
			uhci_dumpregs(sc);
#endif
		rv = config_activate_children(self, act);
		sc->sc_bus.use_polling++;
		uhci_run(sc, 0); /* stop the controller */

		/* save some state if BIOS doesn't */
		sc->sc_saved_frnum = UREAD2(sc, UHCI_FRNUM);

		UWRITE2(sc, UHCI_INTR, 0); /* disable intrs */

		cmd = UREAD2(sc, UHCI_CMD);
		UHCICMD(sc, cmd | UHCI_CMD_EGSM); /* enter global suspend */
		usb_delay_ms(&sc->sc_bus, USB_RESUME_WAIT);
		sc->sc_suspend = act;
		sc->sc_bus.use_polling--;
		DPRINTF(("uhci_activate: cmd=0x%x\n", UREAD2(sc, UHCI_CMD)));
		break;
	case DVACT_POWERDOWN:
		rv = config_activate_children(self, act);
		uhci_run(sc, 0); /* stop the controller */
		break;
	case DVACT_RESUME:
#ifdef DIAGNOSTIC
		if (sc->sc_suspend == DVACT_RESUME)
			printf("uhci_powerhook: weird, resume without suspend.\n");
#endif
		sc->sc_bus.use_polling++;
		sc->sc_suspend = act;
		cmd = UREAD2(sc, UHCI_CMD);
		if (cmd & UHCI_CMD_RS)
			uhci_run(sc, 0); /* in case BIOS has started it */

		/* restore saved state */
		UWRITE4(sc, UHCI_FLBASEADDR, DMAADDR(&sc->sc_dma, 0));
		UWRITE2(sc, UHCI_FRNUM, sc->sc_saved_frnum);
		UWRITE1(sc, UHCI_SOF, sc->sc_saved_sof);

		UHCICMD(sc, cmd | UHCI_CMD_FGR); /* force global resume */
		usb_delay_ms(&sc->sc_bus, USB_RESUME_DELAY);
		UHCICMD(sc, cmd & ~UHCI_CMD_EGSM); /* back to normal */
		UHCICMD(sc, UHCI_CMD_MAXP);
		UWRITE2(sc, UHCI_INTR, UHCI_INTR_TOCRCIE | UHCI_INTR_RIE |
			UHCI_INTR_IOCE | UHCI_INTR_SPIE); /* re-enable intrs */
		uhci_run(sc, 1); /* and start traffic again */
		usb_delay_ms(&sc->sc_bus, USB_RESUME_RECOVERY);
		sc->sc_bus.use_polling--;
#ifdef UHCI_DEBUG
		if (uhcidebug > 2)
			uhci_dumpregs(sc);
#endif
		rv = config_activate_children(self, act);
		break;
	default:
		rv = config_activate_children(self, act);
		break;
	}
	return (rv);
}

int
uhci_detach(struct device *self, int flags)
{
#ifdef DIAGNOSTIC
	struct uhci_softc *sc = (struct uhci_softc *)self;
#endif
	int rv;

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

	KASSERT(sc->sc_intrxfer == NULL);

	/* XXX free other data structures XXX */

	return (rv);
}

struct usbd_xfer *
uhci_allocx(struct usbd_bus *bus)
{
	struct uhci_xfer *ux;

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

void
uhci_freex(struct usbd_bus *bus, struct usbd_xfer *xfer)
{
	struct uhci_xfer *ux = (struct uhci_xfer*)xfer;

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

#ifdef UHCI_DEBUG
void
uhci_dumpregs(struct uhci_softc *sc)
{
	DPRINTFN(-1,("%s regs: cmd=%04x, sts=%04x, intr=%04x, frnum=%04x, "
		     "flbase=%08x, sof=%04x, portsc1=%04x, portsc2=%04x\n",
		     sc->sc_bus.bdev.dv_xname,
		     UREAD2(sc, UHCI_CMD),
		     UREAD2(sc, UHCI_STS),
		     UREAD2(sc, UHCI_INTR),
		     UREAD2(sc, UHCI_FRNUM),
		     UREAD4(sc, UHCI_FLBASEADDR),
		     UREAD1(sc, UHCI_SOF),
		     UREAD2(sc, UHCI_PORTSC1),
		     UREAD2(sc, UHCI_PORTSC2)));
}

void
uhci_dump_td(struct uhci_soft_td *p)
{
	char sbuf[128], sbuf2[128];

	DPRINTFN(-1,("TD(%p) at %08lx = link=0x%08lx status=0x%08lx "
		     "token=0x%08lx buffer=0x%08lx\n",
		     p, (long)p->physaddr,
		     (long)letoh32(p->td.td_link),
		     (long)letoh32(p->td.td_status),
		     (long)letoh32(p->td.td_token),
		     (long)letoh32(p->td.td_buffer)));

	bitmask_snprintf((u_int32_t)letoh32(p->td.td_link), "\20\1T\2Q\3VF",
			 sbuf, sizeof(sbuf));
	bitmask_snprintf((u_int32_t)letoh32(p->td.td_status),
			 "\20\22BITSTUFF\23CRCTO\24NAK\25BABBLE\26DBUFFER\27"
			 "STALLED\30ACTIVE\31IOC\32ISO\33LS\36SPD",
			 sbuf2, sizeof(sbuf2));

	DPRINTFN(-1,("  %s %s,errcnt=%d,actlen=%d pid=%02x,addr=%d,endpt=%d,"
		     "D=%d,maxlen=%d\n", sbuf, sbuf2,
		     UHCI_TD_GET_ERRCNT(letoh32(p->td.td_status)),
		     UHCI_TD_GET_ACTLEN(letoh32(p->td.td_status)),
		     UHCI_TD_GET_PID(letoh32(p->td.td_token)),
		     UHCI_TD_GET_DEVADDR(letoh32(p->td.td_token)),
		     UHCI_TD_GET_ENDPT(letoh32(p->td.td_token)),
		     UHCI_TD_GET_DT(letoh32(p->td.td_token)),
		     UHCI_TD_GET_MAXLEN(letoh32(p->td.td_token))));
}

void
uhci_dump_qh(struct uhci_soft_qh *sqh)
{
	DPRINTFN(-1,("QH(%p) at %08x: hlink=%08x elink=%08x\n", sqh,
	    (int)sqh->physaddr, letoh32(sqh->qh.qh_hlink),
	    letoh32(sqh->qh.qh_elink)));
}


void
uhci_dump(void)
{
	uhci_dump_all(thesc);
}

void
uhci_dump_all(struct uhci_softc *sc)
{
	uhci_dumpregs(sc);
	printf("intrs=%d\n", sc->sc_bus.no_intrs);
	/*printf("framelist[i].link = %08x\n", sc->sc_framelist[0].link);*/
	uhci_dump_qh(sc->sc_lctl_start);
}


void
uhci_dump_qhs(struct uhci_soft_qh *sqh)
{
	uhci_dump_qh(sqh);

	/* uhci_dump_qhs displays all the QHs and TDs from the given QH onwards
	 * Traverses sideways first, then down.
	 *
	 * QH1
	 * QH2
	 * No QH
	 * TD2.1
	 * TD2.2
	 * TD1.1
	 * etc.
	 *
	 * TD2.x being the TDs queued at QH2 and QH1 being referenced from QH1.
	 */


	if (sqh->hlink != NULL && !(letoh32(sqh->qh.qh_hlink) & UHCI_PTR_T))
		uhci_dump_qhs(sqh->hlink);
	else
		DPRINTF(("No QH\n"));

	if (sqh->elink != NULL && !(letoh32(sqh->qh.qh_elink) & UHCI_PTR_T))
		uhci_dump_tds(sqh->elink);
	else
		DPRINTF(("No TD\n"));
}

void
uhci_dump_tds(struct uhci_soft_td *std)
{
	struct uhci_soft_td *td;

	for(td = std; td != NULL; td = td->link.std) {
		uhci_dump_td(td);

		/* Check whether the link pointer in this TD marks
		 * the link pointer as end of queue. This avoids
		 * printing the free list in case the queue/TD has
		 * already been moved there (seatbelt).
		 */
		if (letoh32(td->td.td_link) & UHCI_PTR_T ||
		    letoh32(td->td.td_link) == 0)
			break;
	}
}

void
uhci_dump_xfer(struct uhci_xfer *ex)
{
	struct usbd_pipe *pipe;
	usb_endpoint_descriptor_t *ed;
	struct usbd_device *dev;

#ifdef DIAGNOSTIC
#define DONE ex->isdone
#else
#define DONE 0
#endif
        if (ex == NULL) {
                printf("ex NULL\n");
                return;
        }
        pipe = ex->xfer.pipe;
        if (pipe == NULL) {
		printf("ex %p: done=%d pipe=NULL\n",
		       ex, DONE);
                return;
	}
        if (pipe->endpoint == NULL) {
		printf("ex %p: done=%d pipe=%p pipe->endpoint=NULL\n",
		       ex, DONE, pipe);
                return;
	}
        if (pipe->device == NULL) {
		printf("ex %p: done=%d pipe=%p pipe->device=NULL\n",
		       ex, DONE, pipe);
                return;
	}
        ed = pipe->endpoint->edesc;
        dev = pipe->device;
	printf("ex %p: done=%d dev=%p vid=0x%04x pid=0x%04x addr=%d pipe=%p ep=0x%02x attr=0x%02x\n",
	       ex, DONE, dev,
	       UGETW(dev->ddesc.idVendor),
	       UGETW(dev->ddesc.idProduct),
	       dev->address, pipe,
	       ed->bEndpointAddress, ed->bmAttributes);
#undef DONE
}

void uhci_dump_xfers(struct uhci_softc *sc);
void
uhci_dump_xfers(struct uhci_softc *sc)
{
	struct uhci_xfer *ex;

	printf("ex list:\n");
	for (ex = LIST_FIRST(&sc->sc_intrhead); ex; ex = LIST_NEXT(ex, inext))
		uhci_dump_xfer(ex);
}

void exdump(void);
void exdump(void) { uhci_dump_xfers(thesc); }

#endif

/*
 * This routine is executed periodically and simulates interrupts
 * from the root controller interrupt pipe for port status change.
 */
void
uhci_poll_hub(void *addr)
{
	struct uhci_softc *sc = addr;
	struct usbd_xfer *xfer;
	int s;
	u_char *p;

	if (sc->sc_bus.dying)
		return;

	xfer = sc->sc_intrxfer;
	if (xfer == NULL)
		return;

	p = KERNADDR(&xfer->dmabuf, 0);
	p[0] = 0;
	if (UREAD2(sc, UHCI_PORTSC1) & (UHCI_PORTSC_CSC|UHCI_PORTSC_OCIC))
		p[0] |= 1<<1;
	if (UREAD2(sc, UHCI_PORTSC2) & (UHCI_PORTSC_CSC|UHCI_PORTSC_OCIC))
		p[0] |= 1<<2;
	if (p[0] == 0) {
		/* No change, try again in a while */
		timeout_add_msec(&sc->sc_root_intr, 255);
		return;
	}

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

	s = splusb();
	xfer->device->bus->intr_context++;
	usb_transfer_complete(xfer);
	xfer->device->bus->intr_context--;
	splx(s);
}

void
uhci_root_ctrl_done(struct usbd_xfer *xfer)
{
}

/*
 * Let the last QH loop back to the high speed control transfer QH.
 * This is what intel calls "bandwidth reclamation" and improves
 * USB performance a lot for some devices.
 * If we are already looping, just count it.
 */
void
uhci_add_loop(struct uhci_softc *sc) {
#ifdef UHCI_DEBUG
	if (uhcinoloop)
		return;
#endif
	if (++sc->sc_loops == 1) {
		DPRINTFN(5,("uhci_add_loop\n"));
		/* Note, we don't loop back the soft pointer. */
		sc->sc_last_qh->qh.qh_hlink =
		    htole32(sc->sc_hctl_start->physaddr | UHCI_PTR_QH);
	}
}

void
uhci_rem_loop(struct uhci_softc *sc) {
#ifdef UHCI_DEBUG
	if (uhcinoloop)
		return;
#endif
	if (--sc->sc_loops == 0) {
		DPRINTFN(5,("uhci_rem_loop\n"));
		sc->sc_last_qh->qh.qh_hlink = htole32(UHCI_PTR_T);
	}
}

/* Add high speed control QH, called at splusb(). */
void
uhci_add_hs_ctrl(struct uhci_softc *sc, struct uhci_soft_qh *sqh)
{
	struct uhci_soft_qh *eqh;

	SPLUSBCHECK;

	DPRINTFN(10, ("uhci_add_hs_ctrl: sqh=%p\n", sqh));
	eqh = sc->sc_hctl_end;
	sqh->hlink       = eqh->hlink;
	sqh->qh.qh_hlink = eqh->qh.qh_hlink;
	eqh->hlink       = sqh;
	eqh->qh.qh_hlink = htole32(sqh->physaddr | UHCI_PTR_QH);
	sc->sc_hctl_end = sqh;
#ifdef UHCI_CTL_LOOP
	uhci_add_loop(sc);
#endif
}

/* Remove high speed control QH, called at splusb(). */
void
uhci_remove_hs_ctrl(struct uhci_softc *sc, struct uhci_soft_qh *sqh)
{
	struct uhci_soft_qh *pqh;

	SPLUSBCHECK;

	DPRINTFN(10, ("uhci_remove_hs_ctrl: sqh=%p\n", sqh));
#ifdef UHCI_CTL_LOOP
	uhci_rem_loop(sc);
#endif
	/*
	 * The T bit should be set in the elink of the QH so that the HC
	 * doesn't follow the pointer.  This condition may fail if the
	 * the transferred packet was short so that the QH still points
	 * at the last used TD.
	 * In this case we set the T bit and wait a little for the HC
	 * to stop looking at the TD.
	 */
	if (!(sqh->qh.qh_elink & htole32(UHCI_PTR_T))) {
		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
		delay(UHCI_QH_REMOVE_DELAY);
	}

	pqh = uhci_find_prev_qh(sc->sc_hctl_start, sqh);
	pqh->hlink = sqh->hlink;
	pqh->qh.qh_hlink = sqh->qh.qh_hlink;
	delay(UHCI_QH_REMOVE_DELAY);
	if (sc->sc_hctl_end == sqh)
		sc->sc_hctl_end = pqh;
}

/* Add low speed control QH, called at splusb(). */
void
uhci_add_ls_ctrl(struct uhci_softc *sc, struct uhci_soft_qh *sqh)
{
	struct uhci_soft_qh *eqh;

	SPLUSBCHECK;

	DPRINTFN(10, ("uhci_add_ls_ctrl: sqh=%p\n", sqh));
	eqh = sc->sc_lctl_end;
	sqh->hlink = eqh->hlink;
	sqh->qh.qh_hlink = eqh->qh.qh_hlink;
	eqh->hlink = sqh;
	eqh->qh.qh_hlink = htole32(sqh->physaddr | UHCI_PTR_QH);
	sc->sc_lctl_end = sqh;
}

/* Remove low speed control QH, called at splusb(). */
void
uhci_remove_ls_ctrl(struct uhci_softc *sc, struct uhci_soft_qh *sqh)
{
	struct uhci_soft_qh *pqh;

	SPLUSBCHECK;

	DPRINTFN(10, ("uhci_remove_ls_ctrl: sqh=%p\n", sqh));
	/* See comment in uhci_remove_hs_ctrl() */
	if (!(sqh->qh.qh_elink & htole32(UHCI_PTR_T))) {
		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
		delay(UHCI_QH_REMOVE_DELAY);
	}
	pqh = uhci_find_prev_qh(sc->sc_lctl_start, sqh);
	pqh->hlink = sqh->hlink;
	pqh->qh.qh_hlink = sqh->qh.qh_hlink;
	delay(UHCI_QH_REMOVE_DELAY);
	if (sc->sc_lctl_end == sqh)
		sc->sc_lctl_end = pqh;
}

/* Add bulk QH, called at splusb(). */
void
uhci_add_bulk(struct uhci_softc *sc, struct uhci_soft_qh *sqh)
{
	struct uhci_soft_qh *eqh;

	SPLUSBCHECK;

	DPRINTFN(10, ("uhci_add_bulk: sqh=%p\n", sqh));
	eqh = sc->sc_bulk_end;
	sqh->hlink = eqh->hlink;
	sqh->qh.qh_hlink = eqh->qh.qh_hlink;
	eqh->hlink = sqh;
	eqh->qh.qh_hlink = htole32(sqh->physaddr | UHCI_PTR_QH);
	sc->sc_bulk_end = sqh;
	uhci_add_loop(sc);
}

/* Remove bulk QH, called at splusb(). */
void
uhci_remove_bulk(struct uhci_softc *sc, struct uhci_soft_qh *sqh)
{
	struct uhci_soft_qh *pqh;

	SPLUSBCHECK;

	DPRINTFN(10, ("uhci_remove_bulk: sqh=%p\n", sqh));
	uhci_rem_loop(sc);
	/* See comment in uhci_remove_hs_ctrl() */
	if (!(sqh->qh.qh_elink & htole32(UHCI_PTR_T))) {
		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
		delay(UHCI_QH_REMOVE_DELAY);
	}
	pqh = uhci_find_prev_qh(sc->sc_bulk_start, sqh);
	pqh->hlink       = sqh->hlink;
	pqh->qh.qh_hlink = sqh->qh.qh_hlink;
	delay(UHCI_QH_REMOVE_DELAY);
	if (sc->sc_bulk_end == sqh)
		sc->sc_bulk_end = pqh;
}

int uhci_intr1(struct uhci_softc *);

int
uhci_intr(void *arg)
{
	struct uhci_softc *sc = arg;

	if (sc->sc_bus.dying)
		return (0);
	if (sc->sc_bus.use_polling)
		return (0);
	return (uhci_intr1(sc));
}

int
uhci_intr1(struct uhci_softc *sc)
{
	int status;
	int ack;

	status = UREAD2(sc, UHCI_STS);
	if (status == 0xffff) {
		sc->sc_bus.dying = 1;
		return (0);
	}
	status &= UHCI_STS_ALLINTRS;
	if (status == 0)	/* The interrupt was not for us. */
		return (0);

#ifdef UHCI_DEBUG
	if (uhcidebug > 15) {
		DPRINTF(("%s: uhci_intr1\n", sc->sc_bus.bdev.dv_xname));
		uhci_dumpregs(sc);
	}
#endif

	if (sc->sc_suspend != DVACT_RESUME) {
		printf("%s: interrupt while not operating ignored\n",
		       sc->sc_bus.bdev.dv_xname);
		return (0);
	}

	ack = 0;
	if (status & UHCI_STS_USBINT)
		ack |= UHCI_STS_USBINT;
	if (status & UHCI_STS_USBEI)
		ack |= UHCI_STS_USBEI;
	if (status & UHCI_STS_RD) {
		ack |= UHCI_STS_RD;
#ifdef UHCI_DEBUG
		printf("%s: resume detect\n", sc->sc_bus.bdev.dv_xname);
#endif
	}
	if (status & UHCI_STS_HSE) {
		ack |= UHCI_STS_HSE;
		printf("%s: host system error\n", sc->sc_bus.bdev.dv_xname);
	}
	if (status & UHCI_STS_HCPE) {
		ack |= UHCI_STS_HCPE;
		printf("%s: host controller process error\n",
		       sc->sc_bus.bdev.dv_xname);
	}
	if (status & UHCI_STS_HCH) {
		/* no acknowledge needed */
		if (!sc->sc_bus.dying) {
			printf("%s: host controller halted\n",
			    sc->sc_bus.bdev.dv_xname);
#ifdef UHCI_DEBUG
			uhci_dump_all(sc);
#endif
		}
		sc->sc_bus.dying = 1;
	}

	if (!ack)
		return (0);	/* nothing to acknowledge */
	UWRITE2(sc, UHCI_STS, ack); /* acknowledge the ints */

	sc->sc_bus.no_intrs++;
	usb_schedsoftintr(&sc->sc_bus);

	DPRINTFN(15, ("%s: uhci_intr1: exit\n", sc->sc_bus.bdev.dv_xname));

	return (1);
}

void
uhci_softintr(void *v)
{
	struct uhci_softc *sc = v;
	struct uhci_xfer *ux, *nextex;

	DPRINTFN(10,("%s: uhci_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++;

	/*
	 * Interrupts on UHCI really suck.  When the host controller
	 * interrupts because a transfer is completed there is no
	 * way of knowing which transfer it was.  You can scan down
	 * the TDs and QHs of the previous frame to limit the search,
	 * but that assumes that the interrupt was not delayed by more
	 * than 1 ms, which may not always be true (e.g. after debug
	 * output on a slow console).
	 * We scan all interrupt descriptors to see if any have
	 * completed.
	 */
	for (ux = LIST_FIRST(&sc->sc_intrhead); ux; ux = nextex) {
		nextex = LIST_NEXT(ux, inext);
		uhci_check_intr(sc, &ux->xfer);
	}

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

	sc->sc_bus.intr_context--;
}

void
uhci_check_intr(struct uhci_softc *sc, struct usbd_xfer *xfer)
{
	struct uhci_xfer *ux = (struct uhci_xfer *)xfer;
	struct uhci_soft_td *std, *lstd;
	u_int32_t status;

	DPRINTFN(15, ("%s: ux=%p\n", __func__, ux));
#ifdef DIAGNOSTIC
	if (ux == NULL) {
		printf("%s: no ux? %p\n", __func__, ux);
		return;
	}
#endif
	if (xfer->status == USBD_CANCELLED || xfer->status == USBD_TIMEOUT) {
		DPRINTF(("%s: aborted xfer=%p\n", __func__, xfer));
		return;
	}

	if (ux->stdstart == NULL)
		return;
	lstd = ux->stdend;
#ifdef DIAGNOSTIC
	if (lstd == NULL) {
		printf("%s: std==0\n", __func__);
		return;
	}
#endif
	/*
	 * If the last TD is still active we need to check whether there
	 * is an error somewhere in the middle, or whether there was a
	 * short packet (SPD and not ACTIVE).
	 */
	if (letoh32(lstd->td.td_status) & UHCI_TD_ACTIVE) {
		DPRINTFN(12, ("%s: active ux=%p\n", __func__, ux));
		for (std = ux->stdstart; std != lstd; std = std->link.std) {
			status = letoh32(std->td.td_status);
			/* If there's an active TD the xfer isn't done. */
			if (status & UHCI_TD_ACTIVE)
				break;
			/* Any kind of error makes the xfer done. */
			if (status & UHCI_TD_STALLED)
				goto done;
			/* We want short packets, and it is short: it's done */
			if ((status & UHCI_TD_SPD) &&
			      UHCI_TD_GET_ACTLEN(status) <
			      UHCI_TD_GET_MAXLEN(letoh32(std->td.td_token)))
				goto done;
		}
		DPRINTFN(12, ("%s: ux=%p std=%p still active\n", __func__,
			      ux, ux->stdstart));
		return;
	}
 done:
	DPRINTFN(12, ("uhci_check_intr: ux=%p done\n", ux));
	timeout_del(&xfer->timeout_handle);
	usb_rem_task(xfer->pipe->device, &xfer->abort_task);
	uhci_idone(xfer);
}

/* Called at splusb() */
void
uhci_idone(struct usbd_xfer *xfer)
{
	struct uhci_xfer *ux = (struct uhci_xfer *)xfer;
	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
	struct uhci_soft_td *std;
	u_int32_t status = 0, nstatus;
	int actlen;

	DPRINTFN(12, ("uhci_idone: ux=%p\n", ux));
#ifdef DIAGNOSTIC
	{
		int s = splhigh();
		if (ux->isdone) {
			splx(s);
#ifdef UHCI_DEBUG
			printf("uhci_idone: ux is done!\n   ");
			uhci_dump_xfer(ux);
#else
			printf("uhci_idone: ux=%p is done!\n", ux);
#endif
			return;
		}
		ux->isdone = 1;
		splx(s);
	}
#endif

	if (xfer->nframes != 0) {
		/* Isoc transfer, do things differently. */
		struct uhci_soft_td **stds = upipe->u.iso.stds;
		int i, n, nframes, len;

		DPRINTFN(5,("uhci_idone: ux=%p isoc ready\n", ux));

		nframes = xfer->nframes;
		actlen = 0;
		n = ux->curframe;
		for (i = 0; i < nframes; i++) {
			std = stds[n];
#ifdef UHCI_DEBUG
			if (uhcidebug > 5) {
				DPRINTFN(-1,("uhci_idone: isoc TD %d\n", i));
				uhci_dump_td(std);
			}
#endif
			if (++n >= UHCI_VFRAMELIST_COUNT)
				n = 0;
			status = letoh32(std->td.td_status);
			len = UHCI_TD_GET_ACTLEN(status);
			xfer->frlengths[i] = len;
			actlen += len;
		}
		upipe->u.iso.inuse -= nframes;
		xfer->actlen = actlen;
		xfer->status = USBD_NORMAL_COMPLETION;
		goto end;
	}

#ifdef UHCI_DEBUG
	DPRINTFN(10, ("uhci_idone: ux=%p, xfer=%p, pipe=%p ready\n",
		      ux, xfer, upipe));
	if (uhcidebug > 10)
		uhci_dump_tds(ux->stdstart);
#endif

	/* The transfer is done, compute actual length and status. */
	actlen = 0;
	for (std = ux->stdstart; std != NULL; std = std->link.std) {
		nstatus = letoh32(std->td.td_status);
		if (nstatus & UHCI_TD_ACTIVE)
			break;

		status = nstatus;
		if (UHCI_TD_GET_PID(letoh32(std->td.td_token)) !=
		    UHCI_TD_PID_SETUP)
			actlen += UHCI_TD_GET_ACTLEN(status);
		else {
			/*
			 * UHCI will report CRCTO in addition to a STALL or NAK
			 * for a SETUP transaction.  See section 3.2.2, "TD
			 * CONTROL AND STATUS".
			 */
			if (status & (UHCI_TD_STALLED | UHCI_TD_NAK))
				status &= ~UHCI_TD_CRCTO;
		}
	}
	/* If there are left over TDs we need to update the toggle. */
	if (std != NULL)
		upipe->nexttoggle = UHCI_TD_GET_DT(letoh32(std->td.td_token));

	status &= UHCI_TD_ERROR;
	DPRINTFN(10, ("uhci_idone: actlen=%d, status=0x%x\n",
		      actlen, status));
	xfer->actlen = actlen;
	if (status != 0) {
#ifdef UHCI_DEBUG
		char sbuf[128];

		bitmask_snprintf((u_int32_t)status,
				 "\20\22BITSTUFF\23CRCTO\24NAK\25"
				 "BABBLE\26DBUFFER\27STALLED\30ACTIVE",
				 sbuf, sizeof(sbuf));

		DPRINTFN((status == UHCI_TD_STALLED)*10,
			 ("uhci_idone: error, addr=%d, endpt=0x%02x, "
			  "status 0x%s\n",
			  xfer->device->address,
			  xfer->pipe->endpoint->edesc->bEndpointAddress,
			  sbuf));
#endif

		if (status == UHCI_TD_STALLED)
			xfer->status = USBD_STALLED;
		else
			xfer->status = USBD_IOERROR; /* more info XXX */
	} else {
		xfer->status = USBD_NORMAL_COMPLETION;
	}

 end:
	usb_transfer_complete(xfer);
	DPRINTFN(12, ("uhci_idone: ux=%p done\n", ux));
}

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

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

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

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

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

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

/*
 * Wait here until controller claims to have an interrupt.
 * Then call uhci_intr and return.  Use timeout to avoid waiting
 * too long.
 * Only used during boot when interrupts are not enabled yet.
 */
void
uhci_waitintr(struct uhci_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 = UREAD2(sc, UHCI_STS) & UHCI_STS_ALLINTRS;
		DPRINTFN(15,("uhci_waitintr: 0x%04x\n", intrs));
		if (intrs) {
			uhci_intr1(sc);
			if (xfer->status != USBD_IN_PROGRESS)
				return;
		}
	}

	/* Timeout */
	DPRINTF(("uhci_waitintr: timeout\n"));
	xfer->status = USBD_TIMEOUT;
	usb_transfer_complete(xfer);
}

void
uhci_poll(struct usbd_bus *bus)
{
	struct uhci_softc *sc = (struct uhci_softc *)bus;

	if (UREAD2(sc, UHCI_STS) & UHCI_STS_ALLINTRS)
		uhci_intr1(sc);
}

void
uhci_reset(struct uhci_softc *sc)
{
	int n;

	UHCICMD(sc, UHCI_CMD_HCRESET);
	/* The reset bit goes low when the controller is done. */
	for (n = 0; n < UHCI_RESET_TIMEOUT &&
		    (UREAD2(sc, UHCI_CMD) & UHCI_CMD_HCRESET); n++)
		usb_delay_ms(&sc->sc_bus, 1);
	if (n >= UHCI_RESET_TIMEOUT)
		printf("%s: controller did not reset\n",
		       sc->sc_bus.bdev.dv_xname);
}

usbd_status
uhci_run(struct uhci_softc *sc, int run)
{
	int s, n, running;
	u_int16_t cmd;

	run = run != 0;
	s = splhardusb();
	DPRINTF(("uhci_run: setting run=%d\n", run));
	cmd = UREAD2(sc, UHCI_CMD);
	if (run)
		cmd |= UHCI_CMD_RS;
	else
		cmd &= ~UHCI_CMD_RS;
	UHCICMD(sc, cmd);
	for(n = 0; n < 10; n++) {
		running = !(UREAD2(sc, UHCI_STS) & UHCI_STS_HCH);
		/* return when we've entered the state we want */
		if (run == running) {
			splx(s);
			DPRINTF(("uhci_run: done cmd=0x%x sts=0x%x\n",
				 UREAD2(sc, UHCI_CMD), UREAD2(sc, UHCI_STS)));
			return (USBD_NORMAL_COMPLETION);
		}
		usb_delay_ms(&sc->sc_bus, 1);
	}
	splx(s);
	printf("%s: cannot %s\n", sc->sc_bus.bdev.dv_xname,
	       run ? "start" : "stop");
	return (USBD_IOERROR);
}

/*
 * Memory management routines.
 *  uhci_alloc_std allocates TDs
 *  uhci_alloc_sqh allocates QHs
 * These two routines do their own free list management,
 * partly for speed, partly because allocating DMAable memory
 * has page size granularaity so much memory would be wasted if
 * only one TD/QH (32 bytes) was placed in each allocated chunk.
 */

struct uhci_soft_td *
uhci_alloc_std(struct uhci_softc *sc)
{
	struct uhci_soft_td *std = NULL;
	usbd_status err;
	int i, offs;
	struct usb_dma dma;
	int s;

	s = splusb();
	if (sc->sc_freetds == NULL) {
		DPRINTFN(2,("uhci_alloc_std: allocating chunk\n"));
		err = usb_allocmem(&sc->sc_bus, UHCI_STD_SIZE * UHCI_STD_CHUNK,
			  UHCI_TD_ALIGN, &dma);
		if (err)
			goto out;
		for(i = 0; i < UHCI_STD_CHUNK; i++) {
			offs = i * UHCI_STD_SIZE;
			std = KERNADDR(&dma, offs);
			std->physaddr = DMAADDR(&dma, offs);
			std->link.std = sc->sc_freetds;
			sc->sc_freetds = std;
		}
	}

	std = sc->sc_freetds;
	sc->sc_freetds = std->link.std;
	memset(&std->td, 0, sizeof(struct uhci_td));

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

void
uhci_free_std(struct uhci_softc *sc, struct uhci_soft_td *std)
{
	int s;

#ifdef DIAGNOSTIC
#define TD_IS_FREE 0x12345678
	if (letoh32(std->td.td_token) == TD_IS_FREE) {
		printf("uhci_free_std: freeing free TD %p\n", std);
		return;
	}
	std->td.td_token = htole32(TD_IS_FREE);
#endif

	s = splusb();
	std->link.std = sc->sc_freetds;
	sc->sc_freetds = std;
	splx(s);
}

struct uhci_soft_qh *
uhci_alloc_sqh(struct uhci_softc *sc)
{
	struct uhci_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, ("uhci_alloc_sqh: allocating chunk\n"));
		err = usb_allocmem(&sc->sc_bus, UHCI_SQH_SIZE * UHCI_SQH_CHUNK,
			  UHCI_QH_ALIGN, &dma);
		if (err)
			goto out;
		for (i = 0; i < UHCI_SQH_CHUNK; i++) {
			offs = i * UHCI_SQH_SIZE;
			sqh = KERNADDR(&dma, offs);
			sqh->physaddr = DMAADDR(&dma, offs);
			sqh->hlink = sc->sc_freeqhs;
			sc->sc_freeqhs = sqh;
		}
	}
	sqh = sc->sc_freeqhs;
	sc->sc_freeqhs = sqh->hlink;
	memset(&sqh->qh, 0, sizeof(struct uhci_qh));

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

void
uhci_free_sqh(struct uhci_softc *sc, struct uhci_soft_qh *sqh)
{
	sqh->hlink = sc->sc_freeqhs;
	sc->sc_freeqhs = sqh;
}

void
uhci_free_std_chain(struct uhci_softc *sc, struct uhci_soft_td *std,
    struct uhci_soft_td *stdend)
{
	struct uhci_soft_td *p;

	for (; std != stdend; std = p) {
		p = std->link.std;
		uhci_free_std(sc, std);
	}
}

usbd_status
uhci_alloc_std_chain(struct uhci_softc *sc, u_int len, struct usbd_xfer *xfer,
    struct uhci_soft_td **sp, struct uhci_soft_td **ep)
{
	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
	struct uhci_soft_td *p, *lastp;
	uhci_physaddr_t lastlink;
	int i, ntd, l, tog, mps;
	u_int32_t status;
	u_int16_t flags = xfer->flags;
	int rd = usbd_xfer_isread(xfer);
	struct usb_dma *dma = &xfer->dmabuf;
	int addr = xfer->device->address;
	int endpt = xfer->pipe->endpoint->edesc->bEndpointAddress;

	DPRINTFN(8, ("%s: addr=%d endpt=%d len=%u speed=%d flags=0x%x\n",
	    __func__, addr, UE_GET_ADDR(endpt), len, xfer->device->speed,
	    flags));

	mps = UGETW(xfer->pipe->endpoint->edesc->wMaxPacketSize);
	if (mps == 0) {
		printf("uhci_alloc_std_chain: mps=0\n");
		return (USBD_INVAL);
	}
	ntd = (len + mps - 1) / mps;
	if (len == 0)
		flags |= USBD_FORCE_SHORT_XFER;
	if ((flags & USBD_FORCE_SHORT_XFER) && len % mps == 0)
		ntd++;
	DPRINTFN(10, ("%s: mps=%d ntd=%d\n", __func__, mps, ntd));
	tog = upipe->nexttoggle;
	if (ntd % 2 == 0)
		tog ^= 1;
	upipe->nexttoggle = tog ^ 1;
	lastp = NULL;
	lastlink = UHCI_PTR_T;
	ntd--;
	status = UHCI_TD_ZERO_ACTLEN(UHCI_TD_SET_ERRCNT(3) | UHCI_TD_ACTIVE);
	if (xfer->pipe->device->speed == USB_SPEED_LOW)
		status |= UHCI_TD_LS;
	if (flags & USBD_SHORT_XFER_OK)
		status |= UHCI_TD_SPD;
	for (i = ntd; i >= 0; i--) {
		p = uhci_alloc_std(sc);
		if (p == NULL) {
			uhci_free_std_chain(sc, lastp, NULL);
			return (USBD_NOMEM);
		}
		p->link.std = lastp;
		p->td.td_link = htole32(lastlink | UHCI_PTR_VF | UHCI_PTR_TD);
		lastp = p;
		lastlink = p->physaddr;
		p->td.td_status = htole32(status);
		if (i == ntd) {
			/* last TD */
			l = len % mps;
			if (l == 0 && !(flags & USBD_FORCE_SHORT_XFER))
				l = mps;
			*ep = p;
		} else
			l = mps;
		p->td.td_token =
		    htole32(rd ? UHCI_TD_IN (l, endpt, addr, tog) :
				 UHCI_TD_OUT(l, endpt, addr, tog));
		p->td.td_buffer = htole32(DMAADDR(dma, i * mps));
		tog ^= 1;
	}
	*sp = lastp;
	DPRINTFN(10, ("%s: nexttog=%d\n", __func__, upipe->nexttoggle));
	return (USBD_NORMAL_COMPLETION);
}

void
uhci_device_clear_toggle(struct usbd_pipe *pipe)
{
	struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
	upipe->nexttoggle = 0;
}

usbd_status
uhci_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 (otherwise err would be USBD_INPROG),
	 * so start it first.
	 */
	return (uhci_device_bulk_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
}

usbd_status
uhci_device_bulk_start(struct usbd_xfer *xfer)
{
	struct uhci_softc *sc = (struct uhci_softc *)xfer->device->bus;
	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
	struct uhci_xfer *ux = (struct uhci_xfer *)xfer;
	struct uhci_soft_td *data, *dataend;
	struct uhci_soft_qh *sqh;
	usbd_status err;
	u_int len;
	int s;

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

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

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

	len = xfer->length;
	sqh = upipe->u.bulk.sqh;

	err = uhci_alloc_std_chain(sc, len, xfer, &data, &dataend);
	if (err)
		return (err);
	dataend->td.td_status |= htole32(UHCI_TD_IOC);

#ifdef UHCI_DEBUG
	if (uhcidebug > 8) {
		DPRINTF(("uhci_device_bulk_start: data(1)\n"));
		uhci_dump_tds(data);
	}
#endif

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

	sqh->elink = data;
	sqh->qh.qh_elink = htole32(data->physaddr | UHCI_PTR_TD);

	s = splusb();
	uhci_add_bulk(sc, sqh);
	uhci_add_intr_list(sc, ux);

	if (xfer->timeout && !sc->sc_bus.use_polling) {
		timeout_del(&xfer->timeout_handle);
		timeout_set(&xfer->timeout_handle, uhci_timeout, xfer);
		timeout_add_msec(&xfer->timeout_handle, xfer->timeout);
	}
	xfer->status = USBD_IN_PROGRESS;
	splx(s);

#ifdef UHCI_DEBUG
	if (uhcidebug > 10) {
		DPRINTF(("uhci_device_bulk_start: data(2)\n"));
		uhci_dump_tds(data);
	}
#endif

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

	return (USBD_IN_PROGRESS);
}

/* Abort a device bulk request. */
void
uhci_device_bulk_abort(struct usbd_xfer *xfer)
{
	DPRINTF(("uhci_device_bulk_abort:\n"));
	uhci_abort_xfer(xfer, USBD_CANCELLED);
}

/*
 * 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
uhci_abort_xfer(struct usbd_xfer *xfer, usbd_status status)
{
	struct uhci_softc *sc = (struct uhci_softc *)xfer->device->bus;
	struct uhci_xfer *ux = (struct uhci_xfer *)xfer;
	struct uhci_soft_td *std;
	int s;

	DPRINTFN(1,("uhci_abort_xfer: xfer=%p, status=%d\n", xfer, status));

	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
		ux->isdone = 1;
#endif
		usb_transfer_complete(xfer);
		splx(s);
		return;
	}

	if (xfer->device->bus->intr_context || !curproc)
		panic("uhci_abort_xfer: not in process context");

	/*
	 * Step 1: Make interrupt routine and hardware ignore xfer.
	 */
	s = splusb();
	xfer->status = status;	/* make software ignore it */
	timeout_del(&xfer->timeout_handle);
	usb_rem_task(xfer->device, &xfer->abort_task);
	DPRINTFN(1,("uhci_abort_xfer: stop ux=%p\n", ux));
	for (std = ux->stdstart; std != NULL; std = std->link.std)
		std->td.td_status &= htole32(~(UHCI_TD_ACTIVE | UHCI_TD_IOC));
	splx(s);

	/*
	 * Step 2: Wait until we know hardware has finished any possible
	 * use of the xfer.  Also make sure the soft interrupt routine
	 * has run.
	 */
	usb_delay_ms(&sc->sc_bus, 2); /* Hardware finishes in 1ms */
	s = splusb();
	sc->sc_softwake = 1;
	usb_schedsoftintr(&sc->sc_bus);
	DPRINTFN(1,("uhci_abort_xfer: tsleep\n"));
	tsleep(&sc->sc_softwake, PZERO, "uhciab", 0);
	splx(s);

	/*
	 * Step 3: Execute callback.
	 */
	DPRINTFN(1,("uhci_abort_xfer: callback\n"));
	s = splusb();
#ifdef DIAGNOSTIC
	ux->isdone = 1;
#endif
	usb_transfer_complete(xfer);
	splx(s);
}

/* Close a device bulk pipe. */
void
uhci_device_bulk_close(struct usbd_pipe *pipe)
{
	struct uhci_softc *sc = (struct uhci_softc *)pipe->device->bus;
	struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;

	uhci_free_sqh(sc, upipe->u.bulk.sqh);
	pipe->endpoint->savedtoggle = upipe->nexttoggle;
}

usbd_status
uhci_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 (otherwise err would be USBD_INPROG),
	 * so start it first.
	 */
	return (uhci_device_ctrl_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
}

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

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

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

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

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

	return (USBD_IN_PROGRESS);
}

usbd_status
uhci_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 (uhci_device_intr_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
}

usbd_status
uhci_device_intr_start(struct usbd_xfer *xfer)
{
	struct uhci_softc *sc = (struct uhci_softc *)xfer->device->bus;
	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
	struct uhci_xfer *ux = (struct uhci_xfer *)xfer;
	struct uhci_soft_td *data, *dataend;
	struct uhci_soft_qh *sqh;
	usbd_status err;
	int i, s;

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

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

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

	upipe->u.intr.isread = usbd_xfer_isread(xfer);

	err = uhci_alloc_std_chain(sc, xfer->length, xfer, &data, &dataend);

	if (err)
		return (err);
	dataend->td.td_status |= htole32(UHCI_TD_IOC);

#ifdef UHCI_DEBUG
	if (uhcidebug > 10) {
		DPRINTF(("uhci_device_intr_start: data(1)\n"));
		uhci_dump_tds(data);
		uhci_dump_qh(upipe->u.intr.qhs[0]);
	}
#endif

	s = splusb();
	/* Set up interrupt info. */
	ux->stdstart = data;
	ux->stdend = dataend;
#ifdef DIAGNOSTIC
	if (!ux->isdone) {
		printf("uhci_device_intr_transfer: not done, ux=%p\n", ux);
	}
	ux->isdone = 0;
#endif

	DPRINTFN(10,("uhci_device_intr_start: qhs[0]=%p\n",
		     upipe->u.intr.qhs[0]));
	for (i = 0; i < upipe->u.intr.npoll; i++) {
		sqh = upipe->u.intr.qhs[i];
		sqh->elink = data;
		sqh->qh.qh_elink = htole32(data->physaddr | UHCI_PTR_TD);
	}
	uhci_add_intr_list(sc, ux);
	xfer->status = USBD_IN_PROGRESS;
	splx(s);

#ifdef UHCI_DEBUG
	if (uhcidebug > 10) {
		DPRINTF(("uhci_device_intr_start: data(2)\n"));
		uhci_dump_tds(data);
		uhci_dump_qh(upipe->u.intr.qhs[0]);
	}
#endif

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

	return (USBD_IN_PROGRESS);
}

/* Abort a device control request. */
void
uhci_device_ctrl_abort(struct usbd_xfer *xfer)
{
	DPRINTF(("uhci_device_ctrl_abort:\n"));
	uhci_abort_xfer(xfer, USBD_CANCELLED);
}

/* Close a device control pipe. */
void
uhci_device_ctrl_close(struct usbd_pipe *pipe)
{
}

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

	uhci_abort_xfer(xfer, USBD_CANCELLED);
}

/* Close a device interrupt pipe. */
void
uhci_device_intr_close(struct usbd_pipe *pipe)
{
	struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
	struct uhci_softc *sc = (struct uhci_softc *)pipe->device->bus;
	int i, npoll;
	int s;

	/* Unlink descriptors from controller data structures. */
	npoll = upipe->u.intr.npoll;
	s = splusb();
	for (i = 0; i < npoll; i++)
		uhci_remove_intr(sc, upipe->u.intr.qhs[i]);
	splx(s);

	/*
	 * We now have to wait for any activity on the physical
	 * descriptors to stop.
	 */
	usb_delay_ms(&sc->sc_bus, 2);

	for(i = 0; i < npoll; i++)
		uhci_free_sqh(sc, upipe->u.intr.qhs[i]);
	free(upipe->u.intr.qhs, M_USBHC, 0);

	/* XXX free other resources */
}

usbd_status
uhci_device_request(struct usbd_xfer *xfer)
{
	struct uhci_softc *sc = (struct uhci_softc *)xfer->device->bus;
	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
	struct uhci_xfer *ux = (struct uhci_xfer *)xfer;
	usb_device_request_t *req = &xfer->request;
	int addr = xfer->device->address;
	int endpt = xfer->pipe->endpoint->edesc->bEndpointAddress;
	struct uhci_soft_td *setup, *data, *stat, *next, *dataend;
	struct uhci_soft_qh *sqh;
	u_int len;
	u_int32_t ls;
	usbd_status err;
	int s;

	DPRINTFN(3,("uhci_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),
		    addr, endpt));

	ls = xfer->device->speed == USB_SPEED_LOW ? UHCI_TD_LS : 0;
	len = UGETW(req->wLength);

	setup = upipe->u.ctl.setup;
	stat = upipe->u.ctl.stat;
	sqh = upipe->u.ctl.sqh;

	/* Set up data transaction */
	if (len != 0) {
		upipe->nexttoggle = 1;
		err = uhci_alloc_std_chain(sc, len, xfer, &data, &dataend);
		if (err)
			return (err);
		next = data;
		dataend->link.std = stat;
		dataend->td.td_link = htole32(stat->physaddr | UHCI_PTR_VF | UHCI_PTR_TD);
	} else {
		next = stat;
	}
	upipe->u.ctl.length = len;

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

	setup->link.std = next;
	setup->td.td_link = htole32(next->physaddr | UHCI_PTR_VF | UHCI_PTR_TD);
	setup->td.td_status = htole32(UHCI_TD_SET_ERRCNT(3) | ls |
		UHCI_TD_ACTIVE);
	setup->td.td_token = htole32(UHCI_TD_SETUP(sizeof *req, endpt, addr));
	setup->td.td_buffer = htole32(DMAADDR(&upipe->u.ctl.reqdma, 0));

	stat->link.std = NULL;
	stat->td.td_link = htole32(UHCI_PTR_T);
	stat->td.td_status = htole32(UHCI_TD_SET_ERRCNT(3) | ls |
		UHCI_TD_ACTIVE | UHCI_TD_IOC);
	stat->td.td_token = htole32(usbd_xfer_isread(xfer) ?
	    UHCI_TD_OUT(0, endpt, addr, 1) : UHCI_TD_IN (0, endpt, addr, 1));
	stat->td.td_buffer = htole32(0);

#ifdef UHCI_DEBUG
	if (uhcidebug > 10) {
		DPRINTF(("uhci_device_request: before transfer\n"));
		uhci_dump_tds(setup);
	}
#endif

	/* Set up interrupt info. */
	ux->stdstart = setup;
	ux->stdend = stat;
#ifdef DIAGNOSTIC
	if (!ux->isdone) {
		printf("%s: not done, ux=%p\n", __func__, ux);
	}
	ux->isdone = 0;
#endif

	sqh->elink = setup;
	sqh->qh.qh_elink = htole32(setup->physaddr | UHCI_PTR_TD);

	s = splusb();
	if (xfer->device->speed == USB_SPEED_LOW)
		uhci_add_ls_ctrl(sc, sqh);
	else
		uhci_add_hs_ctrl(sc, sqh);
	uhci_add_intr_list(sc, ux);
#ifdef UHCI_DEBUG
	if (uhcidebug > 12) {
		struct uhci_soft_td *std;
		struct uhci_soft_qh *xqh;
		struct uhci_soft_qh *sxqh;
		int maxqh = 0;
		uhci_physaddr_t link;
		DPRINTF(("uhci_device_request: follow from [0]\n"));
		for (std = sc->sc_vframes[0].htd, link = 0;
		     (link & UHCI_PTR_QH) == 0;
		     std = std->link.std) {
			link = letoh32(std->td.td_link);
			uhci_dump_td(std);
		}
		sxqh = (struct uhci_soft_qh *)std;
		uhci_dump_qh(sxqh);
		for (xqh = sxqh;
		     xqh != NULL;
		     xqh = (maxqh++ == 5 || xqh->hlink == sxqh ||
                            xqh->hlink == xqh ? NULL : xqh->hlink)) {
			uhci_dump_qh(xqh);
		}
		DPRINTF(("Enqueued QH:\n"));
		uhci_dump_qh(sqh);
		uhci_dump_tds(sqh->elink);
	}
#endif
	if (xfer->timeout && !sc->sc_bus.use_polling) {
		timeout_del(&xfer->timeout_handle);
		timeout_set(&xfer->timeout_handle, uhci_timeout, xfer);
		timeout_add_msec(&xfer->timeout_handle, xfer->timeout);
	}
	xfer->status = USBD_IN_PROGRESS;
	splx(s);

	return (USBD_NORMAL_COMPLETION);
}

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

	DPRINTFN(5,("uhci_device_isoc_transfer: xfer=%p\n", xfer));

	/* Put it on our queue, */
	err = usb_insert_transfer(xfer);

	/* bail out on error, */
	if (err && err != USBD_IN_PROGRESS)
		return (err);

	/* XXX should check inuse here */

	/* insert into schedule, */
	uhci_device_isoc_enter(xfer);

	/* and start if the pipe wasn't running */
	if (!err)
		uhci_device_isoc_start(SIMPLEQ_FIRST(&xfer->pipe->queue));

	return (err);
}

void
uhci_device_isoc_enter(struct usbd_xfer *xfer)
{
	struct uhci_softc *sc = (struct uhci_softc *)xfer->device->bus;
	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
	struct iso *iso = &upipe->u.iso;
	struct uhci_soft_td *std;
	u_int32_t buf, len, status;
	int s, i, next, nframes;

	DPRINTFN(5,("uhci_device_isoc_enter: used=%d next=%d xfer=%p "
		    "nframes=%d\n",
		    iso->inuse, iso->next, xfer, xfer->nframes));

	if (sc->sc_bus.dying)
		return;

	if (xfer->status == USBD_IN_PROGRESS) {
		/* This request has already been entered into the frame list */
		printf("uhci_device_isoc_enter: xfer=%p in frame list\n", xfer);
		/* XXX */
	}

#ifdef DIAGNOSTIC
	if (iso->inuse >= UHCI_VFRAMELIST_COUNT)
		printf("uhci_device_isoc_enter: overflow!\n");
#endif

	next = iso->next;
	if (next == -1) {
		/* Not in use yet, schedule it a few frames ahead. */
		next = (UREAD2(sc, UHCI_FRNUM) + 3) % UHCI_VFRAMELIST_COUNT;
		DPRINTFN(2,("uhci_device_isoc_enter: start next=%d\n", next));
	}

	xfer->status = USBD_IN_PROGRESS;
	((struct uhci_xfer *)xfer)->curframe = next;

	buf = DMAADDR(&xfer->dmabuf, 0);
	status = UHCI_TD_ZERO_ACTLEN(UHCI_TD_SET_ERRCNT(0) |
				     UHCI_TD_ACTIVE |
				     UHCI_TD_IOS);
	nframes = xfer->nframes;
	s = splusb();
	for (i = 0; i < nframes; i++) {
		std = iso->stds[next];
		if (++next >= UHCI_VFRAMELIST_COUNT)
			next = 0;
		len = xfer->frlengths[i];
		std->td.td_buffer = htole32(buf);
		if (i == nframes - 1)
			status |= UHCI_TD_IOC;
		std->td.td_status = htole32(status);
		std->td.td_token &= htole32(~UHCI_TD_MAXLEN_MASK);
		std->td.td_token |= htole32(UHCI_TD_SET_MAXLEN(len));
#ifdef UHCI_DEBUG
		if (uhcidebug > 5) {
			DPRINTFN(5,("uhci_device_isoc_enter: TD %d\n", i));
			uhci_dump_td(std);
		}
#endif
		buf += len;
	}
	iso->next = next;
	iso->inuse += xfer->nframes;

	splx(s);
}

usbd_status
uhci_device_isoc_start(struct usbd_xfer *xfer)
{
	struct uhci_softc *sc = (struct uhci_softc *)xfer->device->bus;
	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
	struct uhci_xfer *ux = (struct uhci_xfer *)xfer;
	struct uhci_soft_td *end;
	int s, i;

	DPRINTFN(5,("uhci_device_isoc_start: xfer=%p\n", xfer));

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

#ifdef DIAGNOSTIC
	if (xfer->status != USBD_IN_PROGRESS)
		printf("uhci_device_isoc_start: not in progress %p\n", xfer);
#endif

	/* Find the last TD */
	i = ux->curframe + xfer->nframes;
	if (i >= UHCI_VFRAMELIST_COUNT)
		i -= UHCI_VFRAMELIST_COUNT;
	end = upipe->u.iso.stds[i];

#ifdef DIAGNOSTIC
	if (end == NULL) {
		printf("uhci_device_isoc_start: end == NULL\n");
		return (USBD_INVAL);
	}
#endif

	s = splusb();

	/* Set up interrupt info. */
	ux->stdstart = end;
	ux->stdend = end;
#ifdef DIAGNOSTIC
	if (!ux->isdone)
		printf("%s: not done, ux=%p\n", __func__, ux);
	ux->isdone = 0;
#endif
	uhci_add_intr_list(sc, ux);

	splx(s);

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

	return (USBD_IN_PROGRESS);
}

void
uhci_device_isoc_abort(struct usbd_xfer *xfer)
{
	struct uhci_xfer *ux = (struct uhci_xfer *)xfer;
	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
	struct uhci_soft_td **stds = upipe->u.iso.stds;
	struct uhci_soft_td *std;
	int i, n, s, nframes, maxlen, len;

	s = splusb();

	/* Transfer is already done. */
	if (xfer->status != USBD_NOT_STARTED &&
	    xfer->status != USBD_IN_PROGRESS) {
		splx(s);
		return;
	}

	/* Give xfer the requested abort code. */
	xfer->status = USBD_CANCELLED;

	/* make hardware ignore it, */
	nframes = xfer->nframes;
	n = ux->curframe;
	maxlen = 0;
	for (i = 0; i < nframes; i++) {
		std = stds[n];
		std->td.td_status &= htole32(~(UHCI_TD_ACTIVE | UHCI_TD_IOC));
		len = UHCI_TD_GET_MAXLEN(letoh32(std->td.td_token));
		if (len > maxlen)
			maxlen = len;
		if (++n >= UHCI_VFRAMELIST_COUNT)
			n = 0;
	}

	/* and wait until we are sure the hardware has finished. */
	delay(maxlen);

#ifdef DIAGNOSTIC
	ux->isdone = 1;
#endif
	/* Run callback and remove from interrupt list. */
	usb_transfer_complete(xfer);

	splx(s);
}

void
uhci_device_isoc_close(struct usbd_pipe *pipe)
{
	struct uhci_softc *sc = (struct uhci_softc *)pipe->device->bus;
	struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
	struct uhci_soft_td *std, *vstd;
	struct iso *iso;
	int i, s;

	/*
	 * Make sure all TDs are marked as inactive.
	 * Wait for completion.
	 * Unschedule.
	 * Deallocate.
	 */
	iso = &upipe->u.iso;

	for (i = 0; i < UHCI_VFRAMELIST_COUNT; i++)
		iso->stds[i]->td.td_status &= htole32(~UHCI_TD_ACTIVE);
	usb_delay_ms(&sc->sc_bus, 2); /* wait for completion */

	s = splusb();
	for (i = 0; i < UHCI_VFRAMELIST_COUNT; i++) {
		std = iso->stds[i];
		for (vstd = sc->sc_vframes[i].htd;
		     vstd != NULL && vstd->link.std != std;
		     vstd = vstd->link.std)
			;
		if (vstd == NULL) {
			/*panic*/
			printf("uhci_device_isoc_close: %p not found\n", std);
			splx(s);
			return;
		}
		vstd->link = std->link;
		vstd->td.td_link = std->td.td_link;
		uhci_free_std(sc, std);
	}
	splx(s);

	free(iso->stds, M_USBHC, 0);
}

usbd_status
uhci_setup_isoc(struct usbd_pipe *pipe)
{
	struct uhci_softc *sc = (struct uhci_softc *)pipe->device->bus;
	struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
	int addr = pipe->device->address;
	int endpt = pipe->endpoint->edesc->bEndpointAddress;
	int rd = UE_GET_DIR(endpt) == UE_DIR_IN;
	struct uhci_soft_td *std, *vstd;
	u_int32_t token;
	struct iso *iso;
	int i, s;

	iso = &upipe->u.iso;
	iso->stds = malloc(UHCI_VFRAMELIST_COUNT *
			   sizeof (struct uhci_soft_td *),
			   M_USBHC, M_WAITOK);

	token = rd ? UHCI_TD_IN (0, endpt, addr, 0) :
		     UHCI_TD_OUT(0, endpt, addr, 0);

	/* Allocate the TDs and mark as inactive; */
	for (i = 0; i < UHCI_VFRAMELIST_COUNT; i++) {
		std = uhci_alloc_std(sc);
		if (std == 0)
			goto bad;
		std->td.td_status = htole32(UHCI_TD_IOS); /* iso, inactive */
		std->td.td_token = htole32(token);
		iso->stds[i] = std;
	}

	/* Insert TDs into schedule. */
	s = splusb();
	for (i = 0; i < UHCI_VFRAMELIST_COUNT; i++) {
		std = iso->stds[i];
		vstd = sc->sc_vframes[i].htd;
		std->link = vstd->link;
		std->td.td_link = vstd->td.td_link;
		vstd->link.std = std;
		vstd->td.td_link = htole32(std->physaddr | UHCI_PTR_TD);
	}
	splx(s);

	iso->next = -1;
	iso->inuse = 0;

	return (USBD_NORMAL_COMPLETION);

 bad:
	while (--i >= 0)
		uhci_free_std(sc, iso->stds[i]);
	free(iso->stds, M_USBHC, 0);
	return (USBD_NOMEM);
}

void
uhci_device_isoc_done(struct usbd_xfer *xfer)
{
	struct uhci_xfer *ux = (struct uhci_xfer *)xfer;

	DPRINTFN(4, ("uhci_device_isoc_done: length=%d\n", xfer->actlen));

	if (!uhci_active_intr_list(ux))
		return;

#ifdef DIAGNOSTIC
        if (ux->stdend == NULL) {
                printf("uhci_device_isoc_done: xfer=%p stdend==NULL\n", xfer);
#ifdef UHCI_DEBUG
		uhci_dump_xfer(ux);
#endif
		return;
	}
#endif

	/* Turn off the interrupt since it is active even if the TD is not. */
	ux->stdend->td.td_status &= htole32(~UHCI_TD_IOC);

	uhci_del_intr_list(ux);	/* remove from active list */
}

void
uhci_device_intr_done(struct usbd_xfer *xfer)
{
	struct uhci_softc *sc = (struct uhci_softc *)xfer->device->bus;
	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
	struct uhci_xfer *ux = (struct uhci_xfer *)xfer;
	struct uhci_soft_qh *sqh;
	int i, npoll;

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

	npoll = upipe->u.intr.npoll;
	for(i = 0; i < npoll; i++) {
		sqh = upipe->u.intr.qhs[i];
		sqh->elink = NULL;
		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
	}
	uhci_free_std_chain(sc, ux->stdstart, NULL);

	/* XXX Wasteful. */
	if (xfer->pipe->repeat) {
		struct uhci_soft_td *data, *dataend;

		DPRINTFN(5,("uhci_device_intr_done: requeuing\n"));

		/* This alloc cannot fail since we freed the chain above. */
		uhci_alloc_std_chain(sc, xfer->length, xfer, &data, &dataend);
		dataend->td.td_status |= htole32(UHCI_TD_IOC);

#ifdef UHCI_DEBUG
		if (uhcidebug > 10) {
			DPRINTF(("uhci_device_intr_done: data(1)\n"));
			uhci_dump_tds(data);
			uhci_dump_qh(upipe->u.intr.qhs[0]);
		}
#endif

		ux->stdstart = data;
		ux->stdend = dataend;
#ifdef DIAGNOSTIC
		if (!ux->isdone) {
			printf("%s: not done, ux=%p\n", __func__, ux);
		}
		ux->isdone = 0;
#endif
		for (i = 0; i < npoll; i++) {
			sqh = upipe->u.intr.qhs[i];
			sqh->elink = data;
			sqh->qh.qh_elink = htole32(data->physaddr | UHCI_PTR_TD);
		}
		xfer->status = USBD_IN_PROGRESS;
		/* The ux is already on the examined list, just leave it. */
	} else {
		DPRINTFN(5,("uhci_device_intr_done: removing\n"));
		if (uhci_active_intr_list(ux))
			uhci_del_intr_list(ux);
	}
}

/* Deallocate request data structures */
void
uhci_device_ctrl_done(struct usbd_xfer *xfer)
{
	struct uhci_softc *sc = (struct uhci_softc *)xfer->device->bus;
	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
	struct uhci_xfer *ux = (struct uhci_xfer *)xfer;

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

	if (!uhci_active_intr_list(ux))
		return;

	uhci_del_intr_list(ux);	/* remove from active list */

	if (xfer->device->speed == USB_SPEED_LOW)
		uhci_remove_ls_ctrl(sc, upipe->u.ctl.sqh);
	else
		uhci_remove_hs_ctrl(sc, upipe->u.ctl.sqh);

	if (upipe->u.ctl.length != 0)
		uhci_free_std_chain(sc, ux->stdstart->link.std, ux->stdend);

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

/* Deallocate request data structures */
void
uhci_device_bulk_done(struct usbd_xfer *xfer)
{
	struct uhci_softc *sc = (struct uhci_softc *)xfer->device->bus;
	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
	struct uhci_xfer *ux = (struct uhci_xfer *)xfer;

	DPRINTFN(5,("uhci_device_bulk_done: xfer=%p ux=%p sc=%p upipe=%p\n",
		    xfer, ux, sc, upipe));

	if (!uhci_active_intr_list(ux))
		return;

	uhci_del_intr_list(ux);	/* remove from active list */

	uhci_remove_bulk(sc, upipe->u.bulk.sqh);

	uhci_free_std_chain(sc, ux->stdstart, NULL);

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

/* Add interrupt QH, called with vflock. */
void
uhci_add_intr(struct uhci_softc *sc, struct uhci_soft_qh *sqh)
{
	struct uhci_vframe *vf = &sc->sc_vframes[sqh->pos];
	struct uhci_soft_qh *eqh;

	DPRINTFN(4, ("uhci_add_intr: n=%d sqh=%p\n", sqh->pos, sqh));

	eqh = vf->eqh;
	sqh->hlink       = eqh->hlink;
	sqh->qh.qh_hlink = eqh->qh.qh_hlink;
	eqh->hlink       = sqh;
	eqh->qh.qh_hlink = htole32(sqh->physaddr | UHCI_PTR_QH);
	vf->eqh = sqh;
	vf->bandwidth++;
}

/* Remove interrupt QH. */
void
uhci_remove_intr(struct uhci_softc *sc, struct uhci_soft_qh *sqh)
{
	struct uhci_vframe *vf = &sc->sc_vframes[sqh->pos];
	struct uhci_soft_qh *pqh;

	DPRINTFN(4, ("uhci_remove_intr: n=%d sqh=%p\n", sqh->pos, sqh));

	/* See comment in uhci_remove_ctrl() */
	if (!(sqh->qh.qh_elink & htole32(UHCI_PTR_T))) {
		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
		delay(UHCI_QH_REMOVE_DELAY);
	}

	pqh = uhci_find_prev_qh(vf->hqh, sqh);
	pqh->hlink       = sqh->hlink;
	pqh->qh.qh_hlink = sqh->qh.qh_hlink;
	delay(UHCI_QH_REMOVE_DELAY);
	if (vf->eqh == sqh)
		vf->eqh = pqh;
	vf->bandwidth--;
}

usbd_status
uhci_device_setintr(struct uhci_softc *sc, struct uhci_pipe *upipe, int ival)
{
	struct uhci_soft_qh *sqh, **qhs;
	int i, npoll, s;
	u_int bestbw, bw, bestoffs, offs;

	DPRINTFN(2, ("uhci_device_setintr: pipe=%p\n", upipe));
	if (ival == 0) {
		printf("uhci_device_setintr: 0 interval\n");
		return (USBD_INVAL);
	}

	if (ival > UHCI_VFRAMELIST_COUNT)
		ival = UHCI_VFRAMELIST_COUNT;
	npoll = (UHCI_VFRAMELIST_COUNT + ival - 1) / ival;
	DPRINTFN(2, ("uhci_device_setintr: ival=%d npoll=%d\n", ival, npoll));

	qhs = mallocarray(npoll, sizeof(struct uhci_soft_qh *), M_USBHC,
	    M_NOWAIT);
	if (qhs == NULL)
		return (USBD_NOMEM);

	/*
	 * Figure out which offset in the schedule that has most
	 * bandwidth left over.
	 */
#define MOD(i) ((i) & (UHCI_VFRAMELIST_COUNT-1))
	for (bestoffs = offs = 0, bestbw = ~0; offs < ival; offs++) {
		for (bw = i = 0; i < npoll; i++)
			bw += sc->sc_vframes[MOD(i * ival + offs)].bandwidth;
		if (bw < bestbw) {
			bestbw = bw;
			bestoffs = offs;
		}
	}
	DPRINTFN(1, ("uhci_device_setintr: bw=%d offs=%d\n", bestbw, bestoffs));

	for(i = 0; i < npoll; i++) {
		sqh = uhci_alloc_sqh(sc);
		if (sqh == NULL) {
			while (i > 0)
				uhci_free_sqh(sc, qhs[--i]);
			free(qhs, M_USBHC, 0);
			return (USBD_NOMEM);
		}
		sqh->elink = NULL;
		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
		sqh->pos = MOD(i * ival + bestoffs);
		qhs[i] = sqh;
	}
#undef MOD

	upipe->u.intr.npoll = npoll;
	upipe->u.intr.qhs = qhs;

	s = splusb();
	/* Enter QHs into the controller data structures. */
	for(i = 0; i < npoll; i++)
		uhci_add_intr(sc, upipe->u.intr.qhs[i]);
	splx(s);

	DPRINTFN(5, ("uhci_device_setintr: returns %p\n", upipe));
	return (USBD_NORMAL_COMPLETION);
}

/* Open a new pipe. */
usbd_status
uhci_open(struct usbd_pipe *pipe)
{
	struct uhci_softc *sc = (struct uhci_softc *)pipe->device->bus;
	struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
	usb_endpoint_descriptor_t *ed = pipe->endpoint->edesc;
	usbd_status err;
	int ival;

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

	upipe->nexttoggle = pipe->endpoint->savedtoggle;

	/* Root Hub */
	if (pipe->device->depth == 0) {
		switch (ed->bEndpointAddress) {
		case USB_CONTROL_ENDPOINT:
			pipe->methods = &uhci_root_ctrl_methods;
			break;
		case UE_DIR_IN | UHCI_INTR_ENDPT:
			pipe->methods = &uhci_root_intr_methods;
			break;
		default:
			return (USBD_INVAL);
		}
	} else {
		switch (ed->bmAttributes & UE_XFERTYPE) {
		case UE_CONTROL:
			pipe->methods = &uhci_device_ctrl_methods;
			upipe->u.ctl.sqh = uhci_alloc_sqh(sc);
			if (upipe->u.ctl.sqh == NULL)
				goto bad;
			upipe->u.ctl.setup = uhci_alloc_std(sc);
			if (upipe->u.ctl.setup == NULL) {
				uhci_free_sqh(sc, upipe->u.ctl.sqh);
				goto bad;
			}
			upipe->u.ctl.stat = uhci_alloc_std(sc);
			if (upipe->u.ctl.stat == NULL) {
				uhci_free_sqh(sc, upipe->u.ctl.sqh);
				uhci_free_std(sc, upipe->u.ctl.setup);
				goto bad;
			}
			err = usb_allocmem(&sc->sc_bus,
				  sizeof(usb_device_request_t),
				  0, &upipe->u.ctl.reqdma);
			if (err) {
				uhci_free_sqh(sc, upipe->u.ctl.sqh);
				uhci_free_std(sc, upipe->u.ctl.setup);
				uhci_free_std(sc, upipe->u.ctl.stat);
				goto bad;
			}
			break;
		case UE_INTERRUPT:
			pipe->methods = &uhci_device_intr_methods;
			ival = pipe->interval;
			if (ival == USBD_DEFAULT_INTERVAL)
				ival = ed->bInterval;
			return (uhci_device_setintr(sc, upipe, ival));
		case UE_ISOCHRONOUS:
			pipe->methods = &uhci_device_isoc_methods;
			return (uhci_setup_isoc(pipe));
		case UE_BULK:
			pipe->methods = &uhci_device_bulk_methods;
			upipe->u.bulk.sqh = uhci_alloc_sqh(sc);
			if (upipe->u.bulk.sqh == NULL)
				goto bad;
			break;
		}
	}
	return (USBD_NORMAL_COMPLETION);

 bad:
	return (USBD_NOMEM);
}

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

usb_config_descriptor_t uhci_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 uhci_ifcd = {
	USB_INTERFACE_DESCRIPTOR_SIZE,
	UDESC_INTERFACE,
	0,
	0,
	1,
	UICLASS_HUB,
	UISUBCLASS_HUB,
	UIPROTO_FSHUB,
	0
};

usb_endpoint_descriptor_t uhci_endpd = {
	USB_ENDPOINT_DESCRIPTOR_SIZE,
	UDESC_ENDPOINT,
	UE_DIR_IN | UHCI_INTR_ENDPT,
	UE_INTERRUPT,
	{8},
	255
};

usb_hub_descriptor_t uhci_hubd_piix = {
	USB_HUB_DESCRIPTOR_SIZE,
	UDESC_HUB,
	2,
	{ UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL, 0 },
	50,			/* power on to power good */
	0,
	{ 0x00 },		/* both ports are removable */
};

/*
 * The USB hub protocol requires that SET_FEATURE(PORT_RESET) also
 * enables the port, and also states that SET_FEATURE(PORT_ENABLE)
 * should not be used by the USB subsystem.  As we cannot issue a
 * SET_FEATURE(PORT_ENABLE) externally, we must ensure that the port
 * will be enabled as part of the reset.
 *
 * On the VT83C572, the port cannot be successfully enabled until the
 * outstanding "port enable change" and "connection status change"
 * events have been reset.
 */
usbd_status
uhci_portreset(struct uhci_softc *sc, int index)
{
	int lim, port, x;

	if (index == 1)
		port = UHCI_PORTSC1;
	else if (index == 2)
		port = UHCI_PORTSC2;
	else
		return (USBD_IOERROR);

	x = URWMASK(UREAD2(sc, port));
	UWRITE2(sc, port, x | UHCI_PORTSC_PR);

	usb_delay_ms(&sc->sc_bus, USB_PORT_ROOT_RESET_DELAY);

	DPRINTFN(3,("uhci port %d reset, status0 = 0x%04x\n",
		    index, UREAD2(sc, port)));

	x = URWMASK(UREAD2(sc, port));
	UWRITE2(sc, port, x & ~UHCI_PORTSC_PR);

	delay(100);

	DPRINTFN(3,("uhci port %d reset, status1 = 0x%04x\n",
		    index, UREAD2(sc, port)));

	x = URWMASK(UREAD2(sc, port));
	UWRITE2(sc, port, x  | UHCI_PORTSC_PE);

	for (lim = 10; --lim > 0;) {
		usb_delay_ms(&sc->sc_bus, USB_PORT_RESET_DELAY);

		x = UREAD2(sc, port);

		DPRINTFN(3,("uhci port %d iteration %u, status = 0x%04x\n",
			    index, lim, x));

		if (!(x & UHCI_PORTSC_CCS)) {
			/*
			 * No device is connected (or was disconnected
			 * during reset).  Consider the port reset.
			 * The delay must be long enough to ensure on
			 * the initial iteration that the device
			 * connection will have been registered.  50ms
			 * appears to be sufficient, but 20ms is not.
			 */
			DPRINTFN(3,("uhci port %d loop %u, device detached\n",
				    index, lim));
			break;
		}

		if (x & (UHCI_PORTSC_POEDC | UHCI_PORTSC_CSC)) {
			/*
			 * Port enabled changed and/or connection
			 * status changed were set.  Reset either or
			 * both raised flags (by writing a 1 to that
			 * bit), and wait again for state to settle.
			 */
			UWRITE2(sc, port, URWMASK(x) |
				(x & (UHCI_PORTSC_POEDC | UHCI_PORTSC_CSC)));
			continue;
		}

		if (x & UHCI_PORTSC_PE)
			/* Port is enabled */
			break;

		UWRITE2(sc, port, URWMASK(x) | UHCI_PORTSC_PE);
	}

	DPRINTFN(3,("uhci port %d reset, status2 = 0x%04x\n",
		    index, UREAD2(sc, port)));

	if (lim <= 0) {
		DPRINTFN(1,("uhci port %d reset timed out\n", index));
		return (USBD_TIMEOUT);
	}
	
	sc->sc_isreset = 1;
	return (USBD_NORMAL_COMPLETION);
}

/*
 * Simulate a hardware hub by handling all the necessary requests.
 */
usbd_status
uhci_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 (otherwise err would be USBD_INPROG),
	 * so start it first.
	 */
	return (uhci_root_ctrl_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
}

usbd_status
uhci_root_ctrl_start(struct usbd_xfer *xfer)
{
	struct uhci_softc *sc = (struct uhci_softc *)xfer->device->bus;
	usb_device_request_t *req;
	void *buf = NULL;
	int port, x;
	int s, len, value, index, status, change, l, totlen = 0;
	usb_port_status_t ps;
	usbd_status err;

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

#ifdef DIAGNOSTIC
	if (!(xfer->rqflags & URQ_REQUEST))
		panic("uhci_root_ctrl_start: not a request");
#endif
	req = &xfer->request;

	DPRINTFN(2,("uhci_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(2,("uhci_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(uhci_devd.idVendor, sc->sc_id_vendor);
			memcpy(buf, &uhci_devd, l);
			break;
		case UDESC_CONFIG:
			if ((value & 0xff) != 0) {
				err = USBD_IOERROR;
				goto ret;
			}
			totlen = l = min(len, USB_CONFIG_DESCRIPTOR_SIZE);
			memcpy(buf, &uhci_confd, l);
			buf = (char *)buf + l;
			len -= l;
			l = min(len, USB_INTERFACE_DESCRIPTOR_SIZE);
			totlen += l;
			memcpy(buf, &uhci_ifcd, l);
			buf = (char *)buf + l;
			len -= l;
			l = min(len, USB_ENDPOINT_DESCRIPTOR_SIZE);
			totlen += l;
			memcpy(buf, &uhci_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, "UHCI 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(3, ("uhci_root_ctrl_start: UR_CLEAR_PORT_FEATURE "
			     "port=%d feature=%d\n",
			     index, value));
		if (index == 1)
			port = UHCI_PORTSC1;
		else if (index == 2)
			port = UHCI_PORTSC2;
		else {
			err = USBD_IOERROR;
			goto ret;
		}
		switch(value) {
		case UHF_PORT_ENABLE:
			x = URWMASK(UREAD2(sc, port));
			UWRITE2(sc, port, x & ~UHCI_PORTSC_PE);
			break;
		case UHF_PORT_SUSPEND:
			x = URWMASK(UREAD2(sc, port));
			UWRITE2(sc, port, x & ~UHCI_PORTSC_SUSP);
			break;
		case UHF_PORT_RESET:
			x = URWMASK(UREAD2(sc, port));
			UWRITE2(sc, port, x & ~UHCI_PORTSC_PR);
			break;
		case UHF_C_PORT_CONNECTION:
			x = URWMASK(UREAD2(sc, port));
			UWRITE2(sc, port, x | UHCI_PORTSC_CSC);
			break;
		case UHF_C_PORT_ENABLE:
			x = URWMASK(UREAD2(sc, port));
			UWRITE2(sc, port, x | UHCI_PORTSC_POEDC);
			break;
		case UHF_C_PORT_OVER_CURRENT:
			x = URWMASK(UREAD2(sc, port));
			UWRITE2(sc, port, x | UHCI_PORTSC_OCIC);
			break;
		case UHF_C_PORT_RESET:
			sc->sc_isreset = 0;
			err = USBD_NORMAL_COMPLETION;
			goto ret;
		case UHF_PORT_CONNECTION:
		case UHF_PORT_OVER_CURRENT:
		case UHF_PORT_POWER:
		case UHF_PORT_LOW_SPEED:
		case UHF_C_PORT_SUSPEND:
		default:
			err = USBD_IOERROR;
			goto ret;
		}
		break;
	case C(UR_GET_BUS_STATE, UT_READ_CLASS_OTHER):
		if (index == 1)
			port = UHCI_PORTSC1;
		else if (index == 2)
			port = UHCI_PORTSC2;
		else {
			err = USBD_IOERROR;
			goto ret;
		}
		if (len > 0) {
			*(u_int8_t *)buf =
				(UREAD2(sc, port) & UHCI_PORTSC_LS) >>
				UHCI_PORTSC_LS_SHIFT;
			totlen = 1;
		}
		break;
	case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
		if ((value & 0xff) != 0) {
			err = USBD_IOERROR;
			goto ret;
		}
		l = min(len, USB_HUB_DESCRIPTOR_SIZE);
		totlen = l;
		memcpy(buf, &uhci_hubd_piix, l);
		break;
	case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
		if (len != 4) {
			err = USBD_IOERROR;
			goto ret;
		}
		memset(buf, 0, len);
		totlen = len;
		break;
	case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
		if (index == 1)
			port = UHCI_PORTSC1;
		else if (index == 2)
			port = UHCI_PORTSC2;
		else {
			err = USBD_IOERROR;
			goto ret;
		}
		if (len != 4) {
			err = USBD_IOERROR;
			goto ret;
		}
		x = UREAD2(sc, port);
		status = change = 0;
		if (x & UHCI_PORTSC_CCS)
			status |= UPS_CURRENT_CONNECT_STATUS;
		if (x & UHCI_PORTSC_CSC)
			change |= UPS_C_CONNECT_STATUS;
		if (x & UHCI_PORTSC_PE)
			status |= UPS_PORT_ENABLED;
		if (x & UHCI_PORTSC_POEDC)
			change |= UPS_C_PORT_ENABLED;
		if (x & UHCI_PORTSC_OCI)
			status |= UPS_OVERCURRENT_INDICATOR;
		if (x & UHCI_PORTSC_OCIC)
			change |= UPS_C_OVERCURRENT_INDICATOR;
		if (x & UHCI_PORTSC_SUSP)
			status |= UPS_SUSPEND;
		if (x & UHCI_PORTSC_LSDA)
			status |= UPS_LOW_SPEED;
		status |= UPS_PORT_POWER;
		if (sc->sc_isreset)
			change |= UPS_C_PORT_RESET;
		USETW(ps.wPortStatus, status);
		USETW(ps.wPortChange, change);
		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)
			port = UHCI_PORTSC1;
		else if (index == 2)
			port = UHCI_PORTSC2;
		else {
			err = USBD_IOERROR;
			goto ret;
		}
		switch(value) {
		case UHF_PORT_ENABLE:
			x = URWMASK(UREAD2(sc, port));
			UWRITE2(sc, port, x | UHCI_PORTSC_PE);
			break;
		case UHF_PORT_SUSPEND:
			x = URWMASK(UREAD2(sc, port));
			UWRITE2(sc, port, x | UHCI_PORTSC_SUSP);
			break;
		case UHF_PORT_RESET:
			err = uhci_portreset(sc, index);
			goto ret;
		case UHF_PORT_POWER:
			/* Pretend we turned on power */
			err = USBD_NORMAL_COMPLETION;
			goto ret;
		case UHF_PORT_DISOWN_TO_1_1:
			/* accept, but do nothing */
			err = USBD_NORMAL_COMPLETION;
			goto ret;
		case UHF_C_PORT_CONNECTION:
		case UHF_C_PORT_ENABLE:
		case UHF_C_PORT_OVER_CURRENT:
		case UHF_PORT_CONNECTION:
		case UHF_PORT_OVER_CURRENT:
		case UHF_PORT_LOW_SPEED:
		case UHF_C_PORT_SUSPEND:
		case UHF_C_PORT_RESET:
		default:
			err = USBD_IOERROR;
			goto ret;
		}
		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);
}

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

/* Close the root pipe. */
void
uhci_root_ctrl_close(struct usbd_pipe *pipe)
{
	DPRINTF(("uhci_root_ctrl_close\n"));
}

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

	timeout_del(&sc->sc_root_intr);
	sc->sc_intrxfer = NULL;

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

usbd_status
uhci_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 (otherwise err would be USBD_INPROG),
	 * start first
	 */
	return (uhci_root_intr_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
}

/* Start a transfer on the root interrupt pipe */
usbd_status
uhci_root_intr_start(struct usbd_xfer *xfer)
{
	struct uhci_softc *sc = (struct uhci_softc *)xfer->device->bus;

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

	sc->sc_intrxfer = xfer;
	timeout_add_msec(&sc->sc_root_intr, 255);

	return (USBD_IN_PROGRESS);
}

void
uhci_root_intr_close(struct usbd_pipe *pipe)
{
}

void
uhci_root_intr_done(struct usbd_xfer *xfer)
{
	struct uhci_softc *sc = (struct uhci_softc *)xfer->device->bus;

	if (xfer->pipe->repeat)
		timeout_add_msec(&sc->sc_root_intr, 255);
}