summaryrefslogtreecommitdiffstats
path: root/sys/dev/atkbdc/psm.c
blob: dd2fd7e2cc89d9d58915dec320ec206059ac277c (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
/*-
 * Copyright (c) 1992, 1993 Erik Forsberg.
 * Copyright (c) 1996, 1997 Kazutaka YOKOTA.
 * All rights reserved.
 *
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY ``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 I 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.
 */
/*
 *  Ported to 386bsd Oct 17, 1992
 *  Sandi Donno, Computer Science, University of Cape Town, South Africa
 *  Please send bug reports to sandi@cs.uct.ac.za
 *
 *  Thanks are also due to Rick Macklem, rick@snowhite.cis.uoguelph.ca -
 *  although I was only partially successful in getting the alpha release
 *  of his "driver for the Logitech and ATI Inport Bus mice for use with
 *  386bsd and the X386 port" to work with my Microsoft mouse, I nevertheless
 *  found his code to be an invaluable reference when porting this driver
 *  to 386bsd.
 *
 *  Further modifications for latest 386BSD+patchkit and port to NetBSD,
 *  Andrew Herbert <andrew@werple.apana.org.au> - 8 June 1993
 *
 *  Cloned from the Microsoft Bus Mouse driver, also by Erik Forsberg, by
 *  Andrew Herbert - 12 June 1993
 *
 *  Modified for PS/2 mouse by Charles Hannum <mycroft@ai.mit.edu>
 *  - 13 June 1993
 *
 *  Modified for PS/2 AUX mouse by Shoji Yuen <yuen@nuie.nagoya-u.ac.jp>
 *  - 24 October 1993
 *
 *  Hardware access routines and probe logic rewritten by
 *  Kazutaka Yokota <yokota@zodiac.mech.utsunomiya-u.ac.jp>
 *  - 3, 14, 22 October 1996.
 *  - 12 November 1996. IOCTLs and rearranging `psmread', `psmioctl'...
 *  - 14, 30 November 1996. Uses `kbdio.c'.
 *  - 13 December 1996. Uses queuing version of `kbdio.c'.
 *  - January/February 1997. Tweaked probe logic for 
 *    HiNote UltraII/Latitude/Armada laptops.
 *  - 30 July 1997. Added APM support.
 *  - 5 March 1997. Defined driver configuration flags (PSM_CONFIG_XXX). 
 *    Improved sync check logic.
 *    Vendor specific support routines.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_psm.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/bus.h>
#include <sys/conf.h>
#include <sys/poll.h>
#include <sys/syslog.h>
#include <machine/bus.h>
#include <sys/rman.h>
#include <sys/selinfo.h>
#include <sys/sysctl.h>
#include <sys/time.h>
#include <sys/uio.h>

#include <sys/limits.h>
#include <sys/mouse.h>
#include <machine/resource.h>

#include <isa/isavar.h>
#include <dev/kbd/atkbdcreg.h>

/*
 * Driver specific options: the following options may be set by
 * `options' statements in the kernel configuration file.
 */

/* debugging */
#ifndef PSM_DEBUG
#define PSM_DEBUG	0	/* logging: 0: none, 1: brief, 2: verbose */
#endif

#ifndef PSM_SYNCERR_THRESHOLD1
#define PSM_SYNCERR_THRESHOLD1	20
#endif

#ifndef PSM_INPUT_TIMEOUT
#define PSM_INPUT_TIMEOUT	2000000	/* 2 sec */
#endif

/* end of driver specific options */

#define PSM_DRIVER_NAME		"psm"
#define PSMCPNP_DRIVER_NAME	"psmcpnp"

/* input queue */
#define PSM_BUFSIZE		960
#define PSM_SMALLBUFSIZE	240

/* operation levels */
#define PSM_LEVEL_BASE		0
#define PSM_LEVEL_STANDARD	1
#define PSM_LEVEL_NATIVE	2
#define PSM_LEVEL_MIN		PSM_LEVEL_BASE
#define PSM_LEVEL_MAX		PSM_LEVEL_NATIVE

/* Logitech PS2++ protocol */
#define MOUSE_PS2PLUS_CHECKBITS(b)	\
				((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
#define MOUSE_PS2PLUS_PACKET_TYPE(b)	\
				(((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))

/* some macros */
#define PSM_UNIT(dev)		(minor(dev) >> 1)
#define PSM_NBLOCKIO(dev)	(minor(dev) & 1)
#define PSM_MKMINOR(unit,block)	(((unit) << 1) | ((block) ? 0:1))

/* ring buffer */
typedef struct ringbuf {
    int           count;	/* # of valid elements in the buffer */
    int           head;		/* head pointer */
    int           tail;		/* tail poiner */
    unsigned char buf[PSM_BUFSIZE];
} ringbuf_t;

/* data buffer */
typedef struct packetbuf {
    unsigned char ipacket[16];	/* interim input buffer */
    int           inputbytes;	/* # of bytes in the input buffer */
} packetbuf_t;

#ifndef PSM_PACKETQUEUE
#define PSM_PACKETQUEUE	128
#endif

/* driver control block */
struct psm_softc {		/* Driver status information */
    int		  unit;
    struct selinfo rsel;	/* Process selecting for Input */
    unsigned char state;	/* Mouse driver state */
    int           config;	/* driver configuration flags */
    int           flags;	/* other flags */
    KBDC          kbdc;		/* handle to access the keyboard controller */
    struct resource *intr;	/* IRQ resource */
    void	  *ih;		/* interrupt handle */
    mousehw_t     hw;		/* hardware information */
    mousemode_t   mode;		/* operation mode */
    mousemode_t   dflt_mode;	/* default operation mode */
    mousestatus_t status;	/* accumulated mouse movement */
    ringbuf_t     queue;	/* mouse status queue */
    packetbuf_t   pqueue[PSM_PACKETQUEUE];	/* mouse data queue */
    int           pqueue_start; /* start of data in queue */
    int           pqueue_end;   /* end of data in queue */
    int           button;	/* the latest button state */
    int		  xold;	/* previous absolute X position */
    int		  yold;	/* previous absolute Y position */
    int		  syncerrors; /* XXX: KILL ME! */
    struct timeval inputtimeout;
    struct timeval lastsoftintr;	/* time of last soft interrupt */
    struct timeval lastinputerr;	/* time last sync error happened */
    int		  watchdog;	/* watchdog timer flag */
    struct callout_handle callout;	/* watchdog timer call out */
    struct callout_handle softcallout;	/* buffer timer call out */
    dev_t	  dev;
    dev_t	  bdev;
    int           lasterr;
    int           cmdcount;
};
static devclass_t psm_devclass;
#define PSM_SOFTC(unit)	((struct psm_softc*)devclass_get_softc(psm_devclass, unit))

/* driver state flags (state) */
#define PSM_VALID		0x80
#define PSM_OPEN		1	/* Device is open */
#define PSM_ASLP		2	/* Waiting for mouse data */
#define PSM_SOFTARMED		4	/* Software interrupt armed */

/* driver configuration flags (config) */
#define PSM_CONFIG_RESOLUTION	0x000f	/* resolution */
#define PSM_CONFIG_ACCEL	0x00f0  /* acceleration factor */
#define PSM_CONFIG_NOCHECKSYNC	0x0100  /* disable sync. test */
#define PSM_CONFIG_NOIDPROBE	0x0200  /* disable mouse model probe */
#define PSM_CONFIG_NORESET	0x0400  /* don't reset the mouse */
#define PSM_CONFIG_FORCETAP	0x0800  /* assume `tap' action exists */
#define PSM_CONFIG_IGNPORTERROR	0x1000  /* ignore error in aux port test */
#define PSM_CONFIG_HOOKRESUME	0x2000	/* hook the system resume event */
#define PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resume event */
#define PSM_CONFIG_SYNCHACK	0x8000 /* enable `out-of-sync' hack */

#define PSM_CONFIG_FLAGS	(PSM_CONFIG_RESOLUTION 		\
				    | PSM_CONFIG_ACCEL		\
				    | PSM_CONFIG_NOCHECKSYNC	\
				    | PSM_CONFIG_SYNCHACK	\
				    | PSM_CONFIG_NOIDPROBE	\
				    | PSM_CONFIG_NORESET	\
				    | PSM_CONFIG_FORCETAP	\
				    | PSM_CONFIG_IGNPORTERROR	\
				    | PSM_CONFIG_HOOKRESUME	\
				    | PSM_CONFIG_INITAFTERSUSPEND)

/* other flags (flags) */
#define PSM_FLAGS_FINGERDOWN	0x0001 /* VersaPad finger down */

/* for backward compatibility */
#define OLD_MOUSE_GETHWINFO	_IOR('M', 1, old_mousehw_t)
#define OLD_MOUSE_GETMODE	_IOR('M', 2, old_mousemode_t)
#define OLD_MOUSE_SETMODE	_IOW('M', 3, old_mousemode_t)

typedef struct old_mousehw {
    int buttons;
    int iftype;
    int type;
    int hwid;
} old_mousehw_t;

typedef struct old_mousemode {
    int protocol;
    int rate;
    int resolution;
    int accelfactor;
} old_mousemode_t;

/* packet formatting function */
typedef int packetfunc_t(struct psm_softc *, unsigned char *,
			      int *, int, mousestatus_t *);

/* function prototypes */
static void psmidentify(driver_t *, device_t);
static int psmprobe(device_t);
static int psmattach(device_t);
static int psmdetach(device_t);
static int psmresume(device_t);

static d_open_t psmopen;
static d_close_t psmclose;
static d_read_t psmread;
static d_ioctl_t psmioctl;
static d_poll_t psmpoll;

static int enable_aux_dev(KBDC);
static int disable_aux_dev(KBDC);
static int get_mouse_status(KBDC, int *, int, int);
static int get_aux_id(KBDC);
static int set_mouse_sampling_rate(KBDC, int);
static int set_mouse_scaling(KBDC, int);
static int set_mouse_resolution(KBDC, int);
static int set_mouse_mode(KBDC);
static int get_mouse_buttons(KBDC);
static int is_a_mouse(int);
static void recover_from_error(KBDC);
static int restore_controller(KBDC, int);
static int doinitialize(struct psm_softc *, mousemode_t *);
static int doopen(struct psm_softc *, int);
static int reinitialize(struct psm_softc *, int);
static char *model_name(int);
static void psmsoftintr(void *);
static void psmintr(void *);
static void psmtimeout(void *);
static int timeelapsed(const struct timeval *,
    int, int, const struct timeval *);
static void dropqueue(struct psm_softc *);
static void flushpackets(struct psm_softc *);

/* vendor specific features */
typedef int probefunc_t(struct psm_softc *);

static int mouse_id_proc1(KBDC, int, int, int *);
static int mouse_ext_command(KBDC, int);
static probefunc_t enable_groller;
static probefunc_t enable_gmouse;
static probefunc_t enable_aglide; 
static probefunc_t enable_kmouse;
static probefunc_t enable_msexplorer;
static probefunc_t enable_msintelli;
static probefunc_t enable_4dmouse;
static probefunc_t enable_4dplus;
static probefunc_t enable_mmanplus;
static probefunc_t enable_versapad;
static int tame_mouse(struct psm_softc *, packetbuf_t *, mousestatus_t *, unsigned char *);

static struct {
    int                 model;
    unsigned char	syncmask;
    int 		packetsize;
    probefunc_t 	*probefunc;
} vendortype[] = {
    /*
     * WARNING: the order of probe is very important.  Don't mess it
     * unless you know what you are doing.
     */
    { MOUSE_MODEL_NET,			/* Genius NetMouse */
      0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_gmouse, },
    { MOUSE_MODEL_NETSCROLL,		/* Genius NetScroll */
      0xc8, 6, enable_groller, },
    { MOUSE_MODEL_MOUSEMANPLUS,		/* Logitech MouseMan+ */
      0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus, },
    { MOUSE_MODEL_EXPLORER,		/* Microsoft IntelliMouse Explorer */
      0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msexplorer, },
    { MOUSE_MODEL_4D,			/* A4 Tech 4D Mouse */
      0x08, MOUSE_4D_PACKETSIZE, enable_4dmouse, },
    { MOUSE_MODEL_4DPLUS,		/* A4 Tech 4D+ Mouse */
      0xc8, MOUSE_4DPLUS_PACKETSIZE, enable_4dplus, },
    { MOUSE_MODEL_INTELLI,		/* Microsoft IntelliMouse */
      0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msintelli, },
    { MOUSE_MODEL_GLIDEPOINT,		/* ALPS GlidePoint */
      0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide, },
    { MOUSE_MODEL_THINK,		/* Kensignton ThinkingMouse */
      0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse, },
    { MOUSE_MODEL_VERSAPAD,		/* Interlink electronics VersaPad */
      0xe8, MOUSE_PS2VERSA_PACKETSIZE, enable_versapad, },
    { MOUSE_MODEL_GENERIC,
      0xc0, MOUSE_PS2_PACKETSIZE, NULL, },
};
#define GENERIC_MOUSE_ENTRY	((sizeof(vendortype) / sizeof(*vendortype)) - 1)

/* device driver declarateion */
static device_method_t psm_methods[] = {
	/* Device interface */
	DEVMETHOD(device_identify,	psmidentify),
	DEVMETHOD(device_probe,		psmprobe),
	DEVMETHOD(device_attach,	psmattach),
	DEVMETHOD(device_detach,	psmdetach),
	DEVMETHOD(device_resume,	psmresume),

	{ 0, 0 }
};

static driver_t psm_driver = {
    PSM_DRIVER_NAME,
    psm_methods,
    sizeof(struct psm_softc),
};


static struct cdevsw psm_cdevsw = {
	.d_version =	D_VERSION,
	.d_flags =	D_NEEDGIANT,
	.d_open =	psmopen,
	.d_close =	psmclose,
	.d_read =	psmread,
	.d_ioctl =	psmioctl,
	.d_poll =	psmpoll,
	.d_name =	PSM_DRIVER_NAME,
};

/* debug message level */
static int verbose = PSM_DEBUG;

/* device I/O routines */
static int
enable_aux_dev(KBDC kbdc)
{
    int res;

    res = send_aux_command(kbdc, PSMC_ENABLE_DEV);
    if (verbose >= 2)
        log(LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res);

    return (res == PSM_ACK);
}

static int
disable_aux_dev(KBDC kbdc)
{
    int res;

    res = send_aux_command(kbdc, PSMC_DISABLE_DEV);
    if (verbose >= 2)
        log(LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res);

    return (res == PSM_ACK);
}

static int
get_mouse_status(KBDC kbdc, int *status, int flag, int len)
{
    int cmd;
    int res;
    int i;

    switch (flag) {
    case 0:
    default:
	cmd = PSMC_SEND_DEV_STATUS;
	break;
    case 1:
	cmd = PSMC_SEND_DEV_DATA;
	break;
    }
    empty_aux_buffer(kbdc, 5);
    res = send_aux_command(kbdc, cmd);
    if (verbose >= 2)
        log(LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n", 
	    (flag == 1) ? "DATA" : "STATUS", res);
    if (res != PSM_ACK)
        return 0;

    for (i = 0; i < len; ++i) {
        status[i] = read_aux_data(kbdc);
	if (status[i] < 0)
	    break;
    }

    if (verbose) {
        log(LOG_DEBUG, "psm: %s %02x %02x %02x\n",
            (flag == 1) ? "data" : "status", status[0], status[1], status[2]);
    }

    return i;
}

static int
get_aux_id(KBDC kbdc)
{
    int res;
    int id;

    empty_aux_buffer(kbdc, 5);
    res = send_aux_command(kbdc, PSMC_SEND_DEV_ID);
    if (verbose >= 2)
        log(LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res);
    if (res != PSM_ACK)
	return (-1);

    /* 10ms delay */
    DELAY(10000);

    id = read_aux_data(kbdc);
    if (verbose >= 2)
        log(LOG_DEBUG, "psm: device ID: %04x\n", id);

    return id;
}

static int
set_mouse_sampling_rate(KBDC kbdc, int rate)
{
    int res;

    res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate);
    if (verbose >= 2)
        log(LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res);

    return ((res == PSM_ACK) ? rate : -1);
}

static int
set_mouse_scaling(KBDC kbdc, int scale)
{
    int res;

    switch (scale) {
    case 1:
    default:
	scale = PSMC_SET_SCALING11;
	break;
    case 2:
	scale = PSMC_SET_SCALING21;
	break;
    }
    res = send_aux_command(kbdc, scale);
    if (verbose >= 2)
        log(LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n", 
	    (scale == PSMC_SET_SCALING21) ? "21" : "11", res);

    return (res == PSM_ACK);
}

/* `val' must be 0 through PSMD_MAX_RESOLUTION */
static int
set_mouse_resolution(KBDC kbdc, int val)
{
    int res;

    res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val);
    if (verbose >= 2)
        log(LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res);

    return ((res == PSM_ACK) ? val : -1);
}

/*
 * NOTE: once `set_mouse_mode()' is called, the mouse device must be
 * re-enabled by calling `enable_aux_dev()'
 */
static int
set_mouse_mode(KBDC kbdc)
{
    int res;

    res = send_aux_command(kbdc, PSMC_SET_STREAM_MODE);
    if (verbose >= 2)
        log(LOG_DEBUG, "psm: SET_STREAM_MODE return code:%04x\n", res);

    return (res == PSM_ACK);
}

static int
get_mouse_buttons(KBDC kbdc)
{
    int c = 2;		/* assume two buttons by default */
    int status[3];

    /*
     * NOTE: a special sequence to obtain Logitech Mouse specific
     * information: set resolution to 25 ppi, set scaling to 1:1, set
     * scaling to 1:1, set scaling to 1:1. Then the second byte of the
     * mouse status bytes is the number of available buttons.
     * Some manufactures also support this sequence.
     */
    if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
        return c;
    if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1)
        && set_mouse_scaling(kbdc, 1) 
	&& (get_mouse_status(kbdc, status, 0, 3) >= 3)) {
        if (status[1] != 0)
            return status[1];
    }
    return c;
}

/* misc subroutines */
/*
 * Someday, I will get the complete list of valid pointing devices and
 * their IDs... XXX
 */
static int
is_a_mouse(int id)
{
#if 0
    static int valid_ids[] = {
        PSM_MOUSE_ID,		/* mouse */
        PSM_BALLPOINT_ID,	/* ballpoint device */
        PSM_INTELLI_ID,		/* Intellimouse */
        PSM_EXPLORER_ID,	/* Intellimouse Explorer */
        -1			/* end of table */
    };
    int i;

    for (i = 0; valid_ids[i] >= 0; ++i)
        if (valid_ids[i] == id)
            return TRUE;
    return FALSE;
#else
    return TRUE;
#endif
}

static char *
model_name(int model)
{
    static struct {
	int model_code;
	char *model_name;
    } models[] = {
        { MOUSE_MODEL_NETSCROLL,	"NetScroll" },
        { MOUSE_MODEL_NET,		"NetMouse/NetScroll Optical" },
        { MOUSE_MODEL_GLIDEPOINT,	"GlidePoint" },
        { MOUSE_MODEL_THINK,		"ThinkingMouse" },
        { MOUSE_MODEL_INTELLI,		"IntelliMouse" },
        { MOUSE_MODEL_MOUSEMANPLUS,	"MouseMan+" },
        { MOUSE_MODEL_VERSAPAD,		"VersaPad" },
        { MOUSE_MODEL_EXPLORER,		"IntelliMouse Explorer" },
        { MOUSE_MODEL_4D,		"4D Mouse" },
        { MOUSE_MODEL_4DPLUS,		"4D+ Mouse" },
        { MOUSE_MODEL_GENERIC,		"Generic PS/2 mouse" },
        { MOUSE_MODEL_UNKNOWN,		NULL },
    };
    int i;

    for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i) {
	if (models[i].model_code == model)
	    return models[i].model_name;
    }
    return "Unknown";
}

static void
recover_from_error(KBDC kbdc)
{
    /* discard anything left in the output buffer */
    empty_both_buffers(kbdc, 10);

#if 0
    /*
     * NOTE: KBDC_RESET_KBD may not restore the communication between the
     * keyboard and the controller.
     */
    reset_kbd(kbdc);
#else
    /*
     * NOTE: somehow diagnostic and keyboard port test commands bring the
     * keyboard back.
     */
    if (!test_controller(kbdc)) 
        log(LOG_ERR, "psm: keyboard controller failed.\n");
    /* if there isn't a keyboard in the system, the following error is OK */
    if (test_kbd_port(kbdc) != 0) {
	if (verbose)
	    log(LOG_ERR, "psm: keyboard port failed.\n");
    }
#endif
}

static int
restore_controller(KBDC kbdc, int command_byte)
{
    empty_both_buffers(kbdc, 10);

    if (!set_controller_command_byte(kbdc, 0xff, command_byte)) {
	log(LOG_ERR, "psm: failed to restore the keyboard controller "
		     "command byte.\n");
	empty_both_buffers(kbdc, 10);
	return FALSE;
    } else {
	empty_both_buffers(kbdc, 10);
	return TRUE;
    }
}

/* 
 * Re-initialize the aux port and device. The aux port must be enabled
 * and its interrupt must be disabled before calling this routine. 
 * The aux device will be disabled before returning.
 * The keyboard controller must be locked via `kbdc_lock()' before
 * calling this routine.
 */
static int
doinitialize(struct psm_softc *sc, mousemode_t *mode)
{
    KBDC kbdc = sc->kbdc;
    int stat[3];
    int i;

    switch((i = test_aux_port(kbdc))) {
    case 1:	/* ignore this error */
    case PSM_ACK:
	if (verbose)
	    log(LOG_DEBUG, "psm%d: strange result for test aux port (%d).\n",
	        sc->unit, i);
	/* FALLTHROUGH */
    case 0:	/* no error */
    	break;
    case -1: 	/* time out */
    default: 	/* error */
    	recover_from_error(kbdc);
	if (sc->config & PSM_CONFIG_IGNPORTERROR)
	    break;
    	log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n",
    	    sc->unit, i);
    	return FALSE;
    }

    if (sc->config & PSM_CONFIG_NORESET) {
	/* 
	 * Don't try to reset the pointing device.  It may possibly be
	 * left in the unknown state, though...
	 */
    } else {
	/* 
	 * NOTE: some controllers appears to hang the `keyboard' when
	 * the aux port doesn't exist and `PSMC_RESET_DEV' is issued. 
	 */
	if (!reset_aux_dev(kbdc)) {
            recover_from_error(kbdc);
            log(LOG_ERR, "psm%d: failed to reset the aux device.\n", sc->unit);
            return FALSE;
	}
    }

    /* 
     * both the aux port and the aux device is functioning, see
     * if the device can be enabled. 
     */
    if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
        log(LOG_ERR, "psm%d: failed to enable the aux device.\n", sc->unit);
        return FALSE;
    }
    empty_both_buffers(kbdc, 10);	/* remove stray data if any */

    if (sc->config & PSM_CONFIG_NOIDPROBE) {
	i = GENERIC_MOUSE_ENTRY;
    } else {
	/* FIXME: hardware ID, mouse buttons? */

	/* other parameters */
	for (i = 0; vendortype[i].probefunc != NULL; ++i) {
	    if ((*vendortype[i].probefunc)(sc)) {
		if (verbose >= 2)
		    log(LOG_ERR, "psm%d: found %s\n", 
			sc->unit, model_name(vendortype[i].model));
		break;
	    }
	}
    }

    sc->hw.model = vendortype[i].model;
    sc->mode.packetsize = vendortype[i].packetsize;

    /* set mouse parameters */
    if (mode != (mousemode_t *)NULL) {
	if (mode->rate > 0)
            mode->rate = set_mouse_sampling_rate(kbdc, mode->rate);
	if (mode->resolution >= 0)
            mode->resolution = set_mouse_resolution(kbdc, mode->resolution);
        set_mouse_scaling(kbdc, 1);
        set_mouse_mode(kbdc);	
    }

    /* request a data packet and extract sync. bits */
    if (get_mouse_status(kbdc, stat, 1, 3) < 3) {
        log(LOG_DEBUG, "psm%d: failed to get data (doinitialize).\n",
	    sc->unit);
        sc->mode.syncmask[0] = 0;
    } else {
        sc->mode.syncmask[1] = stat[0] & sc->mode.syncmask[0];	/* syncbits */
	/* the NetScroll Mouse will send three more bytes... Ignore them */
	empty_aux_buffer(kbdc, 5);
    }

    /* just check the status of the mouse */
    if (get_mouse_status(kbdc, stat, 0, 3) < 3)
        log(LOG_DEBUG, "psm%d: failed to get status (doinitialize).\n",
	    sc->unit);

    return TRUE;
}

static int
doopen(struct psm_softc *sc, int command_byte)
{
    int stat[3];

    /* enable the mouse device */
    if (!enable_aux_dev(sc->kbdc)) {
	/* MOUSE ERROR: failed to enable the mouse because:
	 * 1) the mouse is faulty,
	 * 2) the mouse has been removed(!?)
	 * In the latter case, the keyboard may have hung, and need 
	 * recovery procedure...
	 */
	recover_from_error(sc->kbdc);
#if 0
	/* FIXME: we could reset the mouse here and try to enable
	 * it again. But it will take long time and it's not a good
	 * idea to disable the keyboard that long...
	 */
	if (!doinitialize(sc, &sc->mode) || !enable_aux_dev(sc->kbdc)) {
	    recover_from_error(sc->kbdc);
#else
        {
#endif
            restore_controller(sc->kbdc, command_byte);
	    /* mark this device is no longer available */
	    sc->state &= ~PSM_VALID;	
	    log(LOG_ERR, "psm%d: failed to enable the device (doopen).\n",
		sc->unit);
	    return (EIO);
	}
    }

    if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3) 
        log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n", sc->unit);

    /* enable the aux port and interrupt */
    if (!set_controller_command_byte(sc->kbdc, 
	    kbdc_get_device_mask(sc->kbdc),
	    (command_byte & KBD_KBD_CONTROL_BITS)
		| KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) {
	/* CONTROLLER ERROR */
	disable_aux_dev(sc->kbdc);
        restore_controller(sc->kbdc, command_byte);
	log(LOG_ERR, "psm%d: failed to enable the aux interrupt (doopen).\n",
	    sc->unit);
	return (EIO);
    }

    /* start the watchdog timer */
    sc->watchdog = FALSE;
    sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz*2);

    return (0);
}

static int
reinitialize(struct psm_softc *sc, int doinit)
{
    int err;
    int c;
    int s;

    /* don't let anybody mess with the aux device */
    if (!kbdc_lock(sc->kbdc, TRUE))
	return (EIO);
    s = spltty();

    /* block our watchdog timer */
    sc->watchdog = FALSE;
    untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
    callout_handle_init(&sc->callout);

    /* save the current controller command byte */
    empty_both_buffers(sc->kbdc, 10);
    c = get_controller_command_byte(sc->kbdc);
    if (verbose >= 2)
        log(LOG_DEBUG, "psm%d: current command byte: %04x (reinitialize).\n", 
	    sc->unit, c);

    /* enable the aux port but disable the aux interrupt and the keyboard */
    if ((c == -1) || !set_controller_command_byte(sc->kbdc,
	    kbdc_get_device_mask(sc->kbdc),
  	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
        /* CONTROLLER ERROR */
	splx(s);
        kbdc_lock(sc->kbdc, FALSE);
	log(LOG_ERR, "psm%d: unable to set the command byte (reinitialize).\n",
	    sc->unit);
	return (EIO);
    }

    /* flush any data */
    if (sc->state & PSM_VALID) {
	disable_aux_dev(sc->kbdc);	/* this may fail; but never mind... */
	empty_aux_buffer(sc->kbdc, 10);
    }
    flushpackets(sc);
    sc->syncerrors = 0;

    /* try to detect the aux device; are you still there? */
    err = 0;
    if (doinit) {
	if (doinitialize(sc, &sc->mode)) {
	    /* yes */
	    sc->state |= PSM_VALID;
	} else {
	    /* the device has gone! */
	    restore_controller(sc->kbdc, c);
	    sc->state &= ~PSM_VALID;
	    log(LOG_ERR, "psm%d: the aux device has gone! (reinitialize).\n",
		sc->unit);
	    err = ENXIO;
	}
    }
    splx(s);

    /* restore the driver state */
    if ((sc->state & PSM_OPEN) && (err == 0)) {
        /* enable the aux device and the port again */
	err = doopen(sc, c);
	if (err != 0) 
	    log(LOG_ERR, "psm%d: failed to enable the device (reinitialize).\n",
		sc->unit);
    } else {
        /* restore the keyboard port and disable the aux port */
        if (!set_controller_command_byte(sc->kbdc, 
                kbdc_get_device_mask(sc->kbdc),
                (c & KBD_KBD_CONTROL_BITS)
                    | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
            /* CONTROLLER ERROR */
            log(LOG_ERR, "psm%d: failed to disable the aux port (reinitialize).\n",
                sc->unit);
            err = EIO;
	}
    }

    kbdc_lock(sc->kbdc, FALSE);
    return (err);
}

/* psm driver entry points */

static void
psmidentify(driver_t *driver, device_t parent)
{
    device_t psmc;
    device_t psm;
    u_long irq;
    int unit;

    unit = device_get_unit(parent);

    /* always add at least one child */
    psm = BUS_ADD_CHILD(parent, KBDC_RID_AUX, driver->name, unit);
    if (psm == NULL)
	return;

    irq = bus_get_resource_start(psm, SYS_RES_IRQ, KBDC_RID_AUX);
    if (irq > 0)
	return;

    /*
     * If the PS/2 mouse device has already been reported by ACPI or
     * PnP BIOS, obtain the IRQ resource from it.
     * (See psmcpnp_attach() below.)
     */
    psmc = device_find_child(device_get_parent(parent),
			     PSMCPNP_DRIVER_NAME, unit);
    if (psmc == NULL)
	return;
    irq = bus_get_resource_start(psmc, SYS_RES_IRQ, 0);
    if (irq <= 0)
	return;
    bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
}

#define endprobe(v)	do {   if (bootverbose)				\
				--verbose;   				\
                            kbdc_set_device_mask(sc->kbdc, mask);	\
			    kbdc_lock(sc->kbdc, FALSE);			\
			    return (v);	     				\
			} while (0)

static int
psmprobe(device_t dev)
{
    int unit = device_get_unit(dev);
    struct psm_softc *sc = device_get_softc(dev);
    int stat[3];
    int command_byte;
    int mask;
    int rid;
    int i;

#if 0
    kbdc_debug(TRUE);
#endif

    /* see if IRQ is available */
    rid = KBDC_RID_AUX;
    sc->intr = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0, ~0, 1,
				  RF_SHAREABLE | RF_ACTIVE);
    if (sc->intr == NULL) {
	if (bootverbose)
            device_printf(dev, "unable to allocate IRQ\n");
        return (ENXIO);
    }
    bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);

    sc->unit = unit;
    sc->kbdc = atkbdc_open(device_get_unit(device_get_parent(dev)));
    sc->config = device_get_flags(dev) & PSM_CONFIG_FLAGS;
    /* XXX: for backward compatibility */
#if defined(PSM_HOOKRESUME) || defined(PSM_HOOKAPM)
    sc->config |= 
#ifdef PSM_RESETAFTERSUSPEND
	PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
#else
	PSM_CONFIG_HOOKRESUME;
#endif
#endif /* PSM_HOOKRESUME | PSM_HOOKAPM */
    sc->flags = 0;
    if (bootverbose)
        ++verbose;

    device_set_desc(dev, "PS/2 Mouse");

    if (!kbdc_lock(sc->kbdc, TRUE)) {
        printf("psm%d: unable to lock the controller.\n", unit);
        if (bootverbose)
            --verbose;
	return (ENXIO);
    }

    /*
     * NOTE: two bits in the command byte controls the operation of the
     * aux port (mouse port): the aux port disable bit (bit 5) and the aux
     * port interrupt (IRQ 12) enable bit (bit 2).
     */

    /* discard anything left after the keyboard initialization */
    empty_both_buffers(sc->kbdc, 10);

    /* save the current command byte; it will be used later */
    mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS;
    command_byte = get_controller_command_byte(sc->kbdc);
    if (verbose) 
        printf("psm%d: current command byte:%04x\n", unit, command_byte);
    if (command_byte == -1) {
        /* CONTROLLER ERROR */
        printf("psm%d: unable to get the current command byte value.\n",
            unit);
        endprobe(ENXIO);
    }

    /*
     * disable the keyboard port while probing the aux port, which must be
     * enabled during this routine
     */
    if (!set_controller_command_byte(sc->kbdc,
	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
  	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
                | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
        /* 
	 * this is CONTROLLER ERROR; I don't know how to recover 
         * from this error... 
	 */
        restore_controller(sc->kbdc, command_byte);
        printf("psm%d: unable to set the command byte.\n", unit);
        endprobe(ENXIO);
    }
    write_controller_command(sc->kbdc, KBDC_ENABLE_AUX_PORT);

    /*
     * NOTE: `test_aux_port()' is designed to return with zero if the aux
     * port exists and is functioning. However, some controllers appears
     * to respond with zero even when the aux port doesn't exist. (It may
     * be that this is only the case when the controller DOES have the aux
     * port but the port is not wired on the motherboard.) The keyboard
     * controllers without the port, such as the original AT, are
     * supporsed to return with an error code or simply time out. In any
     * case, we have to continue probing the port even when the controller
     * passes this test.
     *
     * XXX: some controllers erroneously return the error code 1 when
     * it has the perfectly functional aux port. We have to ignore this
     * error code. Even if the controller HAS error with the aux port,
     * it will be detected later...
     * XXX: another incompatible controller returns PSM_ACK (0xfa)...
     */
    switch ((i = test_aux_port(sc->kbdc))) {
    case 1:	   /* ignore this error */
    case PSM_ACK:
        if (verbose)
	    printf("psm%d: strange result for test aux port (%d).\n",
	        unit, i);
	/* FALLTHROUGH */
    case 0:        /* no error */
        break;
    case -1:        /* time out */
    default:        /* error */
        recover_from_error(sc->kbdc);
	if (sc->config & PSM_CONFIG_IGNPORTERROR)
	    break;
        restore_controller(sc->kbdc, command_byte);
        if (verbose)
            printf("psm%d: the aux port is not functioning (%d).\n",
                unit, i);
        endprobe(ENXIO);
    }

    if (sc->config & PSM_CONFIG_NORESET) {
	/* 
	 * Don't try to reset the pointing device.  It may possibly be
	 * left in the unknown state, though...
	 */
    } else {
	/*
	 * NOTE: some controllers appears to hang the `keyboard' when the aux
	 * port doesn't exist and `PSMC_RESET_DEV' is issued.
	 *
	 * Attempt to reset the controller twice -- this helps
	 * pierce through some KVM switches. The second reset
	 * is non-fatal.
	 */
	if (!reset_aux_dev(sc->kbdc)) {
            recover_from_error(sc->kbdc);
            restore_controller(sc->kbdc, command_byte);
            if (verbose)
        	printf("psm%d: failed to reset the aux device.\n", unit);
            endprobe(ENXIO);
	} else if (!reset_aux_dev(sc->kbdc)) {
	    recover_from_error(sc->kbdc);
	    if (verbose >= 2)
        	printf("psm%d: failed to reset the aux device (2).\n",
        	    unit);
	}
    }

    /*
     * both the aux port and the aux device is functioning, see if the
     * device can be enabled. NOTE: when enabled, the device will start
     * sending data; we shall immediately disable the device once we know
     * the device can be enabled.
     */
    if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
        /* MOUSE ERROR */
	recover_from_error(sc->kbdc);
	restore_controller(sc->kbdc, command_byte);
	if (verbose)
	    printf("psm%d: failed to enable the aux device.\n", unit);
        endprobe(ENXIO);
    }

    /* save the default values after reset */
    if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
	sc->dflt_mode.rate = sc->mode.rate = stat[2];
	sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
    } else {
	sc->dflt_mode.rate = sc->mode.rate = -1;
	sc->dflt_mode.resolution = sc->mode.resolution = -1;
    }

    /* hardware information */
    sc->hw.iftype = MOUSE_IF_PS2;

    /* verify the device is a mouse */
    sc->hw.hwid = get_aux_id(sc->kbdc);
    if (!is_a_mouse(sc->hw.hwid)) {
        restore_controller(sc->kbdc, command_byte);
        if (verbose)
            printf("psm%d: unknown device type (%d).\n", unit, sc->hw.hwid);
        endprobe(ENXIO);
    }
    switch (sc->hw.hwid) {
    case PSM_BALLPOINT_ID:
        sc->hw.type = MOUSE_TRACKBALL;
        break;
    case PSM_MOUSE_ID:
    case PSM_INTELLI_ID:
    case PSM_EXPLORER_ID:
    case PSM_4DMOUSE_ID:
    case PSM_4DPLUS_ID:
        sc->hw.type = MOUSE_MOUSE;
        break;
    default:
        sc->hw.type = MOUSE_UNKNOWN;
        break;
    }

    if (sc->config & PSM_CONFIG_NOIDPROBE) {
	sc->hw.buttons = 2;
	i = GENERIC_MOUSE_ENTRY;
    } else {
	/* # of buttons */
	sc->hw.buttons = get_mouse_buttons(sc->kbdc);

	/* other parameters */
	for (i = 0; vendortype[i].probefunc != NULL; ++i) {
	    if ((*vendortype[i].probefunc)(sc)) {
		if (verbose >= 2)
		    printf("psm%d: found %s\n",
			   unit, model_name(vendortype[i].model));
		break;
	    }
	}
    }

    sc->hw.model = vendortype[i].model;

    sc->dflt_mode.level = PSM_LEVEL_BASE;
    sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
    sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
    if (sc->config & PSM_CONFIG_NOCHECKSYNC)
        sc->dflt_mode.syncmask[0] = 0;
    else
        sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
    if (sc->config & PSM_CONFIG_FORCETAP)
        sc->mode.syncmask[0] &= ~MOUSE_PS2_TAP;
    sc->dflt_mode.syncmask[1] = 0;	/* syncbits */
    sc->mode = sc->dflt_mode;
    sc->mode.packetsize = vendortype[i].packetsize;

    /* set mouse parameters */
#if 0
    /* 
     * A version of Logitech FirstMouse+ won't report wheel movement,
     * if SET_DEFAULTS is sent...  Don't use this command.
     * This fix was found by Takashi Nishida.
     */
    i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
    if (verbose >= 2)
	printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
#endif
    if (sc->config & PSM_CONFIG_RESOLUTION) {
        sc->mode.resolution
	    = set_mouse_resolution(sc->kbdc, 
				   (sc->config & PSM_CONFIG_RESOLUTION) - 1);
    } else if (sc->mode.resolution >= 0) {
	sc->mode.resolution
	    = set_mouse_resolution(sc->kbdc, sc->dflt_mode.resolution);
    }
    if (sc->mode.rate > 0) {
	sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, sc->dflt_mode.rate);
    }
    set_mouse_scaling(sc->kbdc, 1);

    /* request a data packet and extract sync. bits */
    if (get_mouse_status(sc->kbdc, stat, 1, 3) < 3) {
        printf("psm%d: failed to get data.\n", unit);
        sc->mode.syncmask[0] = 0;
    } else {
        sc->mode.syncmask[1] = stat[0] & sc->mode.syncmask[0];	/* syncbits */
	/* the NetScroll Mouse will send three more bytes... Ignore them */
	empty_aux_buffer(sc->kbdc, 5);
    }

    /* just check the status of the mouse */
    /* 
     * NOTE: XXX there are some arcane controller/mouse combinations out 
     * there, which hung the controller unless there is data transmission 
     * after ACK from the mouse.
     */
    if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3) {
        printf("psm%d: failed to get status.\n", unit);
    } else {
	/* 
	 * When in its native mode, some mice operate with different 
	 * default parameters than in the PS/2 compatible mode.
	 */
        sc->dflt_mode.rate = sc->mode.rate = stat[2];
        sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
     }

    /* disable the aux port for now... */
    if (!set_controller_command_byte(sc->kbdc, 
	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
            (command_byte & KBD_KBD_CONTROL_BITS)
                | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
        /* 
	 * this is CONTROLLER ERROR; I don't know the proper way to 
         * recover from this error... 
	 */
        restore_controller(sc->kbdc, command_byte);
        printf("psm%d: unable to set the command byte.\n", unit);
        endprobe(ENXIO);
    }

    /* done */
    kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
    kbdc_lock(sc->kbdc, FALSE);
    return (0);
}

static int
psmattach(device_t dev)
{
    int unit = device_get_unit(dev);
    struct psm_softc *sc = device_get_softc(dev);
    int error;
    int rid;

    if (sc == NULL)    /* shouldn't happen */
	return (ENXIO);

    /* Setup initial state */
    sc->state = PSM_VALID;
    callout_handle_init(&sc->callout);

    /* Setup our interrupt handler */
    rid = KBDC_RID_AUX;
    sc->intr = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0, ~0, 1,
				  RF_SHAREABLE | RF_ACTIVE);
    if (sc->intr == NULL)
	return (ENXIO);
    error = bus_setup_intr(dev, sc->intr, INTR_TYPE_TTY, psmintr, sc, &sc->ih);
    if (error) {
	bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
	return (error);
    }

    /* Done */
    sc->dev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, FALSE), 0, 0, 0666,
		       "psm%d", unit);
    sc->bdev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, TRUE), 0, 0, 0666,
			"bpsm%d", unit);

    if (!verbose) {
        printf("psm%d: model %s, device ID %d\n", 
	    unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff);
    } else {
        printf("psm%d: model %s, device ID %d-%02x, %d buttons\n",
	    unit, model_name(sc->hw.model),
	    sc->hw.hwid & 0x00ff, sc->hw.hwid >> 8, sc->hw.buttons);
	printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
	    unit, sc->config, sc->flags, sc->mode.packetsize);
	printf("psm%d: syncmask:%02x, syncbits:%02x\n",
	    unit, sc->mode.syncmask[0], sc->mode.syncmask[1]);
    }

    if (bootverbose)
        --verbose;

    return (0);
}

static int
psmdetach(device_t dev)
{
    struct psm_softc *sc;
    int rid;

    sc = device_get_softc(dev);
    if (sc->state & PSM_OPEN)
	return EBUSY;

    rid = KBDC_RID_AUX;
    bus_teardown_intr(dev, sc->intr, sc->ih);
    bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);

    destroy_dev(sc->dev);
    destroy_dev(sc->bdev);

    return 0;
}

static int
psmopen(dev_t dev, int flag, int fmt, struct thread *td)
{
    int unit = PSM_UNIT(dev);
    struct psm_softc *sc;
    int command_byte;
    int err;
    int s;

    /* Get device data */
    sc = PSM_SOFTC(unit);
    if ((sc == NULL) || (sc->state & PSM_VALID) == 0)
	/* the device is no longer valid/functioning */
        return (ENXIO);

    /* Disallow multiple opens */
    if (sc->state & PSM_OPEN)
        return (EBUSY);

    device_busy(devclass_get_device(psm_devclass, unit));

    /* Initialize state */
    sc->mode.level = sc->dflt_mode.level;
    sc->mode.protocol = sc->dflt_mode.protocol;
    sc->watchdog = FALSE;

    /* flush the event queue */
    sc->queue.count = 0;
    sc->queue.head = 0;
    sc->queue.tail = 0;
    sc->status.flags = 0;
    sc->status.button = 0;
    sc->status.obutton = 0;
    sc->status.dx = 0;
    sc->status.dy = 0;
    sc->status.dz = 0;
    sc->button = 0;
    sc->pqueue_start = 0;
    sc->pqueue_end = 0;

    /* empty input buffer */
    flushpackets(sc);
    sc->syncerrors = 0;

    /* don't let timeout routines in the keyboard driver to poll the kbdc */
    if (!kbdc_lock(sc->kbdc, TRUE))
	return (EIO);

    /* save the current controller command byte */
    s = spltty();
    command_byte = get_controller_command_byte(sc->kbdc);

    /* enable the aux port and temporalily disable the keyboard */
    if ((command_byte == -1) 
        || !set_controller_command_byte(sc->kbdc,
	    kbdc_get_device_mask(sc->kbdc),
  	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
        /* CONTROLLER ERROR; do you know how to get out of this? */
        kbdc_lock(sc->kbdc, FALSE);
	splx(s);
	log(LOG_ERR, "psm%d: unable to set the command byte (psmopen).\n",
	    unit);
	return (EIO);
    }
    /* 
     * Now that the keyboard controller is told not to generate 
     * the keyboard and mouse interrupts, call `splx()' to allow 
     * the other tty interrupts. The clock interrupt may also occur, 
     * but timeout routines will be blocked by the poll flag set 
     * via `kbdc_lock()'
     */
    splx(s);
  
    /* enable the mouse device */
    err = doopen(sc, command_byte);

    /* done */
    if (err == 0) 
        sc->state |= PSM_OPEN;
    kbdc_lock(sc->kbdc, FALSE);
    return (err);
}

static int
psmclose(dev_t dev, int flag, int fmt, struct thread *td)
{
    int unit = PSM_UNIT(dev);
    struct psm_softc *sc = PSM_SOFTC(unit);
    int stat[3];
    int command_byte;
    int s;

    /* don't let timeout routines in the keyboard driver to poll the kbdc */
    if (!kbdc_lock(sc->kbdc, TRUE))
	return (EIO);

    /* save the current controller command byte */
    s = spltty();
    command_byte = get_controller_command_byte(sc->kbdc);
    if (command_byte == -1) {
        kbdc_lock(sc->kbdc, FALSE);
	splx(s);
	return (EIO);
    }

    /* disable the aux interrupt and temporalily disable the keyboard */
    if (!set_controller_command_byte(sc->kbdc, 
	    kbdc_get_device_mask(sc->kbdc),
  	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
	log(LOG_ERR, "psm%d: failed to disable the aux int (psmclose).\n",
	    unit);
	/* CONTROLLER ERROR;
	 * NOTE: we shall force our way through. Because the only
	 * ill effect we shall see is that we may not be able
	 * to read ACK from the mouse, and it doesn't matter much 
	 * so long as the mouse will accept the DISABLE command.
	 */
    }
    splx(s);

    /* stop the watchdog timer */
    untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
    callout_handle_init(&sc->callout);

    /* remove anything left in the output buffer */
    empty_aux_buffer(sc->kbdc, 10);

    /* disable the aux device, port and interrupt */
    if (sc->state & PSM_VALID) {
        if (!disable_aux_dev(sc->kbdc)) {
	    /* MOUSE ERROR; 
	     * NOTE: we don't return error and continue, pretending 
	     * we have successfully disabled the device. It's OK because 
	     * the interrupt routine will discard any data from the mouse
	     * hereafter. 
	     */
	    log(LOG_ERR, "psm%d: failed to disable the device (psmclose).\n",
		unit);
        }

        if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
            log(LOG_DEBUG, "psm%d: failed to get status (psmclose).\n", 
		unit);
    }

    if (!set_controller_command_byte(sc->kbdc, 
	    kbdc_get_device_mask(sc->kbdc),
	    (command_byte & KBD_KBD_CONTROL_BITS)
	        | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
	/* CONTROLLER ERROR; 
	 * we shall ignore this error; see the above comment.
	 */
	log(LOG_ERR, "psm%d: failed to disable the aux port (psmclose).\n",
	    unit);
    }

    /* remove anything left in the output buffer */
    empty_aux_buffer(sc->kbdc, 10);

    /* close is almost always successful */
    sc->state &= ~PSM_OPEN;
    kbdc_lock(sc->kbdc, FALSE);
    device_unbusy(devclass_get_device(psm_devclass, unit));
    return (0);
}

static int
tame_mouse(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *status, unsigned char *buf)
{
    static unsigned char butmapps2[8] = {
        0,
        MOUSE_PS2_BUTTON1DOWN, 
        MOUSE_PS2_BUTTON2DOWN,
        MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
        MOUSE_PS2_BUTTON3DOWN,
        MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
        MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
        MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
    };
    static unsigned char butmapmsc[8] = {
        MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
        MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
        MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
        MOUSE_MSC_BUTTON3UP,
        MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
        MOUSE_MSC_BUTTON2UP,
        MOUSE_MSC_BUTTON1UP, 
        0,
    };
    int mapped;
    int i;

    if (sc->mode.level == PSM_LEVEL_BASE) {
        mapped = status->button & ~MOUSE_BUTTON4DOWN;
        if (status->button & MOUSE_BUTTON4DOWN) 
	    mapped |= MOUSE_BUTTON1DOWN;
        status->button = mapped;
        buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
        i = imax(imin(status->dx, 255), -256);
	if (i < 0)
	    buf[0] |= MOUSE_PS2_XNEG;
        buf[1] = i;
        i = imax(imin(status->dy, 255), -256);
	if (i < 0)
	    buf[0] |= MOUSE_PS2_YNEG;
        buf[2] = i;
	return MOUSE_PS2_PACKETSIZE;
    } else if (sc->mode.level == PSM_LEVEL_STANDARD) {
        buf[0] = MOUSE_MSC_SYNC | butmapmsc[status->button & MOUSE_STDBUTTONS];
        i = imax(imin(status->dx, 255), -256);
        buf[1] = i >> 1;
        buf[3] = i - buf[1];
        i = imax(imin(status->dy, 255), -256);
        buf[2] = i >> 1;
        buf[4] = i - buf[2];
        i = imax(imin(status->dz, 127), -128);
        buf[5] = (i >> 1) & 0x7f;
        buf[6] = (i - (i >> 1)) & 0x7f;
        buf[7] = (~status->button >> 3) & 0x7f;
	return MOUSE_SYS_PACKETSIZE;
    }
    return pb->inputbytes;
}

static int
psmread(dev_t dev, struct uio *uio, int flag)
{
    register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
    unsigned char buf[PSM_SMALLBUFSIZE];
    int error = 0;
    int s;
    int l;

    if ((sc->state & PSM_VALID) == 0)
	return EIO;

    /* block until mouse activity occured */
    s = spltty();
    while (sc->queue.count <= 0) {
        if (PSM_NBLOCKIO(dev)) {
            splx(s);
            return EWOULDBLOCK;
        }
        sc->state |= PSM_ASLP;
        error = tsleep( sc, PZERO | PCATCH, "psmrea", 0);
        sc->state &= ~PSM_ASLP;
        if (error) {
            splx(s);
            return error;
        } else if ((sc->state & PSM_VALID) == 0) {
            /* the device disappeared! */
            splx(s);
            return EIO;
	}
    }
    splx(s);

    /* copy data to the user land */
    while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
        s = spltty();
	l = imin(sc->queue.count, uio->uio_resid);
	if (l > sizeof(buf))
	    l = sizeof(buf);
	if (l > sizeof(sc->queue.buf) - sc->queue.head) {
	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0], 
		sizeof(sc->queue.buf) - sc->queue.head);
	    bcopy(&sc->queue.buf[0], 
		&buf[sizeof(sc->queue.buf) - sc->queue.head],
		l - (sizeof(sc->queue.buf) - sc->queue.head));
	} else {
	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
	}
	sc->queue.count -= l;
	sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
        splx(s);
        error = uiomove(buf, l, uio);
        if (error)
	    break;
    }

    return error;
}

static int
block_mouse_data(struct psm_softc *sc, int *c)
{
    int s;

    if (!kbdc_lock(sc->kbdc, TRUE)) 
	return EIO;

    s = spltty();
    *c = get_controller_command_byte(sc->kbdc);
    if ((*c == -1) 
	|| !set_controller_command_byte(sc->kbdc, 
	    kbdc_get_device_mask(sc->kbdc),
            KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
                | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
        /* this is CONTROLLER ERROR */
	splx(s);
        kbdc_lock(sc->kbdc, FALSE);
	return EIO;
    }

    /* 
     * The device may be in the middle of status data transmission.
     * The transmission will be interrupted, thus, incomplete status 
     * data must be discarded. Although the aux interrupt is disabled 
     * at the keyboard controller level, at most one aux interrupt 
     * may have already been pending and a data byte is in the 
     * output buffer; throw it away. Note that the second argument 
     * to `empty_aux_buffer()' is zero, so that the call will just 
     * flush the internal queue.
     * `psmintr()' will be invoked after `splx()' if an interrupt is
     * pending; it will see no data and returns immediately.
     */
    empty_aux_buffer(sc->kbdc, 0);	/* flush the queue */
    read_aux_data_no_wait(sc->kbdc);	/* throw away data if any */
    flushpackets(sc);
    splx(s);

    return 0;
}

static void
dropqueue(struct psm_softc *sc)
{

    	sc->queue.count = 0;
   	sc->queue.head = 0;
    	sc->queue.tail = 0;
	if ((sc->state & PSM_SOFTARMED) != 0) {
		sc->state &= ~PSM_SOFTARMED;
		untimeout(psmsoftintr, (void *)(uintptr_t)sc, sc->softcallout);
	}
	sc->pqueue_start = sc->pqueue_end;
}

static void
flushpackets(struct psm_softc *sc)
{

	dropqueue(sc);
	bzero(&sc->pqueue, sizeof(sc->pqueue));
}

static int
unblock_mouse_data(struct psm_softc *sc, int c)
{
    int error = 0;

    /* 
     * We may have seen a part of status data during `set_mouse_XXX()'.
     * they have been queued; flush it.
     */
    empty_aux_buffer(sc->kbdc, 0);

    /* restore ports and interrupt */
    if (!set_controller_command_byte(sc->kbdc, 
            kbdc_get_device_mask(sc->kbdc),
	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
        /* CONTROLLER ERROR; this is serious, we may have
         * been left with the inaccessible keyboard and
         * the disabled mouse interrupt. 
         */
        error = EIO;
    }

    kbdc_lock(sc->kbdc, FALSE);
    return error;
}

static int
psmioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
{
    struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
    mousemode_t mode;
    mousestatus_t status;
#if (defined(MOUSE_GETVARS))
    mousevar_t *var;
#endif
    mousedata_t *data;
    int stat[3];
    int command_byte;
    int error = 0;
    int s;

    /* Perform IOCTL command */
    switch (cmd) {

    case OLD_MOUSE_GETHWINFO:
	s = spltty();
        ((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
        ((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
        ((old_mousehw_t *)addr)->type = sc->hw.type;
        ((old_mousehw_t *)addr)->hwid = sc->hw.hwid & 0x00ff;
	splx(s);
        break;

    case MOUSE_GETHWINFO:
	s = spltty();
        *(mousehw_t *)addr = sc->hw;
	if (sc->mode.level == PSM_LEVEL_BASE)
	    ((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
	splx(s);
        break;

    case OLD_MOUSE_GETMODE:
	s = spltty();
	switch (sc->mode.level) {
	case PSM_LEVEL_BASE:
	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
	    break;
	case PSM_LEVEL_STANDARD:
	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
	    break;
	case PSM_LEVEL_NATIVE:
	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
	    break;
	}
        ((old_mousemode_t *)addr)->rate = sc->mode.rate;
        ((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
        ((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
	splx(s);
        break;

    case MOUSE_GETMODE:
	s = spltty();
        *(mousemode_t *)addr = sc->mode;
        ((mousemode_t *)addr)->resolution = 
	    MOUSE_RES_LOW - sc->mode.resolution;
	switch (sc->mode.level) {
	case PSM_LEVEL_BASE:
	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
	    ((mousemode_t *)addr)->packetsize = MOUSE_PS2_PACKETSIZE;
	    break;
	case PSM_LEVEL_STANDARD:
	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
	    ((mousemode_t *)addr)->packetsize = MOUSE_SYS_PACKETSIZE;
	    ((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
	    ((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
	    break;
	case PSM_LEVEL_NATIVE:
	    /* FIXME: this isn't quite correct... XXX */
	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
	    break;
	}
	splx(s);
        break;

    case OLD_MOUSE_SETMODE:
    case MOUSE_SETMODE:
	if (cmd == OLD_MOUSE_SETMODE) {
	    mode.rate = ((old_mousemode_t *)addr)->rate;
	    /*
	     * resolution  old I/F   new I/F
	     * default        0         0
	     * low            1        -2
	     * medium low     2        -3
	     * medium high    3        -4
	     * high           4        -5
	     */
	    if (((old_mousemode_t *)addr)->resolution > 0)
	        mode.resolution = -((old_mousemode_t *)addr)->resolution - 1;
	    mode.accelfactor = ((old_mousemode_t *)addr)->accelfactor;
	    mode.level = -1;
	} else {
	    mode = *(mousemode_t *)addr;
	}

	/* adjust and validate parameters. */
	if (mode.rate > UCHAR_MAX)
	    return EINVAL;
        if (mode.rate == 0)
            mode.rate = sc->dflt_mode.rate;
	else if (mode.rate == -1)
	    /* don't change the current setting */
	    ;
	else if (mode.rate < 0)
	    return EINVAL;
	if (mode.resolution >= UCHAR_MAX)
	    return EINVAL;
	if (mode.resolution >= 200)
	    mode.resolution = MOUSE_RES_HIGH;
	else if (mode.resolution >= 100)
	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
	else if (mode.resolution >= 50)
	    mode.resolution = MOUSE_RES_MEDIUMLOW;
	else if (mode.resolution > 0)
	    mode.resolution = MOUSE_RES_LOW;
        if (mode.resolution == MOUSE_RES_DEFAULT)
            mode.resolution = sc->dflt_mode.resolution;
        else if (mode.resolution == -1)
	    /* don't change the current setting */
	    ;
        else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
            mode.resolution = MOUSE_RES_LOW - mode.resolution;
	if (mode.level == -1)
	    /* don't change the current setting */
	    mode.level = sc->mode.level;
	else if ((mode.level < PSM_LEVEL_MIN) || (mode.level > PSM_LEVEL_MAX))
	    return EINVAL;
        if (mode.accelfactor == -1)
	    /* don't change the current setting */
	    mode.accelfactor = sc->mode.accelfactor;
        else if (mode.accelfactor < 0)
	    return EINVAL;

	/* don't allow anybody to poll the keyboard controller */
	error = block_mouse_data(sc, &command_byte);
	if (error)
            return error;

        /* set mouse parameters */
	if (mode.rate > 0)
	    mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
	if (mode.resolution >= 0)
	    mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
	set_mouse_scaling(sc->kbdc, 1);
	get_mouse_status(sc->kbdc, stat, 0, 3);

        s = spltty();
    	sc->mode.rate = mode.rate;
    	sc->mode.resolution = mode.resolution;
    	sc->mode.accelfactor = mode.accelfactor;
    	sc->mode.level = mode.level;
        splx(s);

	unblock_mouse_data(sc, command_byte);
        break;

    case MOUSE_GETLEVEL:
	*(int *)addr = sc->mode.level;
        break;

    case MOUSE_SETLEVEL:
	if ((*(int *)addr < PSM_LEVEL_MIN) || (*(int *)addr > PSM_LEVEL_MAX))
	    return EINVAL;
	sc->mode.level = *(int *)addr;
        break;

    case MOUSE_GETSTATUS:
        s = spltty();
	status = sc->status;
	sc->status.flags = 0;
	sc->status.obutton = sc->status.button;
	sc->status.button = 0;
	sc->status.dx = 0;
	sc->status.dy = 0;
	sc->status.dz = 0;
        splx(s);
        *(mousestatus_t *)addr = status;
        break;

#if (defined(MOUSE_GETVARS))
    case MOUSE_GETVARS:
	var = (mousevar_t *)addr;
	bzero(var, sizeof(*var));
	s = spltty();
        var->var[0] = MOUSE_VARS_PS2_SIG;
        var->var[1] = sc->config;
        var->var[2] = sc->flags;
	splx(s);
        break;

    case MOUSE_SETVARS:
	return ENODEV;
#endif /* MOUSE_GETVARS */

    case MOUSE_READSTATE:
    case MOUSE_READDATA:
	data = (mousedata_t *)addr;
	if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
	    return EINVAL;

	error = block_mouse_data(sc, &command_byte);
	if (error)
            return error;
        if ((data->len = get_mouse_status(sc->kbdc, data->buf, 
		(cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
            error = EIO;
	unblock_mouse_data(sc, command_byte);
	break;

#if (defined(MOUSE_SETRESOLUTION))
    case MOUSE_SETRESOLUTION:
	mode.resolution = *(int *)addr;
	if (mode.resolution >= UCHAR_MAX)
	    return EINVAL;
	else if (mode.resolution >= 200)
	    mode.resolution = MOUSE_RES_HIGH;
	else if (mode.resolution >= 100)
	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
	else if (mode.resolution >= 50)
	    mode.resolution = MOUSE_RES_MEDIUMLOW;
	else if (mode.resolution > 0)
	    mode.resolution = MOUSE_RES_LOW;
        if (mode.resolution == MOUSE_RES_DEFAULT)
            mode.resolution = sc->dflt_mode.resolution;
        else if (mode.resolution == -1)
	    mode.resolution = sc->mode.resolution;
        else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
            mode.resolution = MOUSE_RES_LOW - mode.resolution;

	error = block_mouse_data(sc, &command_byte);
	if (error)
            return error;
        sc->mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
	if (sc->mode.resolution != mode.resolution)
	    error = EIO;
	unblock_mouse_data(sc, command_byte);
        break;
#endif /* MOUSE_SETRESOLUTION */

#if (defined(MOUSE_SETRATE))
    case MOUSE_SETRATE:
	mode.rate = *(int *)addr;
	if (mode.rate > UCHAR_MAX)
	    return EINVAL;
        if (mode.rate == 0)
            mode.rate = sc->dflt_mode.rate;
	else if (mode.rate < 0)
	    mode.rate = sc->mode.rate;

	error = block_mouse_data(sc, &command_byte);
	if (error)
            return error;
        sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
	if (sc->mode.rate != mode.rate)
	    error = EIO;
	unblock_mouse_data(sc, command_byte);
        break;
#endif /* MOUSE_SETRATE */

#if (defined(MOUSE_SETSCALING))
    case MOUSE_SETSCALING:
	if ((*(int *)addr <= 0) || (*(int *)addr > 2))
	    return EINVAL;

	error = block_mouse_data(sc, &command_byte);
	if (error)
            return error;
        if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
	    error = EIO;
	unblock_mouse_data(sc, command_byte);
        break;
#endif /* MOUSE_SETSCALING */

#if (defined(MOUSE_GETHWID))
    case MOUSE_GETHWID:
	error = block_mouse_data(sc, &command_byte);
	if (error)
            return error;
        sc->hw.hwid &= ~0x00ff;
        sc->hw.hwid |= get_aux_id(sc->kbdc);
	*(int *)addr = sc->hw.hwid & 0x00ff;
	unblock_mouse_data(sc, command_byte);
        break;
#endif /* MOUSE_GETHWID */

    default:
	return ENOTTY;
    }

    return error;
}

static void
psmtimeout(void *arg)
{
    struct psm_softc *sc;
    int s;

    sc = (struct psm_softc *)arg;
    s = spltty();
    if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) {
	if (verbose >= 4)
	    log(LOG_DEBUG, "psm%d: lost interrupt?\n", sc->unit);
	psmintr(sc);
	kbdc_lock(sc->kbdc, FALSE);
    }
    sc->watchdog = TRUE;
    splx(s);
    sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz);
}

static int psmhz = 20;
SYSCTL_INT(_debug, OID_AUTO, psmhz, CTLFLAG_RW, &psmhz, 0, "");

static int psm_soft_timeout = 500000; /* 0.5 sec */
SYSCTL_INT(_debug, OID_AUTO, psm_soft_timeout, CTLFLAG_RW,
    &psm_soft_timeout, 0, "");

static int psmerrsecs = 2;
SYSCTL_INT(_debug, OID_AUTO, psmerrsecs, CTLFLAG_RW, &psmerrsecs, 0, "");
static int psmerrusecs = 0;
SYSCTL_INT(_debug, OID_AUTO, psmerrusecs, CTLFLAG_RW, &psmerrusecs, 0, "");
static int psmsecs = 0;
SYSCTL_INT(_debug, OID_AUTO, psmsecs, CTLFLAG_RW, &psmsecs, 0, "");
static int psmusecs = 500000;
SYSCTL_INT(_debug, OID_AUTO, psmusecs, CTLFLAG_RW, &psmusecs, 0, "");

static void
psmintr(void *arg)
{
    struct psm_softc *sc = arg;
    struct timeval now;
    int c;
    packetbuf_t *pb;
    int haderror = 0;


    /* read until there is nothing to read */
    while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
    
        pb = &sc->pqueue[sc->pqueue_end];
        /* discard the byte if the device is not open */
        if ((sc->state & PSM_OPEN) == 0)
            continue;
    
	getmicrouptime(&now);
	if ((pb->inputbytes > 0) && timevalcmp(&now, &sc->inputtimeout, >)) {
	    log(LOG_DEBUG, "psmintr: delay too long; resetting byte count\n");
	    pb->inputbytes = 0;
	    sc->syncerrors = 0;
	}
	sc->inputtimeout.tv_sec = PSM_INPUT_TIMEOUT/1000000;
	sc->inputtimeout.tv_usec = PSM_INPUT_TIMEOUT%1000000;
	timevaladd(&sc->inputtimeout, &now);

        pb->ipacket[pb->inputbytes++] = c;
        if (pb->inputbytes < sc->mode.packetsize) 
	    continue;

#if 0
        log(LOG_DEBUG, "psmintr: %02x %02x %02x %02x %02x %02x\n",
	    pb->ipacket[0], pb->ipacket[1], pb->ipacket[2],
	    pb->ipacket[3], pb->ipacket[4], pb->ipacket[5]);
#endif

	c = pb->ipacket[0];

	if ((c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) {
            log(LOG_DEBUG, "psmintr: out of sync (%04x != %04x) %d"
		" cmds since last error.\n", 
		c & sc->mode.syncmask[0], sc->mode.syncmask[1],
		sc->cmdcount - sc->lasterr);
	    haderror = 1;
	    sc->lasterr = sc->cmdcount;
	    dropqueue(sc);
	    ++sc->syncerrors;
	    sc->lastinputerr = now;
	    if (sc->syncerrors < sc->mode.packetsize) {
		log(LOG_DEBUG, "psmintr: discard a byte (%d).\n", sc->syncerrors);
		--pb->inputbytes;
		bcopy(&pb->ipacket[1], &pb->ipacket[0], pb->inputbytes);
	    } else if (sc->syncerrors == sc->mode.packetsize) {
		log(LOG_DEBUG, "psmintr: re-enable the mouse.\n");
		pb->inputbytes = 0;
		disable_aux_dev(sc->kbdc);
		enable_aux_dev(sc->kbdc);
	    } else if (sc->syncerrors < PSM_SYNCERR_THRESHOLD1) {
		log(LOG_DEBUG, "psmintr: discard a byte (%d).\n", sc->syncerrors);
		--pb->inputbytes;
		bcopy(&pb->ipacket[1], &pb->ipacket[0], pb->inputbytes);
	    } else if (sc->syncerrors >= PSM_SYNCERR_THRESHOLD1) {
		log(LOG_DEBUG, "psmintr: reset the mouse.\n");
		reinitialize(sc, TRUE);
	    }
	    continue;
	}
	/* if this packet is at all bogus then drop the packet. */
	if (haderror ||
	    !timeelapsed(&sc->lastinputerr, psmerrsecs, psmerrusecs, &now)) {
		pb->inputbytes = 0;
		haderror = 0;
		continue;
	}

	sc->cmdcount++;
	if (++sc->pqueue_end >= PSM_PACKETQUEUE)
		sc->pqueue_end = 0;
	/*
	 * If we've filled the queue then call the softintr ourselves,
	 * otherwise schedule the interrupt for later.
	 */
	if (!timeelapsed(&sc->lastsoftintr, psmsecs, psmusecs, &now) ||
	    (sc->pqueue_end == sc->pqueue_start)) {
    		if ((sc->state & PSM_SOFTARMED) != 0) {
			sc->state &= ~PSM_SOFTARMED;
			untimeout(psmsoftintr, arg, sc->softcallout);
		}
		psmsoftintr(arg);
	} else if ((sc->state & PSM_SOFTARMED) == 0) {
		sc->state |= PSM_SOFTARMED;
		sc->softcallout = timeout(psmsoftintr, arg,
		    psmhz < 1 ? 1 : (hz/psmhz));
	}
    }
}

static void
psmsoftintr(void *arg)
{
    /*
     * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
     * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
     */
    static int butmap[8] = {
        0, 
	MOUSE_BUTTON1DOWN, 
	MOUSE_BUTTON3DOWN, 
	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN, 
	MOUSE_BUTTON2DOWN, 
	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN, 
	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
        MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
    };
    static int butmap_versapad[8] = {
	0, 
	MOUSE_BUTTON3DOWN, 
	0, 
	MOUSE_BUTTON3DOWN, 
	MOUSE_BUTTON1DOWN, 
	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN, 
	MOUSE_BUTTON1DOWN,
	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN
    };
    register struct psm_softc *sc = arg;
    mousestatus_t ms;
    int x, y, z;
    int c;
    int l;
    int x0, y0;
    int s;
    packetbuf_t *pb;

    getmicrouptime(&sc->lastsoftintr);

    s = spltty();

    do {
	
	pb = &sc->pqueue[sc->pqueue_start];
	c = pb->ipacket[0];
	/* 
	 * A kludge for Kensington device! 
	 * The MSB of the horizontal count appears to be stored in 
	 * a strange place.
	 */
	if (sc->hw.model == MOUSE_MODEL_THINK)
	    pb->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;

        /* ignore the overflow bits... */
        x = (c & MOUSE_PS2_XNEG) ?  pb->ipacket[1] - 256 : pb->ipacket[1];
        y = (c & MOUSE_PS2_YNEG) ?  pb->ipacket[2] - 256 : pb->ipacket[2];
	z = 0;
        ms.obutton = sc->button;		  /* previous button state */
        ms.button = butmap[c & MOUSE_PS2_BUTTONS];
	/* `tapping' action */
	if (sc->config & PSM_CONFIG_FORCETAP)
	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;

	switch (sc->hw.model) {

	case MOUSE_MODEL_EXPLORER:
	    /*
	     *          b7 b6 b5 b4 b3 b2 b1 b0
	     * byte 1:  oy ox sy sx 1  M  R  L
	     * byte 2:  x  x  x  x  x  x  x  x
	     * byte 3:  y  y  y  y  y  y  y  y
	     * byte 4:  *  *  S2 S1 s  d2 d1 d0
	     *
	     * L, M, R, S1, S2: left, middle, right and side buttons
	     * s: wheel data sign bit
	     * d2-d0: wheel data
	     */
	    z = (pb->ipacket[3] & MOUSE_EXPLORER_ZNEG)
		? (pb->ipacket[3] & 0x0f) - 16 : (pb->ipacket[3] & 0x0f);
	    ms.button |= (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN)
		? MOUSE_BUTTON4DOWN : 0;
	    ms.button |= (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN)
		? MOUSE_BUTTON5DOWN : 0;
	    break;

	case MOUSE_MODEL_INTELLI:
	case MOUSE_MODEL_NET:
	    /* wheel data is in the fourth byte */
	    z = (char)pb->ipacket[3];
	    /* some mice may send 7 when there is no Z movement?! XXX */
	    if ((z >= 7) || (z <= -7))
		z = 0;
	    /* some compatible mice have additional buttons */
	    ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN)
		? MOUSE_BUTTON4DOWN : 0;
	    ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN)
		? MOUSE_BUTTON5DOWN : 0;
	    break;

	case MOUSE_MODEL_MOUSEMANPLUS:
	    /*
	     * PS2++ protocl packet
	     *
	     *          b7 b6 b5 b4 b3 b2 b1 b0
	     * byte 1:  *  1  p3 p2 1  *  *  *
	     * byte 2:  c1 c2 p1 p0 d1 d0 1  0
	     *
	     * p3-p0: packet type
	     * c1, c2: c1 & c2 == 1, if p2 == 0
	     *         c1 & c2 == 0, if p2 == 1
	     *
	     * packet type: 0 (device type)
	     * See comments in enable_mmanplus() below.
	     * 
	     * packet type: 1 (wheel data)
	     *
	     *          b7 b6 b5 b4 b3 b2 b1 b0
	     * byte 3:  h  *  B5 B4 s  d2 d1 d0
	     *
	     * h: 1, if horizontal roller data
	     *    0, if vertical roller data
	     * B4, B5: button 4 and 5
	     * s: sign bit
	     * d2-d0: roller data
	     *
	     * packet type: 2 (reserved)
	     */
	    if (((c & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC)
		    && (abs(x) > 191)
		    && MOUSE_PS2PLUS_CHECKBITS(pb->ipacket)) {
		/* the extended data packet encodes button and wheel events */
		switch (MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket)) {
		case 1:
		    /* wheel data packet */
		    x = y = 0;
		    if (pb->ipacket[2] & 0x80) {
			/* horizontal roller count - ignore it XXX*/
		    } else {
			/* vertical roller count */
			z = (pb->ipacket[2] & MOUSE_PS2PLUS_ZNEG)
			    ? (pb->ipacket[2] & 0x0f) - 16
			    : (pb->ipacket[2] & 0x0f);
		    }
		    ms.button |= (pb->ipacket[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
			? MOUSE_BUTTON4DOWN : 0;
		    ms.button |= (pb->ipacket[2] & MOUSE_PS2PLUS_BUTTON5DOWN)
			? MOUSE_BUTTON5DOWN : 0;
		    break;
		case 2:
		    /* this packet type is reserved by Logitech... */
		    /*
		     * IBM ScrollPoint Mouse uses this packet type to
		     * encode both vertical and horizontal scroll movement.
		     */
		    x = y = 0;
		    /* horizontal count */
		    if (pb->ipacket[2] & 0x0f)
			z = (pb->ipacket[2] & MOUSE_SPOINT_WNEG) ? -2 : 2;
		    /* vertical count */
		    if (pb->ipacket[2] & 0xf0)
			z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG) ? -1 : 1;
#if 0
		    /* vertical count */
		    z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG)
			? ((pb->ipacket[2] >> 4) & 0x0f) - 16
			: ((pb->ipacket[2] >> 4) & 0x0f);
		    /* horizontal count */
		    w = (pb->ipacket[2] & MOUSE_SPOINT_WNEG)
			? (pb->ipacket[2] & 0x0f) - 16
			: (pb->ipacket[2] & 0x0f);
#endif
		    break;
		case 0:
		    /* device type packet - shouldn't happen */
		    /* FALLTHROUGH */
		default:
		    x = y = 0;
		    ms.button = ms.obutton;
		    if (bootverbose)
			log(LOG_DEBUG, "psmintr: unknown PS2++ packet type %d: "
				       "0x%02x 0x%02x 0x%02x\n",
			    MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket),
			    pb->ipacket[0], pb->ipacket[1], pb->ipacket[2]);
		    break;
		}
	    } else {
		/* preserve button states */
		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
	    }
	    break;

	case MOUSE_MODEL_GLIDEPOINT:
	    /* `tapping' action */
	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
	    break;

	case MOUSE_MODEL_NETSCROLL:
	    /* three addtional bytes encode buttons and wheel events */
	    ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON3DOWN)
		? MOUSE_BUTTON4DOWN : 0;
	    ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON1DOWN)
		? MOUSE_BUTTON5DOWN : 0;
	    z = (pb->ipacket[3] & MOUSE_PS2_XNEG) 
		? pb->ipacket[4] - 256 : pb->ipacket[4];
	    break;

	case MOUSE_MODEL_THINK:
	    /* the fourth button state in the first byte */
	    ms.button |= (c & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
	    break;

	case MOUSE_MODEL_VERSAPAD:
	    /* VersaPad PS/2 absolute mode message format
	     *
	     * [packet1]     7   6   5   4   3   2   1   0(LSB)
	     *  ipacket[0]:  1   1   0   A   1   L   T   R
	     *  ipacket[1]: H7  H6  H5  H4  H3  H2  H1  H0
	     *  ipacket[2]: V7  V6  V5  V4  V3  V2  V1  V0
	     *  ipacket[3]:  1   1   1   A   1   L   T   R
	     *  ipacket[4]:V11 V10  V9  V8 H11 H10  H9  H8
	     *  ipacket[5]:  0  P6  P5  P4  P3  P2  P1  P0
	     *
	     * [note]
	     *  R: right physical mouse button (1=on)
	     *  T: touch pad virtual button (1=tapping)
	     *  L: left physical mouse button (1=on)
	     *  A: position data is valid (1=valid)
	     *  H: horizontal data (12bit signed integer. H11 is sign bit.)
	     *  V: vertical data (12bit signed integer. V11 is sign bit.)
	     *  P: pressure data
	     *
	     * Tapping is mapped to MOUSE_BUTTON4.
	     */
	    ms.button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS];
	    ms.button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
	    x = y = 0;
	    if (c & MOUSE_PS2VERSA_IN_USE) {
		x0 = pb->ipacket[1] | (((pb->ipacket[4]) & 0x0f) << 8);
		y0 = pb->ipacket[2] | (((pb->ipacket[4]) & 0xf0) << 4);
		if (x0 & 0x800)
		    x0 -= 0x1000;
		if (y0 & 0x800)
		    y0 -= 0x1000;
		if (sc->flags & PSM_FLAGS_FINGERDOWN) {
		    x = sc->xold - x0;
		    y = y0 - sc->yold;
		    if (x < 0)	/* XXX */
			x++;
		    else if (x)
			x--;
		    if (y < 0)
			y++;
		    else if (y)
			y--;
		} else {
		    sc->flags |= PSM_FLAGS_FINGERDOWN;
		}
		sc->xold = x0;
		sc->yold = y0;
	    } else {
		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
	    }
	    c = ((x < 0) ? MOUSE_PS2_XNEG : 0)
		| ((y < 0) ? MOUSE_PS2_YNEG : 0);
	    break;

	case MOUSE_MODEL_4D:
	    /*
	     *          b7 b6 b5 b4 b3 b2 b1 b0
	     * byte 1:  s2 d2 s1 d1 1  M  R  L
	     * byte 2:  sx x  x  x  x  x  x  x
	     * byte 3:  sy y  y  y  y  y  y  y
	     *
	     * s1: wheel 1 direction
	     * d1: wheel 1 data
	     * s2: wheel 2 direction
	     * d2: wheel 2 data
	     */
	    x = (pb->ipacket[1] & 0x80) ? pb->ipacket[1] - 256 : pb->ipacket[1];
	    y = (pb->ipacket[2] & 0x80) ? pb->ipacket[2] - 256 : pb->ipacket[2];
	    switch (c & MOUSE_4D_WHEELBITS) {
	    case 0x10:
		z = 1;
		break;
	    case 0x30:
		z = -1;
		break;
	    case 0x40:	/* 2nd wheel turning right XXX */
		z = 2;
		break;
	    case 0xc0:	/* 2nd wheel turning left XXX */
		z = -2;
		break;
	    }
	    break;

	case MOUSE_MODEL_4DPLUS:
	    if ((x < 16 - 256) && (y < 16 - 256)) {
		/*
		 *          b7 b6 b5 b4 b3 b2 b1 b0
		 * byte 1:  0  0  1  1  1  M  R  L
		 * byte 2:  0  0  0  0  1  0  0  0
		 * byte 3:  0  0  0  0  S  s  d1 d0
		 *
		 * L, M, R, S: left, middle, right and side buttons
		 * s: wheel data sign bit
		 * d1-d0: wheel data
		 */
		x = y = 0;
		if (pb->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN)
		    ms.button |= MOUSE_BUTTON4DOWN;
		z = (pb->ipacket[2] & MOUSE_4DPLUS_ZNEG)
			? ((pb->ipacket[2] & 0x07) - 8)
			: (pb->ipacket[2] & 0x07) ;
	    } else {
		/* preserve previous button states */
		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
	    }
	    break;

	case MOUSE_MODEL_GENERIC:
	default:
	    break;
	}

        /* scale values */
        if (sc->mode.accelfactor >= 1) {
            if (x != 0) {
                x = x * x / sc->mode.accelfactor;
                if (x == 0)
                    x = 1;
                if (c & MOUSE_PS2_XNEG)
                    x = -x;
            }
            if (y != 0) {
                y = y * y / sc->mode.accelfactor;
                if (y == 0)
                    y = 1;
                if (c & MOUSE_PS2_YNEG)
                    y = -y;
            }
        }

        ms.dx = x;
        ms.dy = y;
        ms.dz = z;
        ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0) 
	    | (ms.obutton ^ ms.button);

	if (sc->mode.level < PSM_LEVEL_NATIVE)
	    pb->inputbytes = tame_mouse(sc, pb, &ms, pb->ipacket);

        sc->status.flags |= ms.flags;
        sc->status.dx += ms.dx;
        sc->status.dy += ms.dy;
        sc->status.dz += ms.dz;
        sc->status.button = ms.button;
        sc->button = ms.button;

	sc->watchdog = FALSE;

        /* queue data */
        if (sc->queue.count + pb->inputbytes < sizeof(sc->queue.buf)) {
	    l = imin(pb->inputbytes, sizeof(sc->queue.buf) - sc->queue.tail);
	    bcopy(&pb->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
	    if (pb->inputbytes > l)
	        bcopy(&pb->ipacket[l], &sc->queue.buf[0], pb->inputbytes - l);
            sc->queue.tail = 
		(sc->queue.tail + pb->inputbytes) % sizeof(sc->queue.buf);
            sc->queue.count += pb->inputbytes;
	}
        pb->inputbytes = 0;

	if (++sc->pqueue_start >= PSM_PACKETQUEUE)
		sc->pqueue_start = 0;
    } while (sc->pqueue_start != sc->pqueue_end);
    if (sc->state & PSM_ASLP) {
        sc->state &= ~PSM_ASLP;
        wakeup( sc);
    }
    selwakeuppri(&sc->rsel, PZERO);
    sc->state &= ~PSM_SOFTARMED;
    splx(s);
}

static int
psmpoll(dev_t dev, int events, struct thread *td)
{
    struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
    int s;
    int revents = 0;

    /* Return true if a mouse event available */
    s = spltty();
    if (events & (POLLIN | POLLRDNORM)) {
	if (sc->queue.count > 0)
	    revents |= events & (POLLIN | POLLRDNORM);
	else
	    selrecord(td, &sc->rsel);
    }
    splx(s);

    return (revents);
}

/* vendor/model specific routines */

static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
{
    if (set_mouse_resolution(kbdc, res) != res)
        return FALSE;
    if (set_mouse_scaling(kbdc, scale)
	&& set_mouse_scaling(kbdc, scale)
	&& set_mouse_scaling(kbdc, scale) 
	&& (get_mouse_status(kbdc, status, 0, 3) >= 3)) 
	return TRUE;
    return FALSE;
}

static int 
mouse_ext_command(KBDC kbdc, int command)
{
    int c;

    c = (command >> 6) & 0x03;
    if (set_mouse_resolution(kbdc, c) != c)
	return FALSE;
    c = (command >> 4) & 0x03;
    if (set_mouse_resolution(kbdc, c) != c)
	return FALSE;
    c = (command >> 2) & 0x03;
    if (set_mouse_resolution(kbdc, c) != c)
	return FALSE;
    c = (command >> 0) & 0x03;
    if (set_mouse_resolution(kbdc, c) != c)
	return FALSE;
    return TRUE;
}

#if notyet
/* Logitech MouseMan Cordless II */
static int
enable_lcordless(struct psm_softc *sc)
{
    int status[3];
    int ch;

    if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 2, status))
        return FALSE;
    if (status[1] == PSMD_RES_HIGH)
	return FALSE;
    ch = (status[0] & 0x07) - 1;	/* channel # */
    if ((ch <= 0) || (ch > 4))
	return FALSE;
    /* 
     * status[1]: always one?
     * status[2]: battery status? (0-100)
     */
    return TRUE;
}
#endif /* notyet */

/* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
static int
enable_groller(struct psm_softc *sc)
{
    int status[3];

    /*
     * The special sequence to enable the fourth button and the
     * roller. Immediately after this sequence check status bytes.
     * if the mouse is NetScroll, the second and the third bytes are 
     * '3' and 'D'.
     */

    /*
     * If the mouse is an ordinary PS/2 mouse, the status bytes should
     * look like the following.
     * 
     * byte 1 bit 7 always 0
     *        bit 6 stream mode (0)
     *        bit 5 disabled (0)
     *        bit 4 1:1 scaling (0)
     *        bit 3 always 0
     *        bit 0-2 button status
     * byte 2 resolution (PSMD_RES_HIGH)
     * byte 3 report rate (?)
     */

    if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
        return FALSE;
    if ((status[1] != '3') || (status[2] != 'D'))
        return FALSE;
    /* FIXME: SmartScroll Mouse has 5 buttons! XXX */
    sc->hw.buttons = 4;
    return TRUE;
}

/* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
static int
enable_gmouse(struct psm_softc *sc)
{
    int status[3];

    /*
     * The special sequence to enable the middle, "rubber" button. 
     * Immediately after this sequence check status bytes.
     * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse, 
     * the second and the third bytes are '3' and 'U'.
     * NOTE: NetMouse reports that it has three buttons although it has
     * two buttons and a rubber button. NetMouse Pro and MIE Mouse
     * say they have three buttons too and they do have a button on the
     * side...
     */
    if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
        return FALSE;
    if ((status[1] != '3') || (status[2] != 'U'))
        return FALSE;
    return TRUE;
}

/* ALPS GlidePoint */
static int
enable_aglide(struct psm_softc *sc)
{
    int status[3];

    /*
     * The special sequence to obtain ALPS GlidePoint specific
     * information. Immediately after this sequence, status bytes will 
     * contain something interesting.
     * NOTE: ALPS produces several models of GlidePoint. Some of those
     * do not respond to this sequence, thus, cannot be detected this way.
     */
    if (set_mouse_sampling_rate(sc->kbdc, 100) != 100)
	return FALSE;
    if (!mouse_id_proc1(sc->kbdc, PSMD_RES_LOW, 2, status))
        return FALSE;
    if ((status[1] == PSMD_RES_LOW) || (status[2] == 100))
        return FALSE;
    return TRUE;
}

/* Kensington ThinkingMouse/Trackball */
static int
enable_kmouse(struct psm_softc *sc)
{
    static unsigned char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
    KBDC kbdc = sc->kbdc;
    int status[3];
    int id1;
    int id2;
    int i;

    id1 = get_aux_id(kbdc);
    if (set_mouse_sampling_rate(kbdc, 10) != 10)
	return FALSE;
    /* 
     * The device is now in the native mode? It returns a different
     * ID value...
     */
    id2 = get_aux_id(kbdc);
    if ((id1 == id2) || (id2 != 2))
	return FALSE;

    if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
        return FALSE;
#if PSM_DEBUG >= 2
    /* at this point, resolution is LOW, sampling rate is 10/sec */
    if (get_mouse_status(kbdc, status, 0, 3) < 3)
        return FALSE;
#endif

    /*
     * The special sequence to enable the third and fourth buttons.
     * Otherwise they behave like the first and second buttons.
     */
    for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
        if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
	    return FALSE;
    }

    /* 
     * At this point, the device is using default resolution and
     * sampling rate for the native mode. 
     */
    if (get_mouse_status(kbdc, status, 0, 3) < 3)
        return FALSE;
    if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
        return FALSE;

    /* the device appears be enabled by this sequence, diable it for now */
    disable_aux_dev(kbdc);
    empty_aux_buffer(kbdc, 5);

    return TRUE;
}

/* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
static int
enable_mmanplus(struct psm_softc *sc)
{
    KBDC kbdc = sc->kbdc;
    int data[3];

    /* the special sequence to enable the fourth button and the roller. */
    /*
     * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION
     * must be called exactly three times since the last RESET command
     * before this sequence. XXX
     */
    if (!set_mouse_scaling(kbdc, 1))
	return FALSE;
    if (!mouse_ext_command(kbdc, 0x39) || !mouse_ext_command(kbdc, 0xdb))
	return FALSE;
    if (get_mouse_status(kbdc, data, 1, 3) < 3)
        return FALSE;

    /*
     * PS2++ protocl, packet type 0
     *
     *          b7 b6 b5 b4 b3 b2 b1 b0
     * byte 1:  *  1  p3 p2 1  *  *  *
     * byte 2:  1  1  p1 p0 m1 m0 1  0
     * byte 3:  m7 m6 m5 m4 m3 m2 m1 m0
     *
     * p3-p0: packet type: 0
     * m7-m0: model ID: MouseMan+:0x50, FirstMouse+:0x51, ScrollPoint:0x58...
     */
    /* check constant bits */
    if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC)
        return FALSE;
    if ((data[1] & 0xc3) != 0xc2)
        return FALSE;
    /* check d3-d0 in byte 2 */
    if (!MOUSE_PS2PLUS_CHECKBITS(data))
        return FALSE;
    /* check p3-p0 */
    if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0)
        return FALSE;

    sc->hw.hwid &= 0x00ff;
    sc->hw.hwid |= data[2] << 8;	/* save model ID */

    /*
     * MouseMan+ (or FirstMouse+) is now in its native mode, in which
     * the wheel and the fourth button events are encoded in the
     * special data packet. The mouse may be put in the IntelliMouse mode
     * if it is initialized by the IntelliMouse's method.
     */
    return TRUE;
}

/* MS IntelliMouse Explorer */
static int
enable_msexplorer(struct psm_softc *sc)
{
    static unsigned char rate0[] = { 200, 100, 80, };
    static unsigned char rate1[] = { 200, 200, 80, };
    KBDC kbdc = sc->kbdc;
    int id;
    int i;

    /* the special sequence to enable the extra buttons and the roller. */
    for (i = 0; i < sizeof(rate1)/sizeof(rate1[0]); ++i) {
        if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i])
	    return FALSE;
    }
    /* the device will give the genuine ID only after the above sequence */
    id = get_aux_id(kbdc);
    if (id != PSM_EXPLORER_ID)
	return FALSE;

    sc->hw.hwid = id;
    sc->hw.buttons = 5;		/* IntelliMouse Explorer XXX */

    /*
     * XXX: this is a kludge to fool some KVM switch products
     * which think they are clever enough to know the 4-byte IntelliMouse
     * protocol, and assume any other protocols use 3-byte packets.
     * They don't convey 4-byte data packets from the IntelliMouse Explorer 
     * correctly to the host computer because of this!
     * The following sequence is actually IntelliMouse's "wake up"
     * sequence; it will make the KVM think the mouse is IntelliMouse
     * when it is in fact IntelliMouse Explorer.
     */
    for (i = 0; i < sizeof(rate0)/sizeof(rate0[0]); ++i) {
        if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i])
	    break;
    }
    id = get_aux_id(kbdc);

    return TRUE;
}

/* MS IntelliMouse */
static int
enable_msintelli(struct psm_softc *sc)
{
    /*
     * Logitech MouseMan+ and FirstMouse+ will also respond to this
     * probe routine and act like IntelliMouse.
     */

    static unsigned char rate[] = { 200, 100, 80, };
    KBDC kbdc = sc->kbdc;
    int id;
    int i;

    /* the special sequence to enable the third button and the roller. */
    for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
        if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
	    return FALSE;
    }
    /* the device will give the genuine ID only after the above sequence */
    id = get_aux_id(kbdc);
    if (id != PSM_INTELLI_ID)
	return FALSE;

    sc->hw.hwid = id;
    sc->hw.buttons = 3;

    return TRUE;
}

/* A4 Tech 4D Mouse */
static int
enable_4dmouse(struct psm_softc *sc)
{
    /*
     * Newer wheel mice from A4 Tech may use the 4D+ protocol.
     */

    static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
    KBDC kbdc = sc->kbdc;
    int id;
    int i;

    for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
        if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
	    return FALSE;
    }
    id = get_aux_id(kbdc);
    /*
     * WinEasy 4D, 4 Way Scroll 4D: 6
     * Cable-Free 4D: 8 (4DPLUS)
     * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS)
     */
    if (id != PSM_4DMOUSE_ID)
	return FALSE;

    sc->hw.hwid = id;
    sc->hw.buttons = 3;		/* XXX some 4D mice have 4? */

    return TRUE;
}

/* A4 Tech 4D+ Mouse */
static int
enable_4dplus(struct psm_softc *sc)
{
    /*
     * Newer wheel mice from A4 Tech seem to use this protocol.
     * Older models are recognized as either 4D Mouse or IntelliMouse.
     */
    KBDC kbdc = sc->kbdc;
    int id;

    /*
     * enable_4dmouse() already issued the following ID sequence...
    static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
    int i;

    for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
        if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
	    return FALSE;
    }
    */

    id = get_aux_id(kbdc);
    switch (id) {
    case PSM_4DPLUS_ID:
	    sc->hw.buttons = 4;
	    break;
    case PSM_4DPLUS_RFSW35_ID:
	    sc->hw.buttons = 3;
	    break;
    default:
	    return FALSE;
    }

    sc->hw.hwid = id;

    return TRUE;
}

/* Interlink electronics VersaPad */
static int
enable_versapad(struct psm_softc *sc)
{
    KBDC kbdc = sc->kbdc;
    int data[3];

    set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
    set_mouse_sampling_rate(kbdc, 100);		/* set rate 100 */
    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
    if (get_mouse_status(kbdc, data, 0, 3) < 3)	/* get status */
	return FALSE;
    if (data[2] != 0xa || data[1] != 0 )	/* rate == 0xa && res. == 0 */
	return FALSE;
    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */

    sc->config |= PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;

    return TRUE;				/* PS/2 absolute mode */
}

static int
psmresume(device_t dev)
{
    struct psm_softc *sc = device_get_softc(dev);
    int unit = device_get_unit(dev);
    int err;

    if (verbose >= 2)
        log(LOG_NOTICE, "psm%d: system resume hook called.\n", unit);

    if (!(sc->config & PSM_CONFIG_HOOKRESUME))
	return (0);

    err = reinitialize(sc, sc->config & PSM_CONFIG_INITAFTERSUSPEND);

    if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
	/* 
	 * Release the blocked process; it must be notified that the device
	 * cannot be accessed anymore.
	 */
        sc->state &= ~PSM_ASLP;
        wakeup(sc);
    }

    if (verbose >= 2)
        log(LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit);

    return (err);
}

DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0);

/*
 * This sucks up assignments from PNPBIOS and ACPI.
 */

/*
 * When the PS/2 mouse device is reported by ACPI or PnP BIOS, it may
 * appear BEFORE the AT keyboard controller.  As the PS/2 mouse device
 * can be probed and attached only after the AT keyboard controller is
 * attached, we shall quietly reserve the IRQ resource for later use.
 * If the PS/2 mouse device is reported to us AFTER the keyboard controller,
 * copy the IRQ resource to the PS/2 mouse device instance hanging
 * under the keyboard controller, then probe and attach it.
 */

static	devclass_t			psmcpnp_devclass;

static	device_probe_t			psmcpnp_probe;
static	device_attach_t			psmcpnp_attach;

static device_method_t psmcpnp_methods[] = {
	DEVMETHOD(device_probe,		psmcpnp_probe),
	DEVMETHOD(device_attach,	psmcpnp_attach),
	
	{ 0, 0 }
};

static driver_t psmcpnp_driver = {
	PSMCPNP_DRIVER_NAME,
	psmcpnp_methods,
	1,			/* no softc */
};

static struct isa_pnp_id psmcpnp_ids[] = {
	{ 0x030fd041, "PS/2 mouse port" },		/* PNP0F03 */
	{ 0x130fd041, "PS/2 mouse port" },		/* PNP0F13 */
	{ 0x1303d041, "PS/2 port" },			/* PNP0313, XXX */
	{ 0x02002e4f, "Dell PS/2 mouse port" },		/* Lat. X200, Dell */
	{ 0x80374d24, "IBM PS/2 mouse port" },		/* IBM3780, ThinkPad */
	{ 0x81374d24, "IBM PS/2 mouse port" },		/* IBM3781, ThinkPad */
	{ 0x0190d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9001, Vaio */
	{ 0x0290d94d, "SONY VAIO PS/2 mouse port"},	/* SNY9002, Vaio */
	{ 0x0390d94d, "SONY VAIO PS/2 mouse port"},	/* SNY9003, Vaio */
	{ 0x0490d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9004, Vaio */
	{ 0 }
};

static int
create_a_copy(device_t atkbdc, device_t me)
{
	device_t psm;
	u_long irq;

	/* find the PS/2 mouse device instance under the keyboard controller */
	psm = device_find_child(atkbdc, PSM_DRIVER_NAME,
				device_get_unit(atkbdc));
	if (psm == NULL)
		return ENXIO;
	if (device_get_state(psm) != DS_NOTPRESENT)
		return 0;

	/* move our resource to the found device */
	irq = bus_get_resource_start(me, SYS_RES_IRQ, 0);
	bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);

	/* ...then probe and attach it */
	return device_probe_and_attach(psm);
}

static int
psmcpnp_probe(device_t dev)
{
	struct resource *res;
	u_long irq;
	int rid;

	if (ISA_PNP_PROBE(device_get_parent(dev), dev, psmcpnp_ids))
		return ENXIO;

	/*
	 * The PnP BIOS and ACPI are supposed to assign an IRQ (12)
	 * to the PS/2 mouse device node. But, some buggy PnP BIOS
	 * declares the PS/2 mouse device node without an IRQ resource!
	 * If this happens, we shall refer to device hints.
	 * If we still don't find it there, use a hardcoded value... XXX
	 */
	rid = 0;
	irq = bus_get_resource_start(dev, SYS_RES_IRQ, rid);
	if (irq <= 0) {
		if (resource_long_value(PSM_DRIVER_NAME,
					device_get_unit(dev), "irq", &irq) != 0)
			irq = 12;	/* XXX */
		device_printf(dev, "irq resource info is missing; "
			      "assuming irq %ld\n", irq);
		bus_set_resource(dev, SYS_RES_IRQ, rid, irq, 1);
	}
	res = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0, ~0, 1,
				 RF_SHAREABLE);
	bus_release_resource(dev, SYS_RES_IRQ, rid, res);

	/* keep quiet */
	if (!bootverbose)
		device_quiet(dev);

	return ((res == NULL) ? ENXIO : 0);
}

static int
psmcpnp_attach(device_t dev)
{
	device_t atkbdc;
	int rid;

	/* find the keyboard controller, which may be on acpi* or isa* bus */
	atkbdc = devclass_get_device(devclass_find(ATKBDC_DRIVER_NAME),
				     device_get_unit(dev));
	if ((atkbdc != NULL) && (device_get_state(atkbdc) == DS_ATTACHED)) {
		create_a_copy(atkbdc, dev);
	} else {
		/*
		 * If we don't have the AT keyboard controller yet,
		 * just reserve the IRQ for later use...
		 * (See psmidentify() above.)
		 */
		rid = 0;
		bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0, ~0, 1,
				   RF_SHAREABLE);
	}

	return 0;
}

/*
 * Return true if 'now' is earlier than (start + (secs.usecs)).
 * Now may be NULL and the function will fetch the current time from
 * getmicrouptime(), or a cached 'now' can be passed in.
 * All values should be numbers derived from getmicrouptime().
 */
static int
timeelapsed(start, secs, usecs, now)
	const struct timeval *start, *now;
	int secs, usecs;
{
	struct timeval snow, tv;

	/* if there is no 'now' passed in, the get it as a convience. */
	if (now == NULL) {
		getmicrouptime(&snow);
		now = &snow;
	}
	
	tv.tv_sec = secs;
	tv.tv_usec = usecs;
	timevaladd(&tv, start);
	return (timevalcmp(&tv, now, <));
}

DRIVER_MODULE(psmcpnp, isa, psmcpnp_driver, psmcpnp_devclass, 0, 0);
DRIVER_MODULE(psmcpnp, acpi, psmcpnp_driver, psmcpnp_devclass, 0, 0);
OpenPOWER on IntegriCloud