aboutsummaryrefslogtreecommitdiff
path: root/sys/dev/lmc/if_lmc.c
blob: a5a722be7c796361684b7b4a5c56321e181a30df (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
/*
 * $FreeBSD$
 *
 * Copyright (c) 2002-2004 David Boggs. <boggs@boggs.palo-alto.ca.us>
 * All rights reserved.
 *
 * BSD License:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * GNU General Public License:
 *
 * This program is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free 
 * Software Foundation; either version 2 of the License, or (at your option) 
 * any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for 
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 
 * Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Description:
 *
 * This is an open-source Unix device driver for PCI-bus WAN interface cards.
 * It sends and receives packets in HDLC frames over synchronous links.
 * A generic PC plus Unix plus some SBE/LMC cards makes an OPEN router.
 * This driver works with FreeBSD, NetBSD, OpenBSD, BSD/OS and Linux.
 * It has been tested on i386 (32-bit little-end), Sparc (64-bit big-end),
 * and Alpha (64-bit little-end) architectures.
 *
 * History and Authors:
 *
 * Ron Crane had the neat idea to use a Fast Ethernet chip as a PCI
 * interface and add an Ethernet-to-HDLC gate array to make a WAN card.
 * David Boggs designed the Ethernet-to-HDLC gate arrays and PC cards.
 * We did this at our company, LAN Media Corporation (LMC).
 * SBE Corp acquired LMC and continues to make the cards.
 *
 * Since the cards use Tulip Ethernet chips, we started with Matt Thomas'
 * ubiquitous "de" driver.  Michael Graff stripped out the Ethernet stuff
 * and added HSSI stuff.  Basil Gunn ported it to Solaris (lost) and
 * Rob Braun ported it to Linux.  Andrew Stanley-Jones added support
 * for three more cards and wrote the first version of lmcconfig.
 * During 2002-5 David Boggs rewrote it and now feels responsible for it.
 *
 * Responsible Individual:
 *
 * Send bug reports and improvements to <boggs@boggs.palo-alto.ca.us>.
 */
#ifdef __FreeBSD__
# include <sys/param.h>	/* OS version */
# define  IFNET 1
# include "opt_inet.h"	/* INET */
# include "opt_inet6.h"	/* INET6 */
# include "opt_netgraph.h" /* NETGRAPH */
# ifdef HAVE_KERNEL_OPTION_HEADERS
# include "opt_device_polling.h" /* DEVICE_POLLING */
# endif
# ifndef INET
#  define INET 0
# endif
# ifndef INET6
#  define INET6 0
# endif
# ifndef NETGRAPH
#  define NETGRAPH 0
# endif
# define  P2P 0		/* not in FreeBSD */
# if (__FreeBSD_version >= 500000)
#  define NSPPP 1	/* No count devices in FreeBSD 5 */
#  include "opt_bpf.h"	/* DEV_BPF */
#  define NBPFILTER DEV_BPF
# else  /* FreeBSD-4 */
# include "sppp.h"	/* NSPPP */
#  include "bpf.h"	/* NBPF */
#  define NBPFILTER NBPF
# endif
# define  GEN_HDLC 0	/* not in FreeBSD */
#
# include <sys/systm.h>
# include <sys/kernel.h>
# include <sys/malloc.h>
# include <sys/mbuf.h>
# include <sys/socket.h>
# include <sys/sockio.h>
# include <sys/module.h>
# include <sys/bus.h>
# include <sys/lock.h>
# include <net/if.h>
# include <net/if_types.h>
# include <net/if_media.h>
# include <net/netisr.h>
# include <machine/bus.h>
# include <machine/resource.h>
# include <sys/rman.h>
# include <vm/vm.h>
# include <vm/pmap.h>
# if (__FreeBSD_version >= 700000)
#  include <sys/priv.h>
# endif
# if (__FreeBSD_version >= 500000)
#  include <sys/mutex.h>
#  include <dev/pci/pcivar.h>
# else /* FreeBSD-4 */
#  include <sys/proc.h>
#  include <pci/pcivar.h>
# endif
# if NETGRAPH
#  include <netgraph/ng_message.h>
#  include <netgraph/netgraph.h>
# endif
# if (INET || INET6)
#  include <netinet/in.h>
#  include <netinet/in_var.h>
# endif
# if NSPPP
#  include <net/if_sppp.h>
# endif
# if NBPFILTER
#  include <net/bpf.h>
# endif
/* and finally... */
# include <dev/lmc/if_lmc.h>
#endif /*__FreeBSD__*/

#ifdef __NetBSD__
# include <sys/param.h>	/* OS version */
# define  IFNET 1
# include "opt_inet.h"	/* INET6, INET */
# define  NETGRAPH 0	/* not in NetBSD */
# include "sppp.h"	/* NSPPP */
# define  P2P 0		/* not in NetBSD */
# include "opt_altq_enabled.h" /* ALTQ */
# include "bpfilter.h"	/* NBPFILTER */
# define  GEN_HDLC 0	/* not in NetBSD */
#
# include <sys/systm.h>
# include <sys/kernel.h>
# include <sys/lkm.h>
# include <sys/mbuf.h>
# include <sys/socket.h>
# include <sys/sockio.h>
# include <sys/device.h>
# include <sys/lock.h>
# include <net/if.h>
# include <net/if_types.h>
# include <net/if_media.h>
# include <net/netisr.h>
# include <machine/bus.h>
# include <machine/intr.h>
# include <dev/pci/pcivar.h>
# if (__NetBSD_Version__ >= 106000000)
#  include <uvm/uvm_extern.h>
# else
#  include <vm/vm.h>
# endif
# if (INET || INET6)
#  include <netinet/in.h>
#  include <netinet/in_var.h>
# endif
# if NSPPP
#  if (__NetBSD_Version__ >= 106000000)
#   include <net/if_spppvar.h>
#  else
#   include <net/if_sppp.h>
#  endif
# endif
# if NBPFILTER
#  include <net/bpf.h>
# endif
/* and finally... */
# include "if_lmc.h"
#endif /*__NetBSD__*/

#ifdef __OpenBSD__
# include <sys/param.h>	/* OS version */
# define  IFNET 1
/* -DINET  is passed on the compiler command line */
/* -DINET6 is passed on the compiler command line */
# define  NETGRAPH 0	/* not in OpenBSD */
# include "sppp.h"	/* NSPPP */
# define  P2P 0		/* not in OpenBSD */
/* -DALTQ  is passed on the compiler command line */
# include "bpfilter.h"	/* NBPFILTER */
# define  GEN_HDLC 0	/* not in OpenBSD */
#
# include <sys/systm.h>
# include <sys/kernel.h>
# include <sys/conf.h>
# include <sys/exec.h>
# include <sys/lkm.h>
# include <sys/mbuf.h>
# include <sys/socket.h>
# include <sys/sockio.h>
# include <sys/device.h>
# include <sys/lock.h>
# include <net/if.h>
# include <net/if_types.h>
# include <net/if_media.h>
# include <net/netisr.h>
# include <machine/bus.h>
# include <machine/intr.h>
# include <dev/pci/pcivar.h>
# if (OpenBSD >= 200206)
#  include <uvm/uvm_extern.h>
# else
#  include <vm/vm.h>
# endif
# if (INET || INET6)
#  include <netinet/in.h>
#  include <netinet/in_var.h>
# endif
# if NSPPP
#  include <net/if_sppp.h>
# endif
# if NBPFILTER
#  include <net/bpf.h>
# endif
/* and finally... */
# include "if_lmc.h"
#endif /*__OpenBSD__*/

#ifdef __bsdi__
# include <sys/param.h>	/* OS version */
# define  IFNET 1
/* -DINET  is passed on the compiler command line */
/* -DINET6 is passed on the compiler command line */
# define  NETGRAPH 0	/* not in BSD/OS */
# define  NSPPP 0	/* not in BSD/OS */
/* -DPPP   is passed on the compiler command line */
/* -DCISCO_HDLC is passed on the compiler command line */
/* -DFR    is passed on the compiler command line */
# if (PPP || CISCO_HDLC || FR)
#  define P2P 1
# else
#  define P2P 0
# endif
# define  ALTQ 0	/* not in BSD/OS */
# include "bpfilter.h"	/* NBPFILTER */
# define  GEN_HDLC 0	/* not in BSD/OS */
#
# include <sys/kernel.h>
# include <sys/malloc.h>
# include <sys/mbuf.h>
# include <sys/socket.h>
# include <sys/sockio.h>
# include <sys/device.h>
# include <sys/lock.h>
# include <net/if.h>
# include <net/if_types.h>
# include <net/if_media.h>
# include <net/netisr.h>
# include <vm/vm.h>
# include <i386/isa/dma.h>
# include <i386/isa/isavar.h>
# include <i386/include/cpu.h>
# include <i386/pci/pci.h>
# if (INET || INET6)
#  include <netinet/in.h>
#  include <netinet/in_var.h>
# endif
# if P2P
#  include <net/if_p2p.h>
#  include <sys/ttycom.h>
# endif
# if NBPFILTER
#  include <net/bpf.h>
# endif
/* and finally... */
# include "if_lmc.h"
#endif /*__bsdi__*/

#ifdef __linux__
# include <linux/config.h>
# if (CONFIG_HDLC || CONFIG_HDLC_MODULE)
#  define GEN_HDLC 1
# else
#  define GEN_HDLC 0
# endif
# define IFNET 0	/* different in Linux */
# define NETGRAPH 0	/* not in Linux */
# define NSPPP 0	/* different in Linux */
# define P2P 0		/* not in Linux */
# define ALTQ 0		/* different in Linux */
# define NBPFILTER 0	/* different in Linux */
#
# include <linux/pci.h>
# include <linux/delay.h>
# include <linux/netdevice.h>
# include <linux/if_arp.h>
# if GEN_HDLC
#  include <linux/hdlc.h>
# endif
/* and finally... */
# include "if_lmc.h"
#endif /* __linux__ */

/* The SROM is a generic 93C46 serial EEPROM (64 words by 16 bits). */
/* Data is set up before the RISING edge of CLK; CLK is parked low. */
static void
shift_srom_bits(softc_t *sc, u_int32_t data, u_int32_t len)
  {
  u_int32_t csr = READ_CSR(TLP_SROM_MII);
  for (; len>0; len--)
    {  /* MSB first */
    if (data & (1<<(len-1)))
      csr |=  TLP_SROM_DIN;	/* DIN setup */
    else
      csr &= ~TLP_SROM_DIN;	/* DIN setup */
    WRITE_CSR(TLP_SROM_MII, csr);
    csr |=  TLP_SROM_CLK;	/* CLK rising edge */
    WRITE_CSR(TLP_SROM_MII, csr);
    csr &= ~TLP_SROM_CLK;	/* CLK falling edge */
    WRITE_CSR(TLP_SROM_MII, csr);
    }
  }

/* Data is sampled on the RISING edge of CLK; CLK is parked low. */
static u_int16_t
read_srom(softc_t *sc, u_int8_t addr)
  {
  int i;
  u_int32_t csr;
  u_int16_t data;

  /* Enable SROM access. */
  csr = (TLP_SROM_SEL | TLP_SROM_RD | TLP_MII_MDOE);
  WRITE_CSR(TLP_SROM_MII, csr);
  /* CS rising edge prepares SROM for a new cycle. */
  csr |= TLP_SROM_CS;
  WRITE_CSR(TLP_SROM_MII, csr);	/* assert CS */
  shift_srom_bits(sc,  6,   4);		/* issue read cmd */
  shift_srom_bits(sc, addr, 6);		/* issue address */
  for (data=0, i=16; i>=0; i--)		/* read ->17<- bits of data */
    {  /* MSB first */
    csr = READ_CSR(TLP_SROM_MII);	/* DOUT sampled */
    data = (data<<1) | ((csr & TLP_SROM_DOUT) ? 1:0);
    csr |=  TLP_SROM_CLK;		/* CLK rising edge */
    WRITE_CSR(TLP_SROM_MII, csr);
    csr &= ~TLP_SROM_CLK;		/* CLK falling edge */
    WRITE_CSR(TLP_SROM_MII, csr);
    }
  /* Disable SROM access. */
  WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOE);

  return data;
  }

/* The SROM is formatted by the mfgr and should NOT be written! */
/* But lmcconfig can rewrite it in case it gets overwritten somehow. */
/* IOCTL SYSCALL: can sleep. */
static void
write_srom(softc_t *sc, u_int8_t addr, u_int16_t data)
  {
  u_int32_t csr;
  int i;

  /* Enable SROM access. */
  csr = (TLP_SROM_SEL | TLP_SROM_RD | TLP_MII_MDOE);
  WRITE_CSR(TLP_SROM_MII, csr);

  /* Issue write-enable command. */
  csr |= TLP_SROM_CS;
  WRITE_CSR(TLP_SROM_MII, csr);	/* assert CS */
  shift_srom_bits(sc,  4, 4);		/* issue write enable cmd */
  shift_srom_bits(sc, 63, 6);		/* issue address */
  csr &= ~TLP_SROM_CS;
  WRITE_CSR(TLP_SROM_MII, csr);	/* deassert CS */

  /* Issue erase command. */
  csr |= TLP_SROM_CS;
  WRITE_CSR(TLP_SROM_MII, csr);	/* assert CS */
  shift_srom_bits(sc, 7, 4);		/* issue erase cmd */
  shift_srom_bits(sc, addr, 6);		/* issue address */
  csr &= ~TLP_SROM_CS;
  WRITE_CSR(TLP_SROM_MII, csr);	/* deassert CS */

  /* Issue write command. */
  csr |= TLP_SROM_CS;
  WRITE_CSR(TLP_SROM_MII, csr);	/* assert CS */
  for (i=0; i<10; i++)  /* 100 ms max wait */
    if ((READ_CSR(TLP_SROM_MII) & TLP_SROM_DOUT)==0) SLEEP(10000);
  shift_srom_bits(sc, 5, 4);		/* issue write cmd */
  shift_srom_bits(sc, addr, 6);		/* issue address */
  shift_srom_bits(sc, data, 16);	/* issue data */
  csr &= ~TLP_SROM_CS;
  WRITE_CSR(TLP_SROM_MII, csr);	/* deassert CS */

  /* Issue write-disable command. */
  csr |= TLP_SROM_CS;
  WRITE_CSR(TLP_SROM_MII, csr);	/* assert CS */
  for (i=0; i<10; i++)  /* 100 ms max wait */
    if ((READ_CSR(TLP_SROM_MII) & TLP_SROM_DOUT)==0) SLEEP(10000);
  shift_srom_bits(sc, 4, 4);		/* issue write disable cmd */
  shift_srom_bits(sc, 0, 6);		/* issue address */
  csr &= ~TLP_SROM_CS;
  WRITE_CSR(TLP_SROM_MII, csr);	/* deassert CS */

  /* Disable SROM access. */
  WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOE);
  }

/* Not all boards have BIOS roms. */
/* The BIOS ROM is an AMD 29F010 1Mbit (128K by 8) EEPROM. */
static u_int8_t
read_bios(softc_t *sc, u_int32_t addr)
  {
  u_int32_t srom_mii;

  /* Load the BIOS rom address register. */
  WRITE_CSR(TLP_BIOS_ROM, addr);

  /* Enable the BIOS rom. */
  srom_mii = TLP_BIOS_SEL | TLP_BIOS_RD | TLP_MII_MDOE;
  WRITE_CSR(TLP_SROM_MII, srom_mii);

  /* Wait at least 20 PCI cycles. */
  DELAY(20);

  /* Read the BIOS rom data. */
  srom_mii = READ_CSR(TLP_SROM_MII);

  /* Disable the BIOS rom. */
  WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOE);

  return (u_int8_t)srom_mii & 0xFF;
  }

static void
write_bios_phys(softc_t *sc, u_int32_t addr, u_int8_t data)
  {
  u_int32_t srom_mii;

  /* Load the BIOS rom address register. */
  WRITE_CSR(TLP_BIOS_ROM, addr);

  /* Enable the BIOS rom. */
  srom_mii = TLP_BIOS_SEL | TLP_BIOS_WR | TLP_MII_MDOE;

  /* Load the data into the data register. */
  srom_mii = (srom_mii & 0xFFFFFF00) | (data & 0xFF);
  WRITE_CSR(TLP_SROM_MII, srom_mii);

  /* Wait at least 20 PCI cycles. */
  DELAY(20);

  /* Disable the BIOS rom. */
  WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOE);
  }

/* IOCTL SYSCALL: can sleep. */
static void
write_bios(softc_t *sc, u_int32_t addr, u_int8_t data)
  {
  u_int8_t read_data;

  /* this sequence enables writing */
  write_bios_phys(sc, 0x5555, 0xAA);
  write_bios_phys(sc, 0x2AAA, 0x55);
  write_bios_phys(sc, 0x5555, 0xA0);
  write_bios_phys(sc, addr,   data);

  /* Wait for the write operation to complete. */
  for (;;)  /* interruptable syscall */
    {
    for (;;)
      {
      read_data = read_bios(sc, addr);
      if ((read_data & 0x80) == (data & 0x80)) break;
      if  (read_data & 0x20)
        {  /* Data sheet says read it again. */
        read_data = read_bios(sc, addr);
        if ((read_data & 0x80) == (data & 0x80)) break;
        if (DRIVER_DEBUG)
          printf("%s: write_bios() failed; rom addr=0x%x\n",
           NAME_UNIT, addr);
        return;
        }
      }
    read_data = read_bios(sc, addr);
    if (read_data == data) break;
    }
  }

/* IOCTL SYSCALL: can sleep. */
static void
erase_bios(softc_t *sc)
  {
  unsigned char read_data;

  /* This sequence enables erasing: */
  write_bios_phys(sc, 0x5555, 0xAA);
  write_bios_phys(sc, 0x2AAA, 0x55);
  write_bios_phys(sc, 0x5555, 0x80);
  write_bios_phys(sc, 0x5555, 0xAA);
  write_bios_phys(sc, 0x2AAA, 0x55);
  write_bios_phys(sc, 0x5555, 0x10);

  /* Wait for the erase operation to complete. */
  for (;;) /* interruptable syscall */
    {
    for (;;)
      {
      read_data = read_bios(sc, 0);
      if (read_data & 0x80) break;
      if (read_data & 0x20)
        {  /* Data sheet says read it again. */
        read_data = read_bios(sc, 0);
        if (read_data & 0x80) break;
        if (DRIVER_DEBUG)
          printf("%s: erase_bios() failed\n", NAME_UNIT);
        return;
        }
      }
    read_data = read_bios(sc, 0);
    if (read_data == 0xFF) break;
    }
  }

/* MDIO is 3-stated between tranactions. */
/* MDIO is set up before the RISING edge of MDC; MDC is parked low. */
static void
shift_mii_bits(softc_t *sc, u_int32_t data, u_int32_t len)
  {
  u_int32_t csr = READ_CSR(TLP_SROM_MII);
  for (; len>0; len--)
    {  /* MSB first */
    if (data & (1<<(len-1)))
      csr |=  TLP_MII_MDOUT; /* MDOUT setup */
    else
      csr &= ~TLP_MII_MDOUT; /* MDOUT setup */
    WRITE_CSR(TLP_SROM_MII, csr);
    csr |=  TLP_MII_MDC;     /* MDC rising edge */
    WRITE_CSR(TLP_SROM_MII, csr);
    csr &= ~TLP_MII_MDC;     /* MDC falling edge */
    WRITE_CSR(TLP_SROM_MII, csr);
    }
  }

/* The specification for the MII is IEEE Std 802.3 clause 22. */
/* MDIO is sampled on the RISING edge of MDC; MDC is parked low. */
static u_int16_t
read_mii(softc_t *sc, u_int8_t regad)
  {
  int i;
  u_int32_t csr;
  u_int16_t data = 0;
 
  WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOUT);

  shift_mii_bits(sc, 0xFFFFF, 20);	/* preamble */
  shift_mii_bits(sc, 0xFFFFF, 20);	/* preamble */
  shift_mii_bits(sc, 1, 2);		/* start symbol */
  shift_mii_bits(sc, 2, 2);		/* read op */
  shift_mii_bits(sc, 0, 5);		/* phyad=0 */
  shift_mii_bits(sc, regad, 5);		/* regad */
  csr = READ_CSR(TLP_SROM_MII);
  csr |= TLP_MII_MDOE;
  WRITE_CSR(TLP_SROM_MII, csr);
  shift_mii_bits(sc, 0, 2);		/* turn-around */
  for (i=15; i>=0; i--)			/* data */
    {  /* MSB first */
    csr = READ_CSR(TLP_SROM_MII);	/* MDIN sampled */
    data = (data<<1) | ((csr & TLP_MII_MDIN) ? 1:0);
    csr |=  TLP_MII_MDC;		/* MDC rising edge */
    WRITE_CSR(TLP_SROM_MII, csr);
    csr &= ~TLP_MII_MDC;		/* MDC falling edge */
    WRITE_CSR(TLP_SROM_MII, csr);
    }
  return data;
  }

static void
write_mii(softc_t *sc, u_int8_t regad, u_int16_t data)
  {
  WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOUT);
  shift_mii_bits(sc, 0xFFFFF, 20);	/* preamble */
  shift_mii_bits(sc, 0xFFFFF, 20);	/* preamble */
  shift_mii_bits(sc, 1, 2);		/* start symbol */
  shift_mii_bits(sc, 1, 2);		/* write op */
  shift_mii_bits(sc, 0, 5);		/* phyad=0 */
  shift_mii_bits(sc, regad, 5);		/* regad */
  shift_mii_bits(sc, 2, 2);		/* turn-around */
  shift_mii_bits(sc, data, 16);		/* data */
  WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOE);
  if (regad == 16) sc->led_state = data; /* a small optimization */
  }

static void
set_mii16_bits(softc_t *sc, u_int16_t bits)
  {
  u_int16_t mii16 = read_mii(sc, 16);
  mii16 |= bits;
  write_mii(sc, 16, mii16);
  }

static void
clr_mii16_bits(softc_t *sc, u_int16_t bits)
  {
  u_int16_t mii16 = read_mii(sc, 16);
  mii16 &= ~bits;
  write_mii(sc, 16, mii16);
  }

static void
set_mii17_bits(softc_t *sc, u_int16_t bits)
  {
  u_int16_t mii17 = read_mii(sc, 17);
  mii17 |= bits;
  write_mii(sc, 17, mii17);
  }

static void
clr_mii17_bits(softc_t *sc, u_int16_t bits)
  {
  u_int16_t mii17 = read_mii(sc, 17);
  mii17 &= ~bits;
  write_mii(sc, 17, mii17);
  }

/*
 * Watchdog code is more readable if it refreshes LEDs
 *  once a second whether they need it or not.
 * But MII refs take 150 uSecs each, so remember the last value
 *  written to MII16 and avoid LED writes that do nothing.
 */

static void
led_off(softc_t *sc, u_int16_t led)
  {
  if ((led & sc->led_state) == led) return;
  set_mii16_bits(sc, led);
  }

static void
led_on(softc_t *sc, u_int16_t led)
  {
  if ((led & sc->led_state) == 0) return;
  clr_mii16_bits(sc, led);
  }

static void
led_inv(softc_t *sc, u_int16_t led)
  {
  u_int16_t mii16 = read_mii(sc, 16);
  mii16 ^= led;
  write_mii(sc, 16, mii16);
  }

/*
 * T1 & T3 framer registers are accessed through MII regs 17 & 18.
 * Write the address to MII reg 17 then R/W data through MII reg 18.
 * The hardware interface is an Intel-style 8-bit muxed A/D bus.
 */
static void
write_framer(softc_t *sc, u_int16_t addr, u_int8_t data)
  {
  write_mii(sc, 17, addr);
  write_mii(sc, 18, data);
  }

static u_int8_t
read_framer(softc_t *sc, u_int16_t addr)
  {
  write_mii(sc, 17, addr);
  return (u_int8_t)read_mii(sc, 18);
  }

/* Tulip's hardware implementation of General Purpose IO
 *   (GPIO) pins makes life difficult for software.
 * Bits 7-0 in the Tulip GPIO CSR are used for two purposes
 *   depending on the state of bit 8.
 * If bit 8 is 0 then bits 7-0 are "data" bits.
 * If bit 8 is 1 then bits 7-0 are "direction" bits.
 * If a direction bit is one, the data bit is an output.
 * The problem is that the direction bits are WRITE-ONLY.
 * Software must remember the direction bits in a shadow copy.
 * (sc->gpio_dir) in order to change some but not all of the bits.
 * All accesses to the Tulip GPIO register use these five procedures.
 */

static void
make_gpio_input(softc_t *sc, u_int32_t bits)
  {
  sc->gpio_dir &= ~bits;
  WRITE_CSR(TLP_GPIO, TLP_GPIO_DIR | (sc->gpio_dir));
  }

static void
make_gpio_output(softc_t *sc, u_int32_t bits)
  {
  sc->gpio_dir |= bits;
  WRITE_CSR(TLP_GPIO, TLP_GPIO_DIR | (sc->gpio_dir));
  }

static u_int32_t
read_gpio(softc_t *sc)
  {
  return READ_CSR(TLP_GPIO);
  }

static void
set_gpio_bits(softc_t *sc, u_int32_t bits)
  {
  WRITE_CSR(TLP_GPIO, (read_gpio(sc) |  bits) & 0xFF);
  }

static void
clr_gpio_bits(softc_t *sc, u_int32_t bits)
  {
  WRITE_CSR(TLP_GPIO, (read_gpio(sc) & ~bits) & 0xFF);
  }

/* Reset ALL of the flip-flops in the gate array to zero. */
/* This does NOT change the gate array programming. */
/* Called during initialization so it must not sleep. */
static void
reset_xilinx(softc_t *sc)
  {
  /* Drive RESET low to force initialization. */
  clr_gpio_bits(sc, GPIO_RESET);
  make_gpio_output(sc, GPIO_RESET);

  /* Hold RESET low for more than 10 uSec. */
  DELAY(50);

  /* Done with RESET; make it an input. */
  make_gpio_input(sc,  GPIO_RESET);
  }

/* Load Xilinx gate array program from on-board rom. */
/* This changes the gate array programming. */
/* IOCTL SYSCALL: can sleep. */
static void
load_xilinx_from_rom(softc_t *sc)
  {
  int i;

  /* Drive MODE low to load from ROM rather than GPIO. */
  clr_gpio_bits(sc, GPIO_MODE);
  make_gpio_output(sc, GPIO_MODE);

  /* Drive DP & RESET low to force configuration. */
  clr_gpio_bits(sc, GPIO_RESET | GPIO_DP);
  make_gpio_output(sc, GPIO_RESET | GPIO_DP);

  /* Hold RESET & DP low for more than 10 uSec. */
  DELAY(50);

  /* Done with RESET & DP; make them inputs. */
  make_gpio_input(sc, GPIO_DP | GPIO_RESET);

  /* BUSY-WAIT for Xilinx chip to configure itself from ROM bits. */
  for (i=0; i<100; i++) /* 1 sec max delay */
    if ((read_gpio(sc) & GPIO_DP) == 0) SLEEP(10000);

  /* Done with MODE; make it an input. */
  make_gpio_input(sc, GPIO_MODE);
  }

/* Load the Xilinx gate array program from userland bits. */
/* This changes the gate array programming. */
/* IOCTL SYSCALL: can sleep. */
static int
load_xilinx_from_file(softc_t *sc, char *addr, u_int32_t len)
  {
  char *data;
  int i, j, error;

  /* Get some pages to hold the Xilinx bits; biggest file is < 6 KB. */
  if (len > 8192) return EFBIG;  /* too big */
  data = malloc(len, M_DEVBUF, M_WAITOK);
  if (data == NULL) return ENOMEM;

  /* Copy the Xilinx bits from userland. */
  if ((error = copyin(addr, data, len)))
    {
    free(data, M_DEVBUF);
    return error;
    }

  /* Drive MODE high to load from GPIO rather than ROM. */
  set_gpio_bits(sc, GPIO_MODE);
  make_gpio_output(sc, GPIO_MODE);

  /* Drive DP & RESET low to force configuration. */
  clr_gpio_bits(sc, GPIO_RESET | GPIO_DP);
  make_gpio_output(sc, GPIO_RESET | GPIO_DP);

  /* Hold RESET & DP low for more than 10 uSec. */
  DELAY(50);
  
  /* Done with RESET & DP; make them inputs. */
  make_gpio_input(sc, GPIO_RESET | GPIO_DP);

  /* BUSY-WAIT for Xilinx chip to clear its config memory. */
  make_gpio_input(sc, GPIO_INIT);
  for (i=0; i<10000; i++) /* 1 sec max delay */
    if ((read_gpio(sc) & GPIO_INIT)==0) SLEEP(10000);

  /* Configure CLK and DATA as outputs. */
  set_gpio_bits(sc, GPIO_CLK);  /* park CLK high */
  make_gpio_output(sc, GPIO_CLK | GPIO_DATA);

  /* Write bits to Xilinx; CLK is parked HIGH. */
  /* DATA is set up before the RISING edge of CLK. */
  for (i=0; i<len; i++)
    for (j=0; j<8; j++)
      {  /* LSB first */
      if ((data[i] & (1<<j)) != 0)
        set_gpio_bits(sc, GPIO_DATA); /* DATA setup */
      else
        clr_gpio_bits(sc, GPIO_DATA); /* DATA setup */
      clr_gpio_bits(sc, GPIO_CLK); /* CLK falling edge */
      set_gpio_bits(sc, GPIO_CLK); /* CLK rising edge */
      }

  /* Stop driving all Xilinx-related signals. */
  /* Pullup and pulldown resistors take over. */
  make_gpio_input(sc, GPIO_CLK | GPIO_DATA | GPIO_MODE);

  free(data, M_DEVBUF);
  return 0;
  }

/* Write fragments of a command into the synthesized oscillator. */
/* DATA is set up before the RISING edge of CLK.  CLK is parked low. */
static void
shift_synth_bits(softc_t *sc, u_int32_t data, u_int32_t len)
  {
  int i;

  for (i=0; i<len; i++)
    { /* LSB first */
    if ((data & (1<<i)) != 0)
      set_gpio_bits(sc, GPIO_DATA); /* DATA setup */
    else
      clr_gpio_bits(sc, GPIO_DATA); /* DATA setup */
    set_gpio_bits(sc, GPIO_CLK);    /* CLK rising edge */
    clr_gpio_bits(sc, GPIO_CLK);    /* CLK falling edge */
    }
  }

/* Write a command to the synthesized oscillator on SSI and HSSIc. */
static void
write_synth(softc_t *sc, struct synth *synth)
  {
  /* SSI cards have a programmable prescaler */
  if (sc->status.card_type == TLP_CSID_SSI)
    {
    if (synth->prescale == 9) /* divide by 512 */
      set_mii17_bits(sc, MII17_SSI_PRESCALE);
    else                      /* divide by  32 */
      clr_mii17_bits(sc, MII17_SSI_PRESCALE);
    }

  clr_gpio_bits(sc,    GPIO_DATA | GPIO_CLK);
  make_gpio_output(sc, GPIO_DATA | GPIO_CLK);

  /* SYNTH is a low-true chip enable for the AV9110 chip. */
  set_gpio_bits(sc,    GPIO_SSI_SYNTH);
  make_gpio_output(sc, GPIO_SSI_SYNTH);
  clr_gpio_bits(sc,    GPIO_SSI_SYNTH);

  /* Serially shift the command into the AV9110 chip. */
  shift_synth_bits(sc, synth->n, 7);
  shift_synth_bits(sc, synth->m, 7);
  shift_synth_bits(sc, synth->v, 1);
  shift_synth_bits(sc, synth->x, 2);
  shift_synth_bits(sc, synth->r, 2);
  shift_synth_bits(sc, 0x16, 5); /* enable clk/x output */

  /* SYNTH (chip enable) going high ends the command. */
  set_gpio_bits(sc,   GPIO_SSI_SYNTH);
  make_gpio_input(sc, GPIO_SSI_SYNTH);

  /* Stop driving serial-related signals; pullups/pulldowns take over. */
  make_gpio_input(sc, GPIO_DATA | GPIO_CLK);

  /* remember the new synthesizer parameters */
  if (&sc->config.synth != synth) sc->config.synth = *synth;
  }

/* Write a command to the DAC controlling the VCXO on some T3 adapters. */
/* The DAC is a TI-TLV5636: 12-bit resolution and a serial interface. */
/* DATA is set up before the FALLING edge of CLK.  CLK is parked HIGH. */
static void
write_dac(softc_t *sc, u_int16_t data)
  {
  int i;

  /* Prepare to use DATA and CLK. */
  set_gpio_bits(sc,    GPIO_DATA | GPIO_CLK);
  make_gpio_output(sc, GPIO_DATA | GPIO_CLK);

  /* High-to-low transition prepares DAC for new value. */
  set_gpio_bits(sc,    GPIO_T3_DAC);
  make_gpio_output(sc, GPIO_T3_DAC);
  clr_gpio_bits(sc,    GPIO_T3_DAC);

  /* Serially shift command bits into DAC. */
  for (i=0; i<16; i++)
    { /* MSB first */
    if ((data & (1<<(15-i))) != 0)
      set_gpio_bits(sc, GPIO_DATA); /* DATA setup */
    else
      clr_gpio_bits(sc, GPIO_DATA); /* DATA setup */
    clr_gpio_bits(sc, GPIO_CLK);    /* CLK falling edge */
    set_gpio_bits(sc, GPIO_CLK);    /* CLK rising edge */
    }

  /* Done with DAC; make it an input; loads new value into DAC. */
  set_gpio_bits(sc,   GPIO_T3_DAC);
  make_gpio_input(sc, GPIO_T3_DAC);

  /* Stop driving serial-related signals; pullups/pulldowns take over. */
  make_gpio_input(sc, GPIO_DATA | GPIO_CLK);
  }

/* begin HSSI card code */

/* Must not sleep. */
static void
hssi_config(softc_t *sc)
  {
  if (sc->status.card_type == 0)
    { /* defaults */
    sc->status.card_type  = READ_PCI_CFG(sc, TLP_CSID);
    sc->config.crc_len    = CFG_CRC_16;
    sc->config.loop_back  = CFG_LOOP_NONE;
    sc->config.tx_clk_src = CFG_CLKMUX_ST;
    sc->config.dte_dce    = CFG_DTE;
    sc->config.synth.n    = 52; /* 52.000 Mbs */
    sc->config.synth.m    = 5;
    sc->config.synth.v    = 0;
    sc->config.synth.x    = 0;
    sc->config.synth.r    = 0;
    sc->config.synth.prescale = 2;
    }

  /* set CRC length */
  if (sc->config.crc_len == CFG_CRC_32)
    set_mii16_bits(sc, MII16_HSSI_CRC32);
  else
    clr_mii16_bits(sc, MII16_HSSI_CRC32);

  /* Assert pin LA in HSSI conn: ask modem for local loop. */
  if (sc->config.loop_back == CFG_LOOP_LL)
    set_mii16_bits(sc, MII16_HSSI_LA);
  else
    clr_mii16_bits(sc, MII16_HSSI_LA);

  /* Assert pin LB in HSSI conn: ask modem for remote loop. */
  if (sc->config.loop_back == CFG_LOOP_RL)
    set_mii16_bits(sc, MII16_HSSI_LB);
  else
    clr_mii16_bits(sc, MII16_HSSI_LB);

  if (sc->status.card_type == TLP_CSID_HSSI)
    {
    /* set TXCLK src */
    if (sc->config.tx_clk_src == CFG_CLKMUX_ST)
      set_gpio_bits(sc, GPIO_HSSI_TXCLK);
    else
      clr_gpio_bits(sc, GPIO_HSSI_TXCLK);
    make_gpio_output(sc, GPIO_HSSI_TXCLK);
    }
  else if (sc->status.card_type == TLP_CSID_HSSIc)
    {  /* cPCI HSSI rev C has extra features */
    /* Set TXCLK source. */
    u_int16_t mii16 = read_mii(sc, 16);
    mii16 &= ~MII16_HSSI_CLKMUX;
    mii16 |= (sc->config.tx_clk_src&3)<<13;
    write_mii(sc, 16, mii16);

    /* cPCI HSSI implements loopback towards the net. */
    if (sc->config.loop_back == CFG_LOOP_LINE)
      set_mii16_bits(sc, MII16_HSSI_LOOP);
    else
      clr_mii16_bits(sc, MII16_HSSI_LOOP);

    /* Set DTE/DCE mode. */
    if (sc->config.dte_dce == CFG_DCE)
      set_gpio_bits(sc, GPIO_HSSI_DCE);
    else
      clr_gpio_bits(sc, GPIO_HSSI_DCE);
    make_gpio_output(sc, GPIO_HSSI_DCE);

    /* Program the synthesized oscillator. */
    write_synth(sc, &sc->config.synth);
    }
  }

static void
hssi_ident(softc_t *sc)
  {
  }

/* Called once a second; must not sleep. */
static int
hssi_watchdog(softc_t *sc)
  {
  u_int16_t mii16 = read_mii(sc, 16) & MII16_HSSI_MODEM;
  int link_status = STATUS_UP;

  led_inv(sc, MII16_HSSI_LED_UL);  /* Software is alive. */
  led_on(sc, MII16_HSSI_LED_LL);  /* always on (SSI cable) */

  /* Check the transmit clock. */
  if (sc->status.tx_speed == 0)
    {
    led_on(sc, MII16_HSSI_LED_UR);
    link_status = STATUS_DOWN;
    }
  else
    led_off(sc, MII16_HSSI_LED_UR);

  /* Is the modem ready? */
  if ((mii16 & MII16_HSSI_CA) == 0)
    {
    led_off(sc, MII16_HSSI_LED_LR);
    link_status = STATUS_DOWN;
    }
  else
    led_on(sc, MII16_HSSI_LED_LR);

  /* Print the modem control signals if they changed. */
  if ((DRIVER_DEBUG) && (mii16 != sc->last_mii16))
    {
    char *on = "ON ", *off = "OFF";
    printf("%s: TA=%s CA=%s LA=%s LB=%s LC=%s TM=%s\n", NAME_UNIT,
     (mii16 & MII16_HSSI_TA) ? on : off,
     (mii16 & MII16_HSSI_CA) ? on : off,
     (mii16 & MII16_HSSI_LA) ? on : off,
     (mii16 & MII16_HSSI_LB) ? on : off,
     (mii16 & MII16_HSSI_LC) ? on : off,
     (mii16 & MII16_HSSI_TM) ? on : off);
    }

  /* SNMP one-second-report */
  sc->status.snmp.hssi.sigs = mii16 & MII16_HSSI_MODEM;

  /* Remember this state until next time. */
  sc->last_mii16 = mii16;

  /* If a loop back is in effect, link status is UP */
  if (sc->config.loop_back != CFG_LOOP_NONE)
    link_status = STATUS_UP;

  return link_status;
  }

/* IOCTL SYSCALL: can sleep (but doesn't). */
static int
hssi_ioctl(softc_t *sc, struct ioctl *ioctl)
  {
  int error = 0;

  if (ioctl->cmd == IOCTL_SNMP_SIGS)
    {
    u_int16_t mii16 = read_mii(sc, 16);
    mii16 &= ~MII16_HSSI_MODEM;
    mii16 |= (MII16_HSSI_MODEM & ioctl->data);
    write_mii(sc, 16, mii16);
    }
  else if (ioctl->cmd == IOCTL_SET_STATUS)
    {
    if (ioctl->data != 0)
      set_mii16_bits(sc, MII16_HSSI_TA);
    else
      clr_mii16_bits(sc, MII16_HSSI_TA);
    }
  else
    error = EINVAL;

  return error;
  }

/* begin DS3 card code */

/* Must not sleep. */
static void
t3_config(softc_t *sc)
  {
  int i;
  u_int8_t ctl1;

  if (sc->status.card_type == 0)
    { /* defaults */
    sc->status.card_type  = TLP_CSID_T3;
    sc->config.crc_len    = CFG_CRC_16;
    sc->config.loop_back  = CFG_LOOP_NONE;
    sc->config.format     = CFG_FORMAT_T3CPAR;
    sc->config.cable_len  = 10; /* meters */
    sc->config.scrambler  = CFG_SCRAM_DL_KEN;
    sc->config.tx_clk_src = CFG_CLKMUX_INT;

    /* Center the VCXO -- get within 20 PPM of 44736000. */
    write_dac(sc, 0x9002); /* set Vref = 2.048 volts */
    write_dac(sc, 2048); /* range is 0..4095 */
    }

  /* Set cable length. */
  if (sc->config.cable_len > 30)
    clr_mii16_bits(sc, MII16_DS3_ZERO);
  else
    set_mii16_bits(sc, MII16_DS3_ZERO);

  /* Set payload scrambler polynomial. */
  if (sc->config.scrambler == CFG_SCRAM_LARS)
    set_mii16_bits(sc, MII16_DS3_POLY);
  else
    clr_mii16_bits(sc, MII16_DS3_POLY);

  /* Set payload scrambler on/off. */
  if (sc->config.scrambler == CFG_SCRAM_OFF)
    clr_mii16_bits(sc, MII16_DS3_SCRAM);
  else
    set_mii16_bits(sc, MII16_DS3_SCRAM);

  /* Set CRC length. */
  if (sc->config.crc_len == CFG_CRC_32)
    set_mii16_bits(sc, MII16_DS3_CRC32);
  else
    clr_mii16_bits(sc, MII16_DS3_CRC32);

  /* Loopback towards host thru the line interface. */
  if (sc->config.loop_back == CFG_LOOP_OTHER)
    set_mii16_bits(sc, MII16_DS3_TRLBK);
  else
    clr_mii16_bits(sc, MII16_DS3_TRLBK);

  /* Loopback towards network thru the line interface. */
  if (sc->config.loop_back == CFG_LOOP_LINE)
    set_mii16_bits(sc, MII16_DS3_LNLBK);
  else if (sc->config.loop_back == CFG_LOOP_DUAL)
    set_mii16_bits(sc, MII16_DS3_LNLBK);
  else
    clr_mii16_bits(sc, MII16_DS3_LNLBK);

  /* Configure T3 framer chip; write EVERY writeable register. */
  ctl1 = CTL1_SER | CTL1_XTX;
  if (sc->config.loop_back == CFG_LOOP_INWARD) ctl1 |= CTL1_3LOOP;
  if (sc->config.loop_back == CFG_LOOP_DUAL)   ctl1 |= CTL1_3LOOP;
  if (sc->config.format == CFG_FORMAT_T3M13)   ctl1 |= CTL1_M13MODE;
  write_framer(sc, T3CSR_CTL1,     ctl1);
  write_framer(sc, T3CSR_TX_FEAC,  CTL5_EMODE);
  write_framer(sc, T3CSR_CTL8,     CTL8_FBEC);
  write_framer(sc, T3CSR_CTL12,    CTL12_DLCB1 | CTL12_C21 | CTL12_MCB1);
  write_framer(sc, T3CSR_DBL_FEAC, 0);
  write_framer(sc, T3CSR_CTL14,    CTL14_RGCEN | CTL14_TGCEN);
  write_framer(sc, T3CSR_INTEN,    0);
  write_framer(sc, T3CSR_CTL20,    CTL20_CVEN);

  /* Clear error counters and latched error bits */
  /*  that may have happened while initializing. */
  for (i=0; i<21; i++) read_framer(sc, i);
  }

static void
t3_ident(softc_t *sc)
  {
  printf(", TXC03401 rev B");
  }

/* Called once a second; must not sleep. */
static int
t3_watchdog(softc_t *sc)
  {
  u_int16_t CV;
  u_int8_t CERR, PERR, MERR, FERR, FEBE;
  u_int8_t ctl1, stat16, feac;
  int link_status = STATUS_UP;
  u_int16_t mii16;

  /* Read the alarm registers. */
  ctl1   = read_framer(sc, T3CSR_CTL1);
  stat16 = read_framer(sc, T3CSR_STAT16);
  mii16  = read_mii(sc, 16);

  /* Always ignore the RTLOC alarm bit. */
  stat16 &= ~STAT16_RTLOC;

  /* Software is alive. */
  led_inv(sc, MII16_DS3_LED_GRN);

  /* Receiving Alarm Indication Signal (AIS). */
  if ((stat16 & STAT16_RAIS) != 0) /* receiving ais */
    led_on(sc, MII16_DS3_LED_BLU);
  else if (ctl1 & CTL1_TXAIS) /* sending ais */
    led_inv(sc, MII16_DS3_LED_BLU);
  else
    led_off(sc, MII16_DS3_LED_BLU);

  /* Receiving Remote Alarm Indication (RAI). */
  if ((stat16 & STAT16_XERR) != 0) /* receiving rai */
    led_on(sc, MII16_DS3_LED_YEL);
  else if ((ctl1 & CTL1_XTX) == 0) /* sending rai */
    led_inv(sc, MII16_DS3_LED_YEL);
  else
    led_off(sc, MII16_DS3_LED_YEL);

  /* If certain status bits are set then the link is 'down'. */
  /* The bad bits are: rxlos rxoof rxais rxidl xerr. */
  if ((stat16 & ~(STAT16_FEAC | STAT16_SEF)) != 0)
    link_status = STATUS_DOWN;

  /* Declare local Red Alarm if the link is down. */
  if (link_status == STATUS_DOWN)
    led_on(sc, MII16_DS3_LED_RED);
  else if (sc->loop_timer != 0) /* loopback is active */
    led_inv(sc, MII16_DS3_LED_RED);
  else
    led_off(sc, MII16_DS3_LED_RED);

  /* Print latched error bits if they changed. */
  if ((DRIVER_DEBUG) && ((stat16 & ~STAT16_FEAC) != sc->last_stat16))
    {
    char *on = "ON ", *off = "OFF";
    printf("%s: RLOS=%s ROOF=%s RAIS=%s RIDL=%s SEF=%s XERR=%s\n",
     NAME_UNIT,
     (stat16 & STAT16_RLOS) ? on : off,
     (stat16 & STAT16_ROOF) ? on : off,
     (stat16 & STAT16_RAIS) ? on : off,
     (stat16 & STAT16_RIDL) ? on : off,
     (stat16 & STAT16_SEF)  ? on : off,
     (stat16 & STAT16_XERR) ? on : off);
    }

  /* Check and print error counters if non-zero. */
  CV   = read_framer(sc, T3CSR_CVHI)<<8;
  CV  += read_framer(sc, T3CSR_CVLO);
  PERR = read_framer(sc, T3CSR_PERR);
  CERR = read_framer(sc, T3CSR_CERR);
  FERR = read_framer(sc, T3CSR_FERR);
  MERR = read_framer(sc, T3CSR_MERR);
  FEBE = read_framer(sc, T3CSR_FEBE);

  /* CV is invalid during LOS. */
  if ((stat16 & STAT16_RLOS)!=0) CV = 0;
  /* CERR & FEBE are invalid in M13 mode */
  if (sc->config.format == CFG_FORMAT_T3M13) CERR = FEBE = 0;
  /* FEBE is invalid during AIS. */
  if ((stat16 & STAT16_RAIS)!=0) FEBE = 0;
  if (DRIVER_DEBUG && (CV || PERR || CERR || FERR || MERR || FEBE))
    printf("%s: CV=%u PERR=%u CERR=%u FERR=%u MERR=%u FEBE=%u\n",
     NAME_UNIT, CV,   PERR,   CERR,   FERR,   MERR,   FEBE);

  /* Driver keeps crude link-level error counters (SNMP is better). */
  sc->status.cntrs.lcv_errs  += CV;
  sc->status.cntrs.par_errs  += PERR;
  sc->status.cntrs.cpar_errs += CERR;
  sc->status.cntrs.frm_errs  += FERR;
  sc->status.cntrs.mfrm_errs += MERR;
  sc->status.cntrs.febe_errs += FEBE;

  /* Check for FEAC messages (FEAC not defined in M13 mode). */
  if (FORMAT_T3CPAR && (stat16 & STAT16_FEAC)) do
    {
    feac = read_framer(sc, T3CSR_FEAC_STK);
    if ((feac & FEAC_STK_VALID)==0) break;
    /* Ignore RxFEACs while a far end loopback has been requested. */
    if ((sc->status.snmp.t3.line & TLOOP_FAR_LINE)!=0) continue;
    switch (feac & FEAC_STK_FEAC)
      {
      case T3BOP_LINE_UP:   break;
      case T3BOP_LINE_DOWN: break;
      case T3BOP_LOOP_DS3:
        {
        if (sc->last_FEAC == T3BOP_LINE_DOWN)
          {
          if (DRIVER_DEBUG)
            printf("%s: Received a 'line loopback deactivate' FEAC msg\n", NAME_UNIT);
          clr_mii16_bits(sc, MII16_DS3_LNLBK);
          sc->loop_timer = 0;
	  }
        if (sc->last_FEAC == T3BOP_LINE_UP)
          {
          if (DRIVER_DEBUG)
            printf("%s: Received a 'line loopback activate' FEAC msg\n", NAME_UNIT);
          set_mii16_bits(sc, MII16_DS3_LNLBK);
          sc->loop_timer = 300;
	  }
        break;
        }
      case T3BOP_OOF:
        {
        if (DRIVER_DEBUG)
          printf("%s: Received a 'far end LOF' FEAC msg\n", NAME_UNIT);
        break;
	}
      case T3BOP_IDLE:
        {
        if (DRIVER_DEBUG)
          printf("%s: Received a 'far end IDL' FEAC msg\n", NAME_UNIT);
        break;
	}
      case T3BOP_AIS:
        {
        if (DRIVER_DEBUG)
          printf("%s: Received a 'far end AIS' FEAC msg\n", NAME_UNIT);
        break;
	}
      case T3BOP_LOS:
        {
        if (DRIVER_DEBUG)
          printf("%s: Received a 'far end LOS' FEAC msg\n", NAME_UNIT);
        break;
	}
      default:
        {
        if (DRIVER_DEBUG)
          printf("%s: Received a 'type 0x%02X' FEAC msg\n", NAME_UNIT, feac & FEAC_STK_FEAC);
        break;
	}
      }
    sc->last_FEAC = feac & FEAC_STK_FEAC;
    } while ((feac & FEAC_STK_MORE) != 0);
  stat16 &= ~STAT16_FEAC;

  /* Send Service-Affecting priority FEAC messages */
  if (((sc->last_stat16 ^ stat16) & 0xF0) && (FORMAT_T3CPAR))
    {
    /* Transmit continuous FEACs */
    write_framer(sc, T3CSR_CTL14,
     read_framer(sc, T3CSR_CTL14) & ~CTL14_FEAC10);
    if      ((stat16 & STAT16_RLOS)!=0)
      write_framer(sc, T3CSR_TX_FEAC, 0xC0 + T3BOP_LOS);
    else if ((stat16 & STAT16_ROOF)!=0)
      write_framer(sc, T3CSR_TX_FEAC, 0xC0 + T3BOP_OOF);
    else if ((stat16 & STAT16_RAIS)!=0)
      write_framer(sc, T3CSR_TX_FEAC, 0xC0 + T3BOP_AIS);
    else if ((stat16 & STAT16_RIDL)!=0)
      write_framer(sc, T3CSR_TX_FEAC, 0xC0 + T3BOP_IDLE);
    else
      write_framer(sc, T3CSR_TX_FEAC, CTL5_EMODE);
    }

  /* Start sending RAI, Remote Alarm Indication. */
  if (((stat16 & STAT16_ROOF)!=0) && ((stat16 & STAT16_RLOS)==0) &&
   ((sc->last_stat16 & STAT16_ROOF)==0))
    write_framer(sc, T3CSR_CTL1, ctl1 &= ~CTL1_XTX);
  /* Stop sending RAI, Remote Alarm Indication. */
  else if (((stat16 & STAT16_ROOF)==0) && ((sc->last_stat16 & STAT16_ROOF)!=0))
    write_framer(sc, T3CSR_CTL1, ctl1 |=  CTL1_XTX);

  /* Start sending AIS, Alarm Indication Signal */
  if (((stat16 & STAT16_RLOS)!=0) && ((sc->last_stat16 & STAT16_RLOS)==0))
    {
    set_mii16_bits(sc, MII16_DS3_FRAME);
    write_framer(sc, T3CSR_CTL1, ctl1 |  CTL1_TXAIS);
    }
  /* Stop sending AIS, Alarm Indication Signal */
  else if (((stat16 & STAT16_RLOS)==0) && ((sc->last_stat16 & STAT16_RLOS)!=0))
    {
    clr_mii16_bits(sc, MII16_DS3_FRAME);
    write_framer(sc, T3CSR_CTL1, ctl1 & ~CTL1_TXAIS);
    }

  /* Time out loopback requests. */
  if (sc->loop_timer != 0)
    if (--sc->loop_timer == 0)
      if ((mii16 & MII16_DS3_LNLBK)!=0)
        {
        if (DRIVER_DEBUG)
          printf("%s: Timeout: Loop Down after 300 seconds\n", NAME_UNIT);
        clr_mii16_bits(sc, MII16_DS3_LNLBK); /* line loopback off */
        }

  /* SNMP error counters */
  sc->status.snmp.t3.lcv  = CV;
  sc->status.snmp.t3.pcv  = PERR;
  sc->status.snmp.t3.ccv  = CERR;
  sc->status.snmp.t3.febe = FEBE;

  /* SNMP Line Status */
  sc->status.snmp.t3.line = 0;
  if ((ctl1  & CTL1_XTX)==0)   sc->status.snmp.t3.line |= TLINE_TX_RAI;
  if (stat16 & STAT16_XERR)    sc->status.snmp.t3.line |= TLINE_RX_RAI;
  if (ctl1   & CTL1_TXAIS)     sc->status.snmp.t3.line |= TLINE_TX_AIS;
  if (stat16 & STAT16_RAIS)    sc->status.snmp.t3.line |= TLINE_RX_AIS;
  if (stat16 & STAT16_ROOF)    sc->status.snmp.t3.line |= TLINE_LOF;
  if (stat16 & STAT16_RLOS)    sc->status.snmp.t3.line |= TLINE_LOS;
  if (stat16 & STAT16_SEF)     sc->status.snmp.t3.line |= T3LINE_SEF;

  /* SNMP Loopback Status */
  sc->status.snmp.t3.loop &= ~TLOOP_FAR_LINE;
  if (sc->config.loop_back == CFG_LOOP_TULIP)
                               sc->status.snmp.t3.loop |= TLOOP_NEAR_OTHER;
  if (ctl1  & CTL1_3LOOP)      sc->status.snmp.t3.loop |= TLOOP_NEAR_INWARD;
  if (mii16 & MII16_DS3_TRLBK) sc->status.snmp.t3.loop |= TLOOP_NEAR_OTHER;
  if (mii16 & MII16_DS3_LNLBK) sc->status.snmp.t3.loop |= TLOOP_NEAR_LINE;
/*if (ctl12 & CTL12_RTPLOOP)   sc->status.snmp.t3.loop |= TLOOP_NEAR_PAYLOAD; */

  /* Remember this state until next time. */
  sc->last_stat16 = stat16;

  /* If an INWARD loopback is in effect, link status is UP */
  if (sc->config.loop_back != CFG_LOOP_NONE) /* XXX INWARD ONLY */
    link_status = STATUS_UP;

  return link_status;
  }

/* IOCTL SYSCALL: can sleep. */
static void
t3_send_dbl_feac(softc_t *sc, int feac1, int feac2)
  {
  u_int8_t tx_feac;
  int i;

  /* The FEAC transmitter could be sending a continuous */
  /*  FEAC msg when told to send a double FEAC message. */
  /* So save the current state of the FEAC transmitter. */
  tx_feac = read_framer(sc, T3CSR_TX_FEAC);
  /* Load second FEAC code and stop FEAC transmitter. */
  write_framer(sc, T3CSR_TX_FEAC,  CTL5_EMODE + feac2);
  /* FEAC transmitter sends 10 more FEACs and then stops. */
  SLEEP(20000); /* sending one FEAC takes 1700 uSecs */
  /* Load first FEAC code and start FEAC transmitter. */
  write_framer(sc, T3CSR_DBL_FEAC, CTL13_DFEXEC + feac1);
  /* Wait for double FEAC sequence to complete -- about 70 ms. */
  for (i=0; i<10; i++) /* max delay 100 ms */
    if (read_framer(sc, T3CSR_DBL_FEAC) & CTL13_DFEXEC) SLEEP(10000);
  /* Flush received FEACS; don't respond to our own loop cmd! */
  while (read_framer(sc, T3CSR_FEAC_STK) & FEAC_STK_VALID) DELAY(1); /* XXX HANG */
  /* Restore previous state of the FEAC transmitter. */
  /* If it was sending a continous FEAC, it will resume. */
  write_framer(sc, T3CSR_TX_FEAC, tx_feac);
  }

/* IOCTL SYSCALL: can sleep. */
static int
t3_ioctl(softc_t *sc, struct ioctl *ioctl)
  {
  int error = 0;

  switch (ioctl->cmd)
    {
    case IOCTL_SNMP_SEND:  /* set opstatus? */
      {
      if (sc->config.format != CFG_FORMAT_T3CPAR)
        error = EINVAL;
      else if (ioctl->data == TSEND_LINE)
        {
        sc->status.snmp.t3.loop |= TLOOP_FAR_LINE;
        t3_send_dbl_feac(sc, T3BOP_LINE_UP, T3BOP_LOOP_DS3);
        }
      else if (ioctl->data == TSEND_RESET)
        {
        t3_send_dbl_feac(sc, T3BOP_LINE_DOWN, T3BOP_LOOP_DS3);
        sc->status.snmp.t3.loop &= ~TLOOP_FAR_LINE;
        }
      else
        error = EINVAL;
      break;
      }
    case IOCTL_SNMP_LOOP:  /* set opstatus = test? */
      {
      if (ioctl->data == CFG_LOOP_NONE)
        {
        clr_mii16_bits(sc, MII16_DS3_FRAME);
        clr_mii16_bits(sc, MII16_DS3_TRLBK);
        clr_mii16_bits(sc, MII16_DS3_LNLBK);
        write_framer(sc, T3CSR_CTL1,
         read_framer(sc, T3CSR_CTL1) & ~CTL1_3LOOP);
        write_framer(sc, T3CSR_CTL12,
         read_framer(sc, T3CSR_CTL12) & ~(CTL12_RTPLOOP | CTL12_RTPLLEN));
	}
      else if (ioctl->data == CFG_LOOP_LINE)
        set_mii16_bits(sc, MII16_DS3_LNLBK);
      else if (ioctl->data == CFG_LOOP_OTHER)
        set_mii16_bits(sc, MII16_DS3_TRLBK);
      else if (ioctl->data == CFG_LOOP_INWARD)
        write_framer(sc, T3CSR_CTL1,
         read_framer(sc, T3CSR_CTL1) | CTL1_3LOOP);
      else if (ioctl->data == CFG_LOOP_DUAL)
        {
        set_mii16_bits(sc, MII16_DS3_LNLBK);
        write_framer(sc, T3CSR_CTL1,
         read_framer(sc, T3CSR_CTL1) | CTL1_3LOOP);
	}
      else if (ioctl->data == CFG_LOOP_PAYLOAD)
        {
        set_mii16_bits(sc, MII16_DS3_FRAME);
        write_framer(sc, T3CSR_CTL12,
         read_framer(sc, T3CSR_CTL12) |  CTL12_RTPLOOP);
        write_framer(sc, T3CSR_CTL12,
         read_framer(sc, T3CSR_CTL12) |  CTL12_RTPLLEN);
        DELAY(25); /* at least two frames (22 uS) */
        write_framer(sc, T3CSR_CTL12,
         read_framer(sc, T3CSR_CTL12) & ~CTL12_RTPLLEN);
	}
      else
        error = EINVAL;
      break;
      }
    default:
      error = EINVAL;
      break;
    }

  return error;
  }

/* begin SSI card code */

/* Must not sleep. */
static void
ssi_config(softc_t *sc)
  {
  if (sc->status.card_type == 0)
    { /* defaults */
    sc->status.card_type  = TLP_CSID_SSI;
    sc->config.crc_len    = CFG_CRC_16;
    sc->config.loop_back  = CFG_LOOP_NONE;
    sc->config.tx_clk_src = CFG_CLKMUX_ST;
    sc->config.dte_dce    = CFG_DTE;
    sc->config.synth.n    = 51; /* 1.536 MHz */
    sc->config.synth.m    = 83;
    sc->config.synth.v    =  1;
    sc->config.synth.x    =  1;
    sc->config.synth.r    =  1;
    sc->config.synth.prescale = 4;
    }

  /* Disable the TX clock driver while programming the oscillator. */
  clr_gpio_bits(sc, GPIO_SSI_DCE);
  make_gpio_output(sc, GPIO_SSI_DCE);

  /* Program the synthesized oscillator. */
  write_synth(sc, &sc->config.synth);

  /* Set DTE/DCE mode. */
  /* If DTE mode then DCD & TXC are received. */
  /* If DCE mode then DCD & TXC are driven. */
  /* Boards with MII rev=4.0 don't drive DCD. */
  if (sc->config.dte_dce == CFG_DCE)
    set_gpio_bits(sc, GPIO_SSI_DCE);
  else
    clr_gpio_bits(sc, GPIO_SSI_DCE);
  make_gpio_output(sc, GPIO_SSI_DCE);

  /* Set CRC length. */
  if (sc->config.crc_len == CFG_CRC_32)
    set_mii16_bits(sc, MII16_SSI_CRC32);
  else
    clr_mii16_bits(sc, MII16_SSI_CRC32);

  /* Loop towards host thru cable drivers and receivers. */
  /* Asserts DCD at the far end of a null modem cable. */
  if (sc->config.loop_back == CFG_LOOP_PINS)
    set_mii16_bits(sc, MII16_SSI_LOOP);
  else
    clr_mii16_bits(sc, MII16_SSI_LOOP);

  /* Assert pin LL in modem conn: ask modem for local loop. */
  /* Asserts TM at the far end of a null modem cable. */
  if (sc->config.loop_back == CFG_LOOP_LL)
    set_mii16_bits(sc, MII16_SSI_LL);
  else
    clr_mii16_bits(sc, MII16_SSI_LL);

  /* Assert pin RL in modem conn: ask modem for remote loop. */
  if (sc->config.loop_back == CFG_LOOP_RL)
    set_mii16_bits(sc, MII16_SSI_RL);
  else
    clr_mii16_bits(sc, MII16_SSI_RL);
  }

static void
ssi_ident(softc_t *sc)
  {
  printf(", LTC1343/44");
  }

/* Called once a second; must not sleep. */
static int
ssi_watchdog(softc_t *sc)
  {
  u_int16_t cable;
  u_int16_t mii16 = read_mii(sc, 16) & MII16_SSI_MODEM;
  int link_status = STATUS_UP;

  /* Software is alive. */
  led_inv(sc, MII16_SSI_LED_UL);

  /* Check the transmit clock. */
  if (sc->status.tx_speed == 0)
    {
    led_on(sc, MII16_SSI_LED_UR);
    link_status = STATUS_DOWN;
    }
  else
    led_off(sc, MII16_SSI_LED_UR);

  /* Check the external cable. */
  cable = read_mii(sc, 17);
  cable = cable &  MII17_SSI_CABLE_MASK;
  cable = cable >> MII17_SSI_CABLE_SHIFT;
  if (cable == 7)
    {
    led_off(sc, MII16_SSI_LED_LL); /* no cable */
    link_status = STATUS_DOWN;
    }
  else
    led_on(sc, MII16_SSI_LED_LL);

  /* The unit at the other end of the cable is ready if: */
  /*  DTE mode and DCD pin is asserted */
  /*  DCE mode and DSR pin is asserted */
  if (((sc->config.dte_dce == CFG_DTE) && ((mii16 & MII16_SSI_DCD)==0)) ||
      ((sc->config.dte_dce == CFG_DCE) && ((mii16 & MII16_SSI_DSR)==0)))
    {
    led_off(sc, MII16_SSI_LED_LR);
    link_status = STATUS_DOWN;
    }
  else
    led_on(sc, MII16_SSI_LED_LR);

  if (DRIVER_DEBUG && (cable != sc->status.cable_type))
    printf("%s: SSI cable type changed to '%s'\n",
     NAME_UNIT, ssi_cables[cable]);
  sc->status.cable_type = cable;

  /* Print the modem control signals if they changed. */
  if ((DRIVER_DEBUG) && (mii16 != sc->last_mii16))
    {
    char *on = "ON ", *off = "OFF";
    printf("%s: DTR=%s DSR=%s RTS=%s CTS=%s DCD=%s RI=%s LL=%s RL=%s TM=%s\n",
     NAME_UNIT,
     (mii16 & MII16_SSI_DTR) ? on : off,
     (mii16 & MII16_SSI_DSR) ? on : off,
     (mii16 & MII16_SSI_RTS) ? on : off,
     (mii16 & MII16_SSI_CTS) ? on : off,
     (mii16 & MII16_SSI_DCD) ? on : off,
     (mii16 & MII16_SSI_RI)  ? on : off,
     (mii16 & MII16_SSI_LL)  ? on : off,
     (mii16 & MII16_SSI_RL)  ? on : off,
     (mii16 & MII16_SSI_TM)  ? on : off);
    }

  /* SNMP one-second report */
  sc->status.snmp.ssi.sigs = mii16 & MII16_SSI_MODEM;

  /* Remember this state until next time. */
  sc->last_mii16 = mii16;

  /* If a loop back is in effect, link status is UP */
  if (sc->config.loop_back != CFG_LOOP_NONE)
    link_status = STATUS_UP;

  return link_status;
  }

/* IOCTL SYSCALL: can sleep (but doesn't). */
static int
ssi_ioctl(softc_t *sc, struct ioctl *ioctl)
  {
  int error = 0;

  if (ioctl->cmd == IOCTL_SNMP_SIGS)
    {
    u_int16_t mii16 = read_mii(sc, 16);
    mii16 &= ~MII16_SSI_MODEM;
    mii16 |= (MII16_SSI_MODEM & ioctl->data);
    write_mii(sc, 16, mii16);
    }
  else if (ioctl->cmd == IOCTL_SET_STATUS)
    {
    if (ioctl->data != 0)
      set_mii16_bits(sc, (MII16_SSI_DTR | MII16_SSI_RTS | MII16_SSI_DCD));
    else
      clr_mii16_bits(sc, (MII16_SSI_DTR | MII16_SSI_RTS | MII16_SSI_DCD));
    }
  else
    error = EINVAL;

  return error;
  }

/* begin T1E1 card code */

/* Must not sleep. */
static void
t1_config(softc_t *sc)
  {
  int i;
  u_int8_t pulse, lbo, gain;

  if (sc->status.card_type == 0)
    {  /* defaults */
    sc->status.card_type   = TLP_CSID_T1E1;
    sc->config.crc_len     = CFG_CRC_16;
    sc->config.loop_back   = CFG_LOOP_NONE;
    sc->config.tx_clk_src  = CFG_CLKMUX_INT;
    sc->config.format      = CFG_FORMAT_T1ESF;
    sc->config.cable_len   = 10;
    sc->config.time_slots  = 0x01FFFFFE;
    sc->config.tx_pulse    = CFG_PULSE_AUTO;
    sc->config.rx_gain     = CFG_GAIN_AUTO;
    sc->config.tx_lbo      = CFG_LBO_AUTO;

    /* Bt8370 occasionally powers up in a loopback mode. */
    /* Data sheet says zero LOOP reg and do a s/w reset. */
    write_framer(sc, Bt8370_LOOP, 0x00); /* no loopback */
    write_framer(sc, Bt8370_CR0,  0x80); /* s/w reset */
    for (i=0; i<10; i++) /* max delay 10 ms */
      if (read_framer(sc, Bt8370_CR0) & 0x80) DELAY(1000);
    }

  /* Set CRC length. */
  if (sc->config.crc_len == CFG_CRC_32)
    set_mii16_bits(sc, MII16_T1_CRC32);
  else
    clr_mii16_bits(sc, MII16_T1_CRC32);

  /* Invert HDLC payload data in SF/AMI mode. */
  /* HDLC stuff bits satisfy T1 pulse density. */
  if (FORMAT_T1SF)
    set_mii16_bits(sc, MII16_T1_INVERT);
  else
    clr_mii16_bits(sc, MII16_T1_INVERT);

  /* Set the transmitter output impedance. */
  if (FORMAT_E1ANY) set_mii16_bits(sc, MII16_T1_Z);

  /* 001:CR0 -- Control Register 0 - T1/E1 and frame format */
  write_framer(sc, Bt8370_CR0, sc->config.format);

  /* 002:JAT_CR -- Jitter Attenuator Control Register */
  if (sc->config.tx_clk_src == CFG_CLKMUX_RT) /* loop timing */
    write_framer(sc, Bt8370_JAT_CR, 0xA3); /* JAT in RX path */
  else
    { /* 64-bit elastic store; free-running JCLK and CLADO */
    write_framer(sc, Bt8370_JAT_CR, 0x4B); /* assert jcenter */
    write_framer(sc, Bt8370_JAT_CR, 0x43); /* release jcenter */
    }

  /* 00C-013:IERn -- Interrupt Enable Registers */
  for (i=Bt8370_IER7; i<=Bt8370_IER0; i++)
    write_framer(sc, i, 0); /* no interrupts; polled */

  /* 014:LOOP -- loopbacks */
  if      (sc->config.loop_back == CFG_LOOP_PAYLOAD)
    write_framer(sc, Bt8370_LOOP, LOOP_PAYLOAD);
  else if (sc->config.loop_back == CFG_LOOP_LINE)
    write_framer(sc, Bt8370_LOOP, LOOP_LINE);
  else if (sc->config.loop_back == CFG_LOOP_OTHER)
    write_framer(sc, Bt8370_LOOP, LOOP_ANALOG);
  else if (sc->config.loop_back == CFG_LOOP_INWARD)
    write_framer(sc, Bt8370_LOOP, LOOP_FRAMER);
  else if (sc->config.loop_back == CFG_LOOP_DUAL)
    write_framer(sc, Bt8370_LOOP, LOOP_DUAL);
  else
    write_framer(sc, Bt8370_LOOP, 0x00); /* no loopback */

  /* 015:DL3_TS -- Data Link 3 */
  write_framer(sc, Bt8370_DL3_TS, 0x00); /* disabled */

  /* 018:PIO -- Programmable I/O */
  write_framer(sc, Bt8370_PIO, 0xFF); /* all pins are outputs */

  /* 019:POE -- Programmable Output Enable */
  write_framer(sc, Bt8370_POE, 0x00); /* all outputs are enabled */

  /* 01A;CMUX -- Clock Input Mux */
  if (sc->config.tx_clk_src == CFG_CLKMUX_EXT)
    write_framer(sc, Bt8370_CMUX, 0x0C); /* external timing */
  else
    write_framer(sc, Bt8370_CMUX, 0x0F); /* internal timing */

  /* 020:LIU_CR -- Line Interface Unit Config Register */
  write_framer(sc, Bt8370_LIU_CR, 0xC1); /* reset LIU, squelch */

  /* 022:RLIU_CR -- RX Line Interface Unit Config Reg */
  /* Errata sheet says don't use freeze-short, but we do anyway! */
  write_framer(sc, Bt8370_RLIU_CR, 0xB1); /* AGC=2048, Long Eye */

  /* Select Rx sensitivity based on cable length. */
  if ((gain = sc->config.rx_gain) == CFG_GAIN_AUTO)
    {
    if      (sc->config.cable_len > 2000)
      gain = CFG_GAIN_EXTEND;
    else if (sc->config.cable_len > 1000)
      gain = CFG_GAIN_LONG;
    else if (sc->config.cable_len > 100)
      gain = CFG_GAIN_MEDIUM;
    else
      gain = CFG_GAIN_SHORT;
    }

  /* 024:VGA_MAX -- Variable Gain Amplifier Max gain */
  write_framer(sc, Bt8370_VGA_MAX, gain);

  /* 028:PRE_EQ -- Pre Equalizer */
  if (gain == CFG_GAIN_EXTEND)
    write_framer(sc, Bt8370_PRE_EQ, 0xE6);  /* ON; thresh 6 */
  else
    write_framer(sc, Bt8370_PRE_EQ, 0xA6);  /* OFF; thresh 6 */

  /* 038-03C:GAINn -- RX Equalizer gain thresholds */
  write_framer(sc, Bt8370_GAIN0, 0x24);
  write_framer(sc, Bt8370_GAIN1, 0x28);
  write_framer(sc, Bt8370_GAIN2, 0x2C);
  write_framer(sc, Bt8370_GAIN3, 0x30);
  write_framer(sc, Bt8370_GAIN4, 0x34);

  /* 040:RCR0 -- Receiver Control Register 0 */
  if      (FORMAT_T1ESF)
    write_framer(sc, Bt8370_RCR0, 0x05); /* B8ZS, 2/5 FErrs */
  else if (FORMAT_T1SF)
    write_framer(sc, Bt8370_RCR0, 0x84); /* AMI,  2/5 FErrs */
  else if (FORMAT_E1NONE)
    write_framer(sc, Bt8370_RCR0, 0x41); /* HDB3, rabort */
  else if (FORMAT_E1CRC)
    write_framer(sc, Bt8370_RCR0, 0x09); /* HDB3, 3 FErrs or 915 CErrs */
  else  /* E1 no CRC */
    write_framer(sc, Bt8370_RCR0, 0x19); /* HDB3, 3 FErrs */

  /* 041:RPATT -- Receive Test Pattern configuration */
  write_framer(sc, Bt8370_RPATT, 0x3E); /* looking for framed QRSS */

  /* 042:RLB -- Receive Loop Back code detector config */
  write_framer(sc, Bt8370_RLB, 0x09); /* 6 bits down; 5 bits up */

  /* 043:LBA -- Loop Back Activate code */
  write_framer(sc, Bt8370_LBA, 0x08); /* 10000 10000 10000 ... */

  /* 044:LBD -- Loop Back Deactivate code */
  write_framer(sc, Bt8370_LBD, 0x24); /* 100100 100100 100100 ... */

  /* 045:RALM -- Receive Alarm signal configuration */
  write_framer(sc, Bt8370_RALM, 0x0C); /* yel_intg rlof_intg */

  /* 046:LATCH -- Alarm/Error/Counter Latch register */
  write_framer(sc, Bt8370_LATCH, 0x1F); /* stop_cnt latch_{cnt,err,alm} */

  /* Select Pulse Shape based on cable length (T1 only). */
  if ((pulse = sc->config.tx_pulse) == CFG_PULSE_AUTO)
    {
    if (FORMAT_T1ANY)
      {
      if      (sc->config.cable_len > 200)
        pulse = CFG_PULSE_T1CSU;
      else if (sc->config.cable_len > 160)
        pulse = CFG_PULSE_T1DSX4;
      else if (sc->config.cable_len > 120)
        pulse = CFG_PULSE_T1DSX3;
      else if (sc->config.cable_len > 80)
        pulse = CFG_PULSE_T1DSX2;
      else if (sc->config.cable_len > 40)
        pulse = CFG_PULSE_T1DSX1;
      else
        pulse = CFG_PULSE_T1DSX0;
      }
    else
      pulse = CFG_PULSE_E1TWIST;
    }

  /* Select Line Build Out based on cable length (T1CSU only). */
  if ((lbo = sc->config.tx_lbo) == CFG_LBO_AUTO)
    {
    if (pulse == CFG_PULSE_T1CSU)
      {
      if      (sc->config.cable_len > 1500)
        lbo = CFG_LBO_0DB;
      else if (sc->config.cable_len > 1000)
        lbo = CFG_LBO_7DB;
      else if (sc->config.cable_len >  500)
        lbo = CFG_LBO_15DB;
      else
        lbo = CFG_LBO_22DB;
      }
    else
      lbo = 0;
    }

  /* 068:TLIU_CR -- Transmit LIU Control Register */
  write_framer(sc, Bt8370_TLIU_CR, (0x40 | (lbo & 0x30) | (pulse & 0x0E)));

  /* 070:TCR0 -- Transmit Framer Configuration */
  write_framer(sc, Bt8370_TCR0, sc->config.format>>1);

  /* 071:TCR1 -- Transmitter Configuration */
  if (FORMAT_T1SF)
    write_framer(sc, Bt8370_TCR1, 0x43); /* tabort, AMI PDV enforced */
  else
    write_framer(sc, Bt8370_TCR1, 0x41); /* tabort, B8ZS or HDB3 */

  /* 072:TFRM -- Transmit Frame format       MYEL YEL MF FE CRC FBIT */
  if      (sc->config.format == CFG_FORMAT_T1ESF)
    write_framer(sc, Bt8370_TFRM, 0x0B); /*  -   YEL MF -  CRC FBIT */
  else if (sc->config.format == CFG_FORMAT_T1SF)
    write_framer(sc, Bt8370_TFRM, 0x19); /*  -   YEL MF -   -  FBIT */
  else if (sc->config.format == CFG_FORMAT_E1FAS)
    write_framer(sc, Bt8370_TFRM, 0x11); /*  -   YEL -  -   -  FBIT */
  else if (sc->config.format == CFG_FORMAT_E1FASCRC)
    write_framer(sc, Bt8370_TFRM, 0x1F); /*  -   YEL MF FE CRC FBIT */
  else if (sc->config.format == CFG_FORMAT_E1FASCAS)
    write_framer(sc, Bt8370_TFRM, 0x31); /* MYEL YEL -  -   -  FBIT */
  else if (sc->config.format == CFG_FORMAT_E1FASCRCCAS)
    write_framer(sc, Bt8370_TFRM, 0x3F); /* MYEL YEL MF FE CRC FBIT */
  else if (sc->config.format == CFG_FORMAT_E1NONE)
    write_framer(sc, Bt8370_TFRM, 0x00); /* NO FRAMING BITS AT ALL! */

  /* 073:TERROR -- Transmit Error Insert */
  write_framer(sc, Bt8370_TERROR, 0x00); /* no errors, please! */

  /* 074:TMAN -- Transmit Manual Sa-byte/FEBE configuration */
  write_framer(sc, Bt8370_TMAN, 0x00); /* none */

  /* 075:TALM -- Transmit Alarm Signal Configuration */
  if (FORMAT_E1ANY)
    write_framer(sc, Bt8370_TALM, 0x38); /* auto_myel auto_yel auto_ais */
  else if (FORMAT_T1ANY)
    write_framer(sc, Bt8370_TALM, 0x18); /* auto_yel auto_ais */

  /* 076:TPATT -- Transmit Test Pattern Configuration */
  write_framer(sc, Bt8370_TPATT, 0x00); /* disabled */

  /* 077:TLB -- Transmit Inband Loopback Code Configuration */
  write_framer(sc, Bt8370_TLB, 0x00); /* disabled */

  /* 090:CLAD_CR -- Clack Rate Adapter Configuration */
  if (FORMAT_T1ANY)
    write_framer(sc, Bt8370_CLAD_CR, 0x06); /* loop filter gain 1/2^6 */
  else
    write_framer(sc, Bt8370_CLAD_CR, 0x08); /* loop filter gain 1/2^8 */

  /* 091:CSEL -- CLAD frequency Select */
  if (FORMAT_T1ANY)
    write_framer(sc, Bt8370_CSEL, 0x55); /* 1544 kHz */
  else
    write_framer(sc, Bt8370_CSEL, 0x11); /* 2048 kHz */

  /* 092:CPHASE -- CLAD Phase detector */
  if (FORMAT_T1ANY)
    write_framer(sc, Bt8370_CPHASE, 0x22); /* phase compare @  386 kHz */
  else
    write_framer(sc, Bt8370_CPHASE, 0x00); /* phase compare @ 2048 kHz */

  if (FORMAT_T1ESF) /* BOP & PRM are enabled in T1ESF mode only. */
    {
    /* 0A0:BOP -- Bit Oriented Protocol messages */
    write_framer(sc, Bt8370_BOP, RBOP_25 | TBOP_OFF);
    /* 0A4:DL1_TS -- Data Link 1 Time Slot Enable */
    write_framer(sc, Bt8370_DL1_TS, 0x40); /* FDL bits in odd frames */
    /* 0A6:DL1_CTL -- Data Link 1 Control */
    write_framer(sc, Bt8370_DL1_CTL, 0x03); /* FCS mode, TX on, RX on */
    /* 0A7:RDL1_FFC -- Rx Data Link 1 Fifo Fill Control */
    write_framer(sc, Bt8370_RDL1_FFC, 0x30); /* assert "near full" at 48 */
    /* 0AA:PRM -- Performance Report Messages */
    write_framer(sc, Bt8370_PRM, 0x80);
    }

  /* 0D0:SBI_CR -- System Bus Interface Configuration Register */
  if (FORMAT_T1ANY)
    write_framer(sc, Bt8370_SBI_CR, 0x47); /* 1.544 with 24 TS +Fbits */
  else
    write_framer(sc, Bt8370_SBI_CR, 0x46); /* 2.048 with 32 TS */

  /* 0D1:RSB_CR -- Receive System Bus Configuration Register */
  /* Change RINDO & RFSYNC on falling edge of RSBCLKI. */
  write_framer(sc, Bt8370_RSB_CR, 0x70);

  /* 0D2,0D3:RSYNC_{TS,BIT} -- Receive frame Sync offset */
  write_framer(sc, Bt8370_RSYNC_BIT, 0x00);
  write_framer(sc, Bt8370_RSYNC_TS,  0x00);

  /* 0D4:TSB_CR -- Transmit System Bus Configuration Register */
  /* Change TINDO & TFSYNC on falling edge of TSBCLKI. */
  write_framer(sc, Bt8370_TSB_CR, 0x30);

  /* 0D5,0D6:TSYNC_{TS,BIT} -- Transmit frame Sync offset */
  write_framer(sc, Bt8370_TSYNC_BIT, 0x00);
  write_framer(sc, Bt8370_TSYNC_TS,  0x00);

  /* 0D7:RSIG_CR -- Receive SIGnalling Configuratin Register */
  write_framer(sc, Bt8370_RSIG_CR, 0x00);

  /* Assign and configure 64Kb TIME SLOTS. */
  /* TS24..TS1 must be assigned for T1, TS31..TS0 for E1. */
  /* Timeslots with no user data have RINDO and TINDO off. */
  for (i=0; i<32; i++)
    {
    /* 0E0-0FF:SBCn -- System Bus Per-Channel Control */
    if      (FORMAT_T1ANY && (i==0 || i>24))
      write_framer(sc, Bt8370_SBCn +i, 0x00); /* not assigned in T1 mode */
    else if (FORMAT_E1ANY && (i==0)  && !FORMAT_E1NONE)
      write_framer(sc, Bt8370_SBCn +i, 0x01); /* assigned, TS0  o/h bits */
    else if (FORMAT_E1CAS && (i==16) && !FORMAT_E1NONE)
      write_framer(sc, Bt8370_SBCn +i, 0x01); /* assigned, TS16 o/h bits */
    else if ((sc->config.time_slots & (1<<i)) != 0)
      write_framer(sc, Bt8370_SBCn +i, 0x0D); /* assigned, RINDO, TINDO */
    else
      write_framer(sc, Bt8370_SBCn +i, 0x01); /* assigned, idle */

    /* 100-11F:TPCn -- Transmit Per-Channel Control */
    if      (FORMAT_E1CAS && (i==0))
      write_framer(sc, Bt8370_TPCn +i, 0x30); /* tidle, sig=0000 (MAS) */
    else if (FORMAT_E1CAS && (i==16))
      write_framer(sc, Bt8370_TPCn +i, 0x3B); /* tidle, sig=1011 (XYXX) */
    else if ((sc->config.time_slots & (1<<i)) == 0)
      write_framer(sc, Bt8370_TPCn +i, 0x20); /* tidle: use TSLIP_LOn */
    else
      write_framer(sc, Bt8370_TPCn +i, 0x00); /* nothing special */

    /* 140-15F:TSLIP_LOn -- Transmit PCM Slip Buffer */
    write_framer(sc, Bt8370_TSLIP_LOn +i, 0x7F); /* idle chan data */
    /* 180-19F:RPCn -- Receive Per-Channel Control */
    write_framer(sc, Bt8370_RPCn +i, 0x00);   /* nothing special */
    }

  /* Enable transmitter output drivers. */
  set_mii16_bits(sc, MII16_T1_XOE);
  }

static void
t1_ident(softc_t *sc)
  {
  printf(", Bt837%x rev %x",
   read_framer(sc, Bt8370_DID)>>4,
   read_framer(sc, Bt8370_DID)&0x0F);
  }

/* Called once a second; must not sleep. */
static int
t1_watchdog(softc_t *sc)
  {
  u_int16_t LCV = 0, FERR = 0, CRC = 0, FEBE = 0;
  u_int8_t alm1, alm3, loop, isr0;
  int link_status = STATUS_UP;
  int i;

  /* Read the alarm registers */
  alm1 = read_framer(sc, Bt8370_ALM1);
  alm3 = read_framer(sc, Bt8370_ALM3);
  loop = read_framer(sc, Bt8370_LOOP);
  isr0 = read_framer(sc, Bt8370_ISR0);

  /* Always ignore the SIGFRZ alarm bit, */
  alm1 &= ~ALM1_SIGFRZ;
  if (FORMAT_T1ANY)  /* ignore RYEL in T1 modes */
    alm1 &= ~ALM1_RYEL;
  else if (FORMAT_E1NONE) /* ignore all alarms except LOS */
    alm1 &= ALM1_RLOS;

  /* Software is alive. */
  led_inv(sc, MII16_T1_LED_GRN);

  /* Receiving Alarm Indication Signal (AIS). */
  if ((alm1 & ALM1_RAIS)!=0) /* receiving ais */
    led_on(sc, MII16_T1_LED_BLU);
  else if ((alm1 & ALM1_RLOS)!=0) /* sending ais */
    led_inv(sc, MII16_T1_LED_BLU);
  else
    led_off(sc, MII16_T1_LED_BLU);

  /* Receiving Remote Alarm Indication (RAI). */
  if ((alm1 & (ALM1_RMYEL | ALM1_RYEL))!=0) /* receiving rai */
    led_on(sc, MII16_T1_LED_YEL);
  else if ((alm1 & ALM1_RLOF)!=0) /* sending rai */
    led_inv(sc, MII16_T1_LED_YEL);
  else
    led_off(sc, MII16_T1_LED_YEL);

  /* If any alarm bits are set then the link is 'down'. */
  /* The bad bits are: rmyel ryel rais ralos rlos rlof. */
  /* Some alarm bits have been masked by this point. */
  if (alm1 != 0) link_status = STATUS_DOWN;

  /* Declare local Red Alarm if the link is down. */
  if (link_status == STATUS_DOWN)
    led_on(sc, MII16_T1_LED_RED);
  else if (sc->loop_timer != 0) /* loopback is active */
    led_inv(sc, MII16_T1_LED_RED);
  else
    led_off(sc, MII16_T1_LED_RED);

  /* Print latched error bits if they changed. */
  if ((DRIVER_DEBUG) && (alm1 != sc->last_alm1))
    {
    char *on = "ON ", *off = "OFF";
    printf("%s: RLOF=%s RLOS=%s RALOS=%s RAIS=%s RYEL=%s RMYEL=%s\n",
     NAME_UNIT,
     (alm1 & ALM1_RLOF)  ? on : off,
     (alm1 & ALM1_RLOS)  ? on : off,
     (alm1 & ALM1_RALOS) ? on : off,
     (alm1 & ALM1_RAIS)  ? on : off,
     (alm1 & ALM1_RYEL)  ? on : off,
     (alm1 & ALM1_RMYEL) ? on : off);
    }

  /* Check and print error counters if non-zero. */
  LCV = read_framer(sc, Bt8370_LCV_LO)  +
        (read_framer(sc, Bt8370_LCV_HI)<<8);
  if (!FORMAT_E1NONE)
    FERR = read_framer(sc, Bt8370_FERR_LO) +
          (read_framer(sc, Bt8370_FERR_HI)<<8);
  if (FORMAT_E1CRC || FORMAT_T1ESF)
    CRC  = read_framer(sc, Bt8370_CRC_LO)  +
          (read_framer(sc, Bt8370_CRC_HI)<<8);
  if (FORMAT_E1CRC)
    FEBE = read_framer(sc, Bt8370_FEBE_LO) +
          (read_framer(sc, Bt8370_FEBE_HI)<<8);
  /* Only LCV is valid if Out-Of-Frame */
  if (FORMAT_E1NONE) FERR = CRC = FEBE = 0;
  if ((DRIVER_DEBUG) && (LCV || FERR || CRC || FEBE))
    printf("%s: LCV=%u FERR=%u CRC=%u FEBE=%u\n",
     NAME_UNIT, LCV,   FERR,   CRC,   FEBE);

  /* Driver keeps crude link-level error counters (SNMP is better). */
  sc->status.cntrs.lcv_errs  += LCV;
  sc->status.cntrs.frm_errs  += FERR;
  sc->status.cntrs.crc_errs  += CRC;
  sc->status.cntrs.febe_errs += FEBE;

  /* Check for BOP messages in the ESF Facility Data Link. */
  if ((FORMAT_T1ESF) && (read_framer(sc, Bt8370_ISR1) & 0x80))
    {
    u_int8_t bop_code = read_framer(sc, Bt8370_RBOP) & 0x3F;

    switch (bop_code)
      {
      case T1BOP_OOF:
        {
        if ((DRIVER_DEBUG) && ((sc->last_alm1 & ALM1_RMYEL)==0))
          printf("%s: Receiving a 'yellow alarm' BOP msg\n", NAME_UNIT);
        break;
        }
      case T1BOP_LINE_UP:
        {
        if (DRIVER_DEBUG)
          printf("%s: Received a 'line loopback activate' BOP msg\n", NAME_UNIT);
        write_framer(sc, Bt8370_LOOP, LOOP_LINE);
        sc->loop_timer = 305;
        break;
        }
      case T1BOP_LINE_DOWN:
        {
        if (DRIVER_DEBUG)
          printf("%s: Received a 'line loopback deactivate' BOP msg\n", NAME_UNIT);
        write_framer(sc, Bt8370_LOOP,
         read_framer(sc, Bt8370_LOOP) & ~LOOP_LINE);
        sc->loop_timer = 0;
        break;
        }
      case T1BOP_PAY_UP:
        {
        if (DRIVER_DEBUG)
          printf("%s: Received a 'payload loopback activate' BOP msg\n", NAME_UNIT);
        write_framer(sc, Bt8370_LOOP, LOOP_PAYLOAD);
        sc->loop_timer = 305;
        break;
        }
      case T1BOP_PAY_DOWN:
        {
        if (DRIVER_DEBUG)
          printf("%s: Received a 'payload loopback deactivate' BOP msg\n", NAME_UNIT);
        write_framer(sc, Bt8370_LOOP,
         read_framer(sc, Bt8370_LOOP) & ~LOOP_PAYLOAD);
        sc->loop_timer = 0;
        break;
        }
      default:
        {
        if (DRIVER_DEBUG)
          printf("%s: Received a type 0x%02X BOP msg\n", NAME_UNIT, bop_code);
        break;
        }
      }
    }

  /* Check for HDLC pkts in the ESF Facility Data Link. */
  if ((FORMAT_T1ESF) && (read_framer(sc, Bt8370_ISR2) & 0x70))
    {
    /* while (not fifo-empty && not start-of-msg) flush fifo */
    while ((read_framer(sc, Bt8370_RDL1_STAT) & 0x0C) == 0)
      read_framer(sc, Bt8370_RDL1);
    /* If (not fifo-empty), then begin processing fifo contents. */
    if ((read_framer(sc, Bt8370_RDL1_STAT) & 0x0C) == 0x08)
      {
      u_int8_t msg[64];
      u_int8_t stat = read_framer(sc, Bt8370_RDL1);
      sc->status.cntrs.fdl_pkts++;
      for (i=0; i<(stat & 0x3F); i++)
        msg[i] = read_framer(sc, Bt8370_RDL1);
      /* Is this FDL message a T1.403 performance report? */
      if (((stat & 0x3F)==11) &&
          ((msg[0]==0x38) || (msg[0]==0x3A)) &&
           (msg[1]==1)   &&  (msg[2]==3))
        /* Copy 4 PRs from FDL pkt to SNMP struct. */
        memcpy(sc->status.snmp.t1.prm, msg+3, 8);
      }
    }

  /* Check for inband loop up/down commands. */
  if (FORMAT_T1ANY)
    {
    u_int8_t isr6   = read_framer(sc, Bt8370_ISR6);
    u_int8_t alarm2 = read_framer(sc, Bt8370_ALM2);
    u_int8_t tlb    = read_framer(sc, Bt8370_TLB);

    /* Inband Code == Loop Up && On Transition && Inband Tx Inactive */
    if ((isr6 & 0x40) && (alarm2 & 0x40) && ((tlb & 1)==0))
      { /* CSU loop up is 10000 10000 ... */
      if (DRIVER_DEBUG)
        printf("%s: Received a 'CSU Loop Up' inband msg\n", NAME_UNIT);
      write_framer(sc, Bt8370_LOOP, LOOP_LINE); /* Loop up */
      sc->loop_timer = 305;
      }
    /* Inband Code == Loop Down && On Transition && Inband Tx Inactive */
    if ((isr6 & 0x80) && (alarm2 & 0x80) && ((tlb & 1)==0))
      { /* CSU loop down is 100 100 100 ... */
      if (DRIVER_DEBUG)
        printf("%s: Received a 'CSU Loop Down' inband msg\n", NAME_UNIT);
      write_framer(sc, Bt8370_LOOP,
       read_framer(sc, Bt8370_LOOP) & ~LOOP_LINE); /* loop down */
      sc->loop_timer = 0;
      }
    }

  /* Manually send Yellow Alarm BOP msgs. */
  if (FORMAT_T1ESF)
    {
    u_int8_t isr7 = read_framer(sc, Bt8370_ISR7);

    if ((isr7 & 0x02) && (alm1 & 0x02)) /* RLOF on-transition */
      { /* Start sending continuous Yellow Alarm BOP messages. */
      write_framer(sc, Bt8370_BOP,  RBOP_25 | TBOP_CONT);
      write_framer(sc, Bt8370_TBOP, 0x00); /* send BOP; order matters */
      }
    else if ((isr7 & 0x02) && ((alm1 & 0x02)==0)) /* RLOF off-transition */
      { /* Stop sending continuous Yellow Alarm BOP messages. */
      write_framer(sc, Bt8370_BOP,  RBOP_25 | TBOP_OFF);
      }
    }

  /* Time out loopback requests. */
  if (sc->loop_timer != 0)
    if (--sc->loop_timer == 0)
      if (loop != 0)
        {
        if (DRIVER_DEBUG)
          printf("%s: Timeout: Loop Down after 300 seconds\n", NAME_UNIT);
        write_framer(sc, Bt8370_LOOP, loop & ~(LOOP_PAYLOAD | LOOP_LINE));
        }

  /* RX Test Pattern status */
  if ((DRIVER_DEBUG) && (isr0 & 0x10))
    printf("%s: RX Test Pattern Sync\n", NAME_UNIT);

  /* SNMP Error Counters */
  sc->status.snmp.t1.lcv  = LCV;
  sc->status.snmp.t1.fe   = FERR;
  sc->status.snmp.t1.crc  = CRC;
  sc->status.snmp.t1.febe = FEBE;

  /* SNMP Line Status */
  sc->status.snmp.t1.line = 0;
  if  (alm1 & ALM1_RMYEL)  sc->status.snmp.t1.line |= TLINE_RX_RAI;
  if  (alm1 & ALM1_RYEL)   sc->status.snmp.t1.line |= TLINE_RX_RAI;
  if  (alm1 & ALM1_RLOF)   sc->status.snmp.t1.line |= TLINE_TX_RAI;
  if  (alm1 & ALM1_RAIS)   sc->status.snmp.t1.line |= TLINE_RX_AIS;
  if  (alm1 & ALM1_RLOS)   sc->status.snmp.t1.line |= TLINE_TX_AIS;
  if  (alm1 & ALM1_RLOF)   sc->status.snmp.t1.line |= TLINE_LOF;
  if  (alm1 & ALM1_RLOS)   sc->status.snmp.t1.line |= TLINE_LOS;
  if  (alm3 & ALM3_RMAIS)  sc->status.snmp.t1.line |= T1LINE_RX_TS16_AIS;
  if  (alm3 & ALM3_SRED)   sc->status.snmp.t1.line |= T1LINE_TX_TS16_LOMF;
  if  (alm3 & ALM3_SEF)    sc->status.snmp.t1.line |= T1LINE_SEF;
  if  (isr0 & 0x10)        sc->status.snmp.t1.line |= T1LINE_RX_TEST;
  if ((alm1 & ALM1_RMYEL) && (FORMAT_E1CAS))
                           sc->status.snmp.t1.line |= T1LINE_RX_TS16_LOMF;

  /* SNMP Loopback Status */
  sc->status.snmp.t1.loop &= ~(TLOOP_FAR_LINE | TLOOP_FAR_PAYLOAD);
  if (sc->config.loop_back == CFG_LOOP_TULIP)
                           sc->status.snmp.t1.loop |= TLOOP_NEAR_OTHER;
  if (loop & LOOP_PAYLOAD) sc->status.snmp.t1.loop |= TLOOP_NEAR_PAYLOAD;
  if (loop & LOOP_LINE)    sc->status.snmp.t1.loop |= TLOOP_NEAR_LINE;
  if (loop & LOOP_ANALOG)  sc->status.snmp.t1.loop |= TLOOP_NEAR_OTHER;
  if (loop & LOOP_FRAMER)  sc->status.snmp.t1.loop |= TLOOP_NEAR_INWARD;

  /* Remember this state until next time. */
  sc->last_alm1 = alm1;

  /* If an INWARD loopback is in effect, link status is UP */
  if (sc->config.loop_back != CFG_LOOP_NONE) /* XXX INWARD ONLY */
    link_status = STATUS_UP;

  return link_status;
  }

/* IOCTL SYSCALL: can sleep. */
static void
t1_send_bop(softc_t *sc, int bop_code)
  {
  u_int8_t bop;
  int i;

  /* The BOP transmitter could be sending a continuous */
  /*  BOP msg when told to send this BOP_25 message. */
  /* So save and restore the state of the BOP machine. */
  bop = read_framer(sc, Bt8370_BOP);
  write_framer(sc, Bt8370_BOP, RBOP_OFF | TBOP_OFF);
  for (i=0; i<40; i++) /* max delay 400 ms. */
    if (read_framer(sc, Bt8370_BOP_STAT) & 0x80) SLEEP(10000);
  /* send 25 repetitions of bop_code */
  write_framer(sc, Bt8370_BOP, RBOP_OFF | TBOP_25);
  write_framer(sc, Bt8370_TBOP, bop_code); /* order matters */
  /* wait for tx to stop */
  for (i=0; i<40; i++) /* max delay 400 ms. */
    if (read_framer(sc, Bt8370_BOP_STAT) & 0x80) SLEEP(10000);
  /* Restore previous state of the BOP machine. */
  write_framer(sc, Bt8370_BOP, bop);
  }

/* IOCTL SYSCALL: can sleep. */
static int
t1_ioctl(softc_t *sc, struct ioctl *ioctl)
  {
  int error = 0;

  switch (ioctl->cmd)
    {
    case IOCTL_SNMP_SEND:  /* set opstatus? */
      {
      switch (ioctl->data)
        {
        case TSEND_NORMAL:
          {
          write_framer(sc, Bt8370_TPATT, 0x00); /* tx pattern generator off */
          write_framer(sc, Bt8370_RPATT, 0x00); /* rx pattern detector off */
          write_framer(sc, Bt8370_TLB,   0x00); /* tx inband generator off */
          break;
	  }
        case TSEND_LINE:
          {
          if (FORMAT_T1ESF)
            t1_send_bop(sc, T1BOP_LINE_UP);
          else if (FORMAT_T1SF)
            {
            write_framer(sc, Bt8370_LBP, 0x08); /* 10000 10000 ... */
            write_framer(sc, Bt8370_TLB, 0x05); /* 5 bits, framed, start */
	    }
          sc->status.snmp.t1.loop |= TLOOP_FAR_LINE;
          break;
	  }
        case TSEND_PAYLOAD:
          {
          t1_send_bop(sc, T1BOP_PAY_UP);
          sc->status.snmp.t1.loop |= TLOOP_FAR_PAYLOAD;
          break;
	  }
        case TSEND_RESET:
          {
          if (sc->status.snmp.t1.loop == TLOOP_FAR_LINE)
            {
            if (FORMAT_T1ESF)
              t1_send_bop(sc, T1BOP_LINE_DOWN);
            else if (FORMAT_T1SF)
              {
              write_framer(sc, Bt8370_LBP, 0x24); /* 100100 100100 ... */
              write_framer(sc, Bt8370_TLB, 0x09); /* 6 bits, framed, start */
	      }
            sc->status.snmp.t1.loop &= ~TLOOP_FAR_LINE;
	    }
          if (sc->status.snmp.t1.loop == TLOOP_FAR_PAYLOAD)
            {
            t1_send_bop(sc, T1BOP_PAY_DOWN);
            sc->status.snmp.t1.loop &= ~TLOOP_FAR_PAYLOAD;
	    }
          break;
	  }
        case TSEND_QRS:
          {
          write_framer(sc, Bt8370_TPATT, 0x1E); /* framed QRSS */
          break;
	  }
        default:
          {
          error = EINVAL;
          break;
	  }
	}
      break;
      }
    case IOCTL_SNMP_LOOP:  /* set opstatus = test? */
      {
      u_int8_t new_loop = 0;

      if (ioctl->data == CFG_LOOP_NONE)
        new_loop = 0;
      else if (ioctl->data == CFG_LOOP_PAYLOAD)
        new_loop = LOOP_PAYLOAD;
      else if (ioctl->data == CFG_LOOP_LINE)
        new_loop = LOOP_LINE;
      else if (ioctl->data == CFG_LOOP_OTHER)
        new_loop = LOOP_ANALOG;
      else if (ioctl->data == CFG_LOOP_INWARD)
        new_loop = LOOP_FRAMER;
      else if (ioctl->data == CFG_LOOP_DUAL)
        new_loop = LOOP_DUAL;
      else
        error = EINVAL;
      if (error == 0)
        {
        write_framer(sc, Bt8370_LOOP, new_loop);
        sc->config.loop_back = ioctl->data;
	}
      break;
      }
    default:
      error = EINVAL;
      break;
    }

  return error;
  }

static
struct card hssi_card =
  {
  .config   = hssi_config,
  .ident    = hssi_ident,
  .watchdog = hssi_watchdog,
  .ioctl    = hssi_ioctl,
  };

static
struct card t3_card =
  {
  .config   = t3_config,
  .ident    = t3_ident,
  .watchdog = t3_watchdog,
  .ioctl    = t3_ioctl,
  };

static
struct card ssi_card =
  {
  .config   = ssi_config,
  .ident    = ssi_ident,
  .watchdog = ssi_watchdog,
  .ioctl    = ssi_ioctl,
  };

static
struct card t1_card =
  {
  .config   = t1_config,
  .ident    = t1_ident,
  .watchdog = t1_watchdog,
  .ioctl    = t1_ioctl,
  };

/* RAWIP is raw IP packets (v4 or v6) in HDLC frames with NO HEADERS. */
/* No HDLC Address/Control fields!  No line control protocol at all!  */
/* This code is BSD/ifnet-specific; Linux and Netgraph also do RAWIP. */

#if IFNET

# if ((defined(__FreeBSD__) && (__FreeBSD_version < 500000)) ||\
        defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__))
static void
netisr_dispatch(int isr, struct mbuf *mbuf)
  {
  struct ifqueue *intrq = NULL;
  int qfull = 0;

#if INET
  if (isr == NETISR_IP)   intrq = &ipintrq;
#endif
#if INET6
  if (isr == NETISR_IPV6) intrq = &ip6intrq;
#endif

  if ((intrq != NULL) && ((qfull = IF_QFULL(intrq)) == 0))
    {
    /* rxintr_cleanup() ENQUEUES in a hard interrupt. */
    /* networking code DEQUEUES in a soft interrupt. */
    /* Some BSD QUEUE routines are not interrupt-safe. */
    DISABLE_INTR; /* noop in FreeBSD */
    IF_ENQUEUE(intrq, mbuf);
    ENABLE_INTR;
    schednetisr(isr); /* schedule a soft interrupt */
    }
  else
    {
    m_freem(mbuf);
    if ((intrq != NULL) && (qfull != 0))
      IF_DROP(intrq);
    }
  }
# endif /* ((__FreeBSD__ && (__FreeBSD_version < 500000)) || */
           /* __NetBSD__ || __OpenBSD__ || __bsdi__) */

/* rxintr_cleanup calls this to give a newly arrived pkt to higher levels. */
static void
lmc_raw_input(struct ifnet *ifp, struct mbuf *mbuf)
  {
  softc_t *sc = IFP2SC(ifp);

# if INET
  if (mbuf->m_data[0]>>4 == 4)
    netisr_dispatch(NETISR_IP,   mbuf);
  else
# endif
# if INET6
  if (mbuf->m_data[0]>>4 == 6)
    netisr_dispatch(NETISR_IPV6, mbuf);
  else
# endif
    {
    m_freem(mbuf);
    sc->status.cntrs.idiscards++;
    if (DRIVER_DEBUG)
      printf("%s: lmc_raw_input: rx pkt discarded: not IPv4 or IPv6\n",
	NAME_UNIT);
    }
  }

#endif /* IFNET */

/* There are TWO VERSIONS of interrupt/DMA code: Linux & BSD.
 * Handling Linux and the BSDs with CPP directives would
 *  make the code unreadable, so there are two versions.
 * Conceptually, the two versions do the same thing and
 *  core_interrupt() doesn't know they are different.
 *
 * We are "standing on the head of a pin" in these routines.
 * Tulip CSRs can be accessed, but nothing else is interrupt-safe!
 * Do NOT access: MII, GPIO, SROM, BIOSROM, XILINX, SYNTH, or DAC.
 */

#if BSD /* BSD version of interrupt/DMA code */

/* Singly-linked tail-queues hold mbufs with active DMA.
 * For RX, single mbuf clusters; for TX, mbuf chains are queued.
 * NB: mbufs are linked through their m_nextpkt field.
 * Callers must hold sc->bottom_lock; not otherwise locked.
 */

/* Put an mbuf (chain) on the tail of the descriptor ring queue. */
static void  /* BSD version */
mbuf_enqueue(struct desc_ring *ring, struct mbuf *m)
  {
  m->m_nextpkt = NULL;
  if (ring->tail == NULL)
    ring->head = m;
  else
    ring->tail->m_nextpkt = m;
  ring->tail = m;
  }

/* Get an mbuf (chain) from the head of the descriptor ring queue. */
static struct mbuf*  /* BSD version */
mbuf_dequeue(struct desc_ring *ring)
  {
  struct mbuf *m = ring->head;
  if (m != NULL)
    if ((ring->head = m->m_nextpkt) == NULL)
      ring->tail = NULL;
  return m;
  }

# ifdef __FreeBSD__
static void /* *** FreeBSD ONLY *** Callout from bus_dmamap_load() */
fbsd_dmamap_load(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
  {
  struct desc_ring *ring = arg;
  ring->nsegs = error ? 0 : nsegs;
  ring->segs[0] = segs[0];
  ring->segs[1] = segs[1];
  }
# endif

/* Initialize a DMA descriptor ring. */
static int  /* BSD version */
create_ring(softc_t *sc, struct desc_ring *ring, int num_descs)
  {
  struct dma_desc *descs;
  int size_descs = sizeof(struct dma_desc)*num_descs;
  int i, error = 0;

  /* The DMA descriptor array must not cross a page boundary. */
  if (size_descs > PAGE_SIZE)
    {
    printf("%s: DMA descriptor array > PAGE_SIZE (%d)\n", NAME_UNIT, 
     (u_int)PAGE_SIZE);
    return EINVAL;
    }

#ifdef __FreeBSD__

  /* Create a DMA tag for descriptors and buffers. */
  if ((error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
   BUS_SPACE_MAXADDR, NULL, NULL, PAGE_SIZE, 2, PAGE_SIZE, BUS_DMA_ALLOCNOW,
# if (__FreeBSD_version >= 502000)
   NULL, NULL,
# endif
   &ring->tag)))
    {
    printf("%s: bus_dma_tag_create() failed: error %d\n", NAME_UNIT, error);
    return error;
    }

  /* Allocate wired physical memory for DMA descriptor array */
  /*  and map physical address to kernel virtual address. */
  if ((error = bus_dmamem_alloc(ring->tag, (void**)&ring->first,
   BUS_DMA_NOWAIT | BUS_DMA_COHERENT | BUS_DMA_ZERO, &ring->map)))
    {
    printf("%s: bus_dmamem_alloc() failed; error %d\n", NAME_UNIT, error);
    return error;
    }
  descs = ring->first;

  /* Map kernel virtual address to PCI address for DMA descriptor array. */
  if ((error = bus_dmamap_load(ring->tag, ring->map, descs, size_descs,
   fbsd_dmamap_load, ring, 0)))
    {
    printf("%s: bus_dmamap_load() failed; error %d\n", NAME_UNIT, error);
    return error;
    }
  ring->dma_addr = ring->segs[0].ds_addr;

  /* Allocate dmamaps for each DMA descriptor. */
  for (i=0; i<num_descs; i++)
    if ((error = bus_dmamap_create(ring->tag, 0, &descs[i].map)))
      {
      printf("%s: bus_dmamap_create() failed; error %d\n", NAME_UNIT, error);
      return error;
      }

#elif (defined(__NetBSD__) || defined(__OpenBSD__))

  /* Use the DMA tag passed to attach() for descriptors and buffers. */
  ring->tag = sc->pa_dmat;

  /* Allocate wired physical memory for DMA descriptor array. */
  if ((error = bus_dmamem_alloc(ring->tag, size_descs, PAGE_SIZE, 0,
   ring->segs, 1, &ring->nsegs, BUS_DMA_NOWAIT)))
    {
    printf("%s: bus_dmamem_alloc() failed; error %d\n", NAME_UNIT, error);
    return error;
    }

  /* Map physical address to kernel virtual address. */
  if ((error = bus_dmamem_map(ring->tag, ring->segs, ring->nsegs,
   size_descs, (caddr_t *)&ring->first, BUS_DMA_NOWAIT | BUS_DMA_COHERENT)))
    {
    printf("%s: bus_dmamem_map() failed; error %d\n", NAME_UNIT, error);
    return error;
    }
  descs = ring->first; /* suppress compiler warning about aliasing */
  memset(descs, 0, size_descs);

  /* Allocate dmamap for PCI access to DMA descriptor array. */
  if ((error = bus_dmamap_create(ring->tag, size_descs, 1,
   size_descs, 0, BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &ring->map)))
    {
    printf("%s: bus_dmamap_create() failed; error %d\n", NAME_UNIT, error);
    return error;
    }

  /* Map kernel virtual address to PCI address for DMA descriptor array. */
  if ((error = bus_dmamap_load(ring->tag, ring->map, descs, size_descs,
   0, BUS_DMA_NOWAIT)))
    {
    printf("%s: bus_dmamap_load() failed; error %d\n", NAME_UNIT, error);
    return error;
    }
  ring->dma_addr = ring->map->dm_segs[0].ds_addr;

  /* Allocate dmamaps for each DMA descriptor. */
  for (i=0; i<num_descs; i++)
    if ((error = bus_dmamap_create(ring->tag, MAX_DESC_LEN, 2,
     MAX_CHUNK_LEN, 0, BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &descs[i].map)))
      {
      printf("%s: bus_dmamap_create() failed; error %d\n", NAME_UNIT, error);
      return error;
      }

#elif defined(__bsdi__)

  /* Allocate wired physical memory for DMA descriptor array. */
  if ((ring->first = malloc(size_descs, M_DEVBUF, M_NOWAIT)) == NULL)
    {
    printf("%s: malloc() failed for DMA descriptor array\n", NAME_UNIT);
    return ENOMEM;
    }
  descs = ring->first;
  memset(descs, 0, size_descs);

  /* Map kernel virtual address to PCI address for DMA descriptor array. */
  ring->dma_addr = vtophys(descs); /* Relax! BSD/OS only. */

#endif

  ring->read  = descs;
  ring->write = descs;
  ring->first = descs;
  ring->last  = descs + num_descs -1;
  ring->last->control = TLP_DCTL_END_RING;
  ring->num_descs = num_descs;
  ring->size_descs = size_descs;
  ring->head = NULL;
  ring->tail = NULL;

  return 0;
  }

/* Destroy a DMA descriptor ring */
static void  /* BSD version */
destroy_ring(softc_t *sc, struct desc_ring *ring)
  {
  struct dma_desc *desc;
  struct mbuf *m;

  /* Free queued mbufs. */
  while ((m = mbuf_dequeue(ring)) != NULL)
    m_freem(m);

  /* TX may have one pkt that is not on any queue. */
  if (sc->tx_mbuf != NULL)
    {
    m_freem(sc->tx_mbuf);
    sc->tx_mbuf = NULL;
    }

  /* Unmap active DMA descriptors. */
  while (ring->read != ring->write)
    {
    bus_dmamap_unload(ring->tag, ring->read->map);
    if (ring->read++ == ring->last) ring->read = ring->first;
    }

#ifdef __FreeBSD__

  /* Free the dmamaps of all DMA descriptors. */
  for (desc=ring->first; desc!=ring->last+1; desc++)
    if (desc->map != NULL)
      bus_dmamap_destroy(ring->tag, desc->map);

  /* Unmap PCI address for DMA descriptor array. */
  if (ring->dma_addr != 0)
    bus_dmamap_unload(ring->tag, ring->map);
  /* Free kernel memory for DMA descriptor array. */
  if (ring->first != NULL)
    bus_dmamem_free(ring->tag, ring->first, ring->map);
  /* Free the DMA tag created for this ring. */
  if (ring->tag != NULL)
    bus_dma_tag_destroy(ring->tag);

#elif (defined(__NetBSD__) || defined(__OpenBSD__))

  /* Free the dmamaps of all DMA descriptors. */
  for (desc=ring->first; desc!=ring->last+1; desc++)
    if (desc->map != NULL)
      bus_dmamap_destroy(ring->tag, desc->map);

  /* Unmap PCI address for DMA descriptor array. */
  if (ring->dma_addr != 0)
    bus_dmamap_unload(ring->tag, ring->map);
  /* Free dmamap for DMA descriptor array. */
  if (ring->map != NULL)
    bus_dmamap_destroy(ring->tag, ring->map);
  /* Unmap kernel address for DMA descriptor array. */
  if (ring->first != NULL)
    bus_dmamem_unmap(ring->tag, (caddr_t)ring->first, ring->size_descs);
  /* Free kernel memory for DMA descriptor array. */
  if (ring->segs[0].ds_addr != 0)
    bus_dmamem_free(ring->tag, ring->segs, ring->nsegs);

#elif defined(__bsdi__)

  /* Free kernel memory for DMA descriptor array. */
  if (ring->first != NULL)
    free(ring->first, M_DEVBUF);

#endif
  }

/* Clean up after a packet has been received. */
static int  /* BSD version */
rxintr_cleanup(softc_t *sc)
  {
  struct desc_ring *ring = &sc->rxring;
  struct dma_desc *first_desc, *last_desc;
  struct mbuf *first_mbuf=NULL, *last_mbuf=NULL;
  struct mbuf *new_mbuf;
  int pkt_len, desc_len;

#if (defined(__FreeBSD__) && defined(DEVICE_POLLING))
  /* Input packet flow control (livelock prevention): */
  /* Give pkts to higher levels only if quota is > 0. */
  if (sc->quota <= 0) return 0;
#endif

  /* This looks complicated, but remember: typically packets up */
  /*  to 2048 bytes long fit in one mbuf and use one descriptor. */

  first_desc = last_desc = ring->read;

  /* ASSERTION: If there is a descriptor in the ring and the hardware has */
  /*  finished with it, then that descriptor will have RX_FIRST_DESC set. */
  if ((ring->read != ring->write) && /* descriptor ring not empty */
     ((ring->read->status & TLP_DSTS_OWNER) == 0) && /* hardware done */
     ((ring->read->status & TLP_DSTS_RX_FIRST_DESC) == 0)) /* should be set */
    panic("%s: rxintr_cleanup: rx-first-descriptor not set.\n", NAME_UNIT);

  /* First decide if a complete packet has arrived. */
  /* Run down DMA descriptors looking for one marked "last". */
  /* Bail out if an active descriptor is encountered. */
  /* Accumulate most significant bits of packet length. */
  pkt_len = 0;
  for (;;)
    {
    if (last_desc == ring->write) return 0;  /* no more descs */
    if (last_desc->status & TLP_DSTS_OWNER) return 0; /* still active */
    if (last_desc->status & TLP_DSTS_RX_LAST_DESC) break; /* end of packet */
    pkt_len += last_desc->length1 + last_desc->length2; /* entire desc filled */
    if (last_desc++->control & TLP_DCTL_END_RING) last_desc = ring->first; /* ring wrap */
    }

  /* A complete packet has arrived; how long is it? */
  /* H/w ref man shows RX pkt length as a 14-bit field. */
  /* An experiment found that only the 12 LSBs work. */
  if (((last_desc->status>>16)&0xFFF) == 0) pkt_len += 4096; /* carry-bit */
  pkt_len = (pkt_len & 0xF000) + ((last_desc->status>>16) & 0x0FFF);
  /* Subtract the CRC length unless doing so would underflow. */
  if (pkt_len >= sc->config.crc_len) pkt_len -= sc->config.crc_len;

  /* Run down DMA descriptors again doing the following:
   *  1) put pkt info in pkthdr of first mbuf,
   *  2) link mbufs,
   *  3) set mbuf lengths.
   */
  first_desc = ring->read;
  do
    {
    /* Read a DMA descriptor from the ring. */
    last_desc = ring->read;
    /* Advance the ring read pointer. */
    if (ring->read++ == ring->last) ring->read = ring->first;

    /* Dequeue the corresponding cluster mbuf. */
    new_mbuf = mbuf_dequeue(ring);
    if (new_mbuf == NULL)
      panic("%s: rxintr_cleanup: expected an mbuf\n", NAME_UNIT);

    desc_len = last_desc->length1 + last_desc->length2;
    /* If bouncing, copy bounce buf to mbuf. */
    DMA_SYNC(last_desc->map, desc_len, BUS_DMASYNC_POSTREAD);
    /* Unmap kernel virtual address to PCI address. */
    bus_dmamap_unload(ring->tag, last_desc->map);

    /* 1) Put pkt info in pkthdr of first mbuf. */
    if (last_desc == first_desc)
      {
      first_mbuf = new_mbuf;
      first_mbuf->m_pkthdr.len   = pkt_len; /* total pkt length */
#if IFNET
      first_mbuf->m_pkthdr.rcvif = sc->ifp; /* how it got here */
#else
      first_mbuf->m_pkthdr.rcvif = NULL;
#endif
      }
    else /* 2) link mbufs. */
      {
      last_mbuf->m_next = new_mbuf;
      /* M_PKTHDR should be set in the first mbuf only. */
      new_mbuf->m_flags &= ~M_PKTHDR;
      }
    last_mbuf = new_mbuf;

    /* 3) Set mbuf lengths. */
    new_mbuf->m_len = (pkt_len >= desc_len) ? desc_len : pkt_len;
    pkt_len -= new_mbuf->m_len;
    } while ((last_desc->status & TLP_DSTS_RX_LAST_DESC) == 0);

  /* Decide whether to accept or to discard this packet. */
  /* RxHDLC sets MIIERR for bad CRC, abort and partial byte at pkt end. */
  if (((last_desc->status & TLP_DSTS_RX_BAD) == 0) &&
   (sc->status.oper_status == STATUS_UP) &&
   (first_mbuf->m_pkthdr.len > 0))
    {
    /* Optimization: copy a small pkt into a small mbuf. */
    if (first_mbuf->m_pkthdr.len <= COPY_BREAK)
      {
      MGETHDR(new_mbuf, M_DONTWAIT, MT_DATA);
      if (new_mbuf != NULL)
        {
        new_mbuf->m_pkthdr.rcvif = first_mbuf->m_pkthdr.rcvif;
        new_mbuf->m_pkthdr.len   = first_mbuf->m_pkthdr.len;
        new_mbuf->m_len          = first_mbuf->m_len;
        memcpy(new_mbuf->m_data,   first_mbuf->m_data,
         first_mbuf->m_pkthdr.len);
        m_freem(first_mbuf);
        first_mbuf = new_mbuf;
        }
      }
    /* Include CRC and one flag byte in input byte count. */
    sc->status.cntrs.ibytes += first_mbuf->m_pkthdr.len + sc->config.crc_len +1;
    sc->status.cntrs.ipackets++;
#if IFNET
    sc->ifp->if_ipackets++;
    LMC_BPF_MTAP(first_mbuf);
#endif
#if (defined(__FreeBSD__) && defined(DEVICE_POLLING))
    sc->quota--;
#endif

    /* Give this good packet to the network stacks. */
#if NETGRAPH
    if (sc->ng_hook != NULL) /* is hook connected? */
      {
# if (__FreeBSD_version >= 500000)
      int error;  /* ignore error */
      NG_SEND_DATA_ONLY(error, sc->ng_hook, first_mbuf);
# else /* FreeBSD-4 */
      ng_queue_data(sc->ng_hook, first_mbuf, NULL);
# endif
      return 1;  /* did something */
      }
#endif /* NETGRAPH */
    if (sc->config.line_pkg == PKG_RAWIP)
      lmc_raw_input(sc->ifp, first_mbuf);
    else
      {
#if NSPPP
      sppp_input(sc->ifp, first_mbuf);
#elif P2P
      new_mbuf = first_mbuf;
      while (new_mbuf != NULL)
        {
        sc->p2p->p2p_hdrinput(sc->p2p, new_mbuf->m_data, new_mbuf->m_len);
        new_mbuf = new_mbuf->m_next;
        }
      sc->p2p->p2p_input(sc->p2p, NULL);
      m_freem(first_mbuf);
#else
      m_freem(first_mbuf);
      sc->status.cntrs.idiscards++;
#endif
      }
    }
  else if (sc->status.oper_status != STATUS_UP)
    {
    /* If the link is down, this packet is probably noise. */
    m_freem(first_mbuf);
    sc->status.cntrs.idiscards++;
    if (DRIVER_DEBUG)
      printf("%s: rxintr_cleanup: rx pkt discarded: link down\n", NAME_UNIT);
    }
  else /* Log and discard this bad packet. */
    {
    if (DRIVER_DEBUG)
      printf("%s: RX bad pkt; len=%d %s%s%s%s\n",
       NAME_UNIT, first_mbuf->m_pkthdr.len,
       (last_desc->status & TLP_DSTS_RX_MII_ERR)  ? " miierr"  : "",
       (last_desc->status & TLP_DSTS_RX_DRIBBLE)  ? " dribble" : "",
       (last_desc->status & TLP_DSTS_RX_DESC_ERR) ? " descerr" : "",
       (last_desc->status & TLP_DSTS_RX_OVERRUN)  ? " overrun" : "");
    if (last_desc->status & TLP_DSTS_RX_OVERRUN)
      sc->status.cntrs.fifo_over++;
    else
      sc->status.cntrs.ierrors++;
    m_freem(first_mbuf);
    }

  return 1; /* did something */
  }

/* Setup (prepare) to receive a packet. */
/* Try to keep the RX descriptor ring full of empty buffers. */
static int  /* BSD version */
rxintr_setup(softc_t *sc)
  {
  struct desc_ring *ring = &sc->rxring;
  struct dma_desc *desc;
  struct mbuf *m;
  int desc_len;
  int error;

  /* Ring is full if (wrap(write+1)==read) */
  if (((ring->write == ring->last) ? ring->first : ring->write+1) == ring->read)
    return 0;  /* ring is full; nothing to do */

  /* Allocate a small mbuf and attach an mbuf cluster. */
  MGETHDR(m, M_DONTWAIT, MT_DATA);
  if (m == NULL)
    {
    sc->status.cntrs.rxdma++;
    if (DRIVER_DEBUG)
      printf("%s: rxintr_setup: MGETHDR() failed\n", NAME_UNIT);
    return 0;
    }
  MCLGET(m, M_DONTWAIT);
  if ((m->m_flags & M_EXT) == 0)
    {
    m_freem(m);
    sc->status.cntrs.rxdma++;
    if (DRIVER_DEBUG)
      printf("%s: rxintr_setup: MCLGET() failed\n", NAME_UNIT);
    return 0;
    }

  /* Queue the mbuf for later processing by rxintr_cleanup. */
  mbuf_enqueue(ring, m);

  /* Write a DMA descriptor into the ring. */
  /* Hardware won't see it until the OWNER bit is set. */
  desc = ring->write;
  /* Advance the ring write pointer. */
  if (ring->write++ == ring->last) ring->write = ring->first;

  desc_len = (MCLBYTES < MAX_DESC_LEN) ? MCLBYTES : MAX_DESC_LEN;
  /* Map kernel virtual address to PCI address. */
  if ((error = DMA_LOAD(desc->map, m->m_data, desc_len)))
    printf("%s: bus_dmamap_load(rx) failed; error %d\n", NAME_UNIT, error);
  /* Invalidate the cache for this mbuf. */
  DMA_SYNC(desc->map, desc_len, BUS_DMASYNC_PREREAD);

  /* Set up the DMA descriptor. */
#ifdef __FreeBSD__
  desc->address1 = ring->segs[0].ds_addr;
#elif (defined(__NetBSD__) || defined(__OpenBSD__))
  desc->address1 = desc->map->dm_segs[0].ds_addr;
#elif defined(__bsdi__)
  desc->address1 = vtophys(m->m_data); /* Relax! BSD/OS only. */
#endif
  desc->length1  = desc_len>>1;
  desc->address2 = desc->address1 + desc->length1;
  desc->length2  = desc_len>>1;

  /* Before setting the OWNER bit, flush the cache (memory barrier). */
  DMA_SYNC(ring->map, ring->size_descs, BUS_DMASYNC_PREWRITE);

  /* Commit the DMA descriptor to the hardware. */
  desc->status = TLP_DSTS_OWNER;

  /* Notify the receiver that there is another buffer available. */
  WRITE_CSR(TLP_RX_POLL, 1);

  return 1; /* did something */
  }

/* Clean up after a packet has been transmitted. */
/* Free the mbuf chain and update the DMA descriptor ring. */
static int  /* BSD version */
txintr_cleanup(softc_t *sc)
  {
  struct desc_ring *ring = &sc->txring;
  struct dma_desc *desc;

  while ((ring->read != ring->write) && /* while ring is not empty */
        ((ring->read->status & TLP_DSTS_OWNER) == 0))
    {
    /* Read a DMA descriptor from the ring. */
    desc = ring->read;
    /* Advance the ring read pointer. */
    if (ring->read++ == ring->last) ring->read = ring->first;

    /* This is a no-op on most architectures. */
    DMA_SYNC(desc->map, desc->length1 + desc->length2, BUS_DMASYNC_POSTWRITE);
    /* Unmap kernel virtual address to PCI address. */
    bus_dmamap_unload(ring->tag, desc->map);

    /* If this descriptor is the last segment of a packet, */
    /*  then dequeue and free the corresponding mbuf chain. */
    if ((desc->control & TLP_DCTL_TX_LAST_SEG) != 0)
      {
      struct mbuf *m;
      if ((m = mbuf_dequeue(ring)) == NULL)
        panic("%s: txintr_cleanup: expected an mbuf\n", NAME_UNIT);

      /* Include CRC and one flag byte in output byte count. */
      sc->status.cntrs.obytes += m->m_pkthdr.len + sc->config.crc_len +1;
      sc->status.cntrs.opackets++;
#if IFNET
      sc->ifp->if_opackets++;
      LMC_BPF_MTAP(m);
#endif
      /* The only bad TX status is fifo underrun. */
      if ((desc->status & TLP_DSTS_TX_UNDERRUN) != 0)
        sc->status.cntrs.fifo_under++;

      m_freem(m);
      return 1;  /* did something */
      }
    }

  return 0;
  }

/* Build DMA descriptors for a transmit packet mbuf chain. */
static int /* 0=success; 1=error */ /* BSD version */
txintr_setup_mbuf(softc_t *sc, struct mbuf *m)
  {
  struct desc_ring *ring = &sc->txring;
  struct dma_desc *desc;
  unsigned int desc_len;

  /* build DMA descriptors for a chain of mbufs. */
  while (m != NULL)
    {
    char *data = m->m_data;
    int length = m->m_len; /* zero length mbufs happen! */

    /* Build DMA descriptors for one mbuf. */
    while (length > 0)
      {
      int error;

      /* Ring is full if (wrap(write+1)==read) */
      if (((ring->temp==ring->last) ? ring->first : ring->temp+1) == ring->read)
        { /* Not enough DMA descriptors; try later. */
        for (; ring->temp!=ring->write;
         ring->temp = (ring->temp==ring->first)? ring->last : ring->temp-1)
          bus_dmamap_unload(ring->tag, ring->temp->map);
        sc->status.cntrs.txdma++;
        return 1;
	}

      /* Provisionally, write a descriptor into the ring. */
      /* But don't change the REAL ring write pointer. */
      /* Hardware won't see it until the OWNER bit is set. */
      desc = ring->temp;
      /* Advance the temporary ring write pointer. */
      if (ring->temp++ == ring->last) ring->temp = ring->first;

      /* Clear all control bits except the END_RING bit. */
      desc->control &= TLP_DCTL_END_RING;
      /* Don't pad short packets up to 64 bytes. */
      desc->control |= TLP_DCTL_TX_NO_PAD;
      /* Use Tulip's CRC-32 generator, if appropriate. */
      if (sc->config.crc_len != CFG_CRC_32)
        desc->control |= TLP_DCTL_TX_NO_CRC;
      /* Set the OWNER bit, except in the first descriptor. */
      if (desc != ring->write)
        desc->status = TLP_DSTS_OWNER;

      desc_len = (length > MAX_CHUNK_LEN) ? MAX_CHUNK_LEN : length;
      /* Map kernel virtual address to PCI address. */
      if ((error = DMA_LOAD(desc->map, data, desc_len)))
        printf("%s: bus_dmamap_load(tx) failed; error %d\n", NAME_UNIT, error);
      /* Flush the cache and if bouncing, copy mbuf to bounce buf. */
      DMA_SYNC(desc->map, desc_len, BUS_DMASYNC_PREWRITE);

      /* Prevent wild fetches if mapping fails (nsegs==0). */
      desc->length1  = desc->length2  = 0;
      desc->address1 = desc->address2 = 0;
#if (defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__))
        {
# ifdef __FreeBSD__
        bus_dma_segment_t *segs = ring->segs;
        int nsegs = ring->nsegs;
# elif (defined(__NetBSD__) || defined(__OpenBSD__))
        bus_dma_segment_t *segs = desc->map->dm_segs;
        int nsegs = desc->map->dm_nsegs;
# endif
        if (nsegs >= 1)
          {
          desc->address1 = segs[0].ds_addr;
          desc->length1  = segs[0].ds_len;
          }
        if (nsegs == 2)
          {
          desc->address2 = segs[1].ds_addr;
          desc->length2  = segs[1].ds_len;
          }
        }
#elif defined(__bsdi__)
      desc->address1 = vtophys(data); /* Relax! BSD/OS only. */
      desc->length1  = desc_len;
#endif

      data   += desc_len;
      length -= desc_len;
      } /* while (length > 0) */

    m = m->m_next;
    } /* while (m != NULL) */

  return 0; /* success */
  }

/* Setup (prepare) to transmit a packet. */
/* Select a packet, build DMA descriptors and give packet to hardware. */
/* If DMA descriptors run out, abandon the attempt and return 0. */
static int  /* BSD version */
txintr_setup(softc_t *sc)
  {
  struct desc_ring *ring = &sc->txring;
  struct dma_desc *first_desc, *last_desc;

  /* Protect against half-up links: Don't transmit */
  /*  if the receiver can't hear the far end. */
  if (sc->status.oper_status != STATUS_UP) return 0;

  /* Pick a packet to transmit. */
#if NETGRAPH
  if ((sc->ng_hook != NULL) && (sc->tx_mbuf == NULL))
    {
    if (!IFQ_IS_EMPTY(&sc->ng_fastq))
      IFQ_DEQUEUE(&sc->ng_fastq, sc->tx_mbuf);
    else
      IFQ_DEQUEUE(&sc->ng_sndq,  sc->tx_mbuf);
    }
  else
#endif
  if (sc->tx_mbuf == NULL)
    {
    if (sc->config.line_pkg == PKG_RAWIP)
      IFQ_DEQUEUE(&sc->ifp->if_snd, sc->tx_mbuf);
    else
      {
#if NSPPP
      sc->tx_mbuf = sppp_dequeue(sc->ifp);
#elif P2P
      if (!IFQ_IS_EMPTY(&sc->p2p->p2p_isnd))
        IFQ_DEQUEUE(&sc->p2p->p2p_isnd, sc->tx_mbuf);
      else
        IFQ_DEQUEUE(&sc->ifp->if_snd, sc->tx_mbuf);
#endif
      }
    }
  if (sc->tx_mbuf == NULL) return 0;  /* no pkt to transmit */

  /* Build DMA descriptors for an outgoing mbuf chain. */
  ring->temp = ring->write; /* temporary ring write pointer */
  if (txintr_setup_mbuf(sc, sc->tx_mbuf) != 0) return 0;

  /* Enqueue the mbuf; txintr_cleanup will free it. */
  mbuf_enqueue(ring, sc->tx_mbuf);

  /* The transmitter has room for another packet. */
  sc->tx_mbuf = NULL;

  /* Set first & last segment bits. */
  /* last_desc is the desc BEFORE the one pointed to by ring->temp. */
  first_desc = ring->write;
  first_desc->control |= TLP_DCTL_TX_FIRST_SEG;
  last_desc = (ring->temp==ring->first)? ring->last : ring->temp-1;
   last_desc->control |= TLP_DCTL_TX_LAST_SEG;
  /* Interrupt at end-of-transmission?  Why bother the poor computer! */
/* last_desc->control |= TLP_DCTL_TX_INTERRUPT; */

  /* Make sure the OWNER bit is not set in the next descriptor. */
  /* The OWNER bit may have been set if a previous call aborted. */
  ring->temp->status = 0;

  /* Commit the DMA descriptors to the software. */
  ring->write = ring->temp;

  /* Before setting the OWNER bit, flush the cache (memory barrier). */
  DMA_SYNC(ring->map, ring->size_descs, BUS_DMASYNC_PREWRITE);

  /* Commit the DMA descriptors to the hardware. */
  first_desc->status = TLP_DSTS_OWNER;

  /* Notify the transmitter that there is another packet to send. */
  WRITE_CSR(TLP_TX_POLL, 1);

  return 1; /* did something */
  }

#endif /* BSD */

#ifdef __linux__
/* NOTE: this is the LINUX version of the interrupt/DMA code, */

/* Singly-linked tail-queues hold sk_buffs with active DMA.
 * skbuffs are linked through their sk_buff.next field.
 * Callers must hold sc->bottom_lock; not otherwise locked.
 */

/* Put an skbuff on the tail of the descriptor ring queue. */
static void  /* Linux version */
skbuff_enqueue(struct desc_ring *ring, struct sk_buff *skb)
  {
  skb->next = NULL;
  if (ring->tail == NULL)
    ring->head = skb;
  else
    ring->tail->next = skb;
  ring->tail = skb;
  }

/* Get an skbuff from the head of the descriptor ring queue. */
static struct sk_buff*  /* Linux version */
skbuff_dequeue(struct desc_ring *ring)
  {
  struct sk_buff *skb = ring->head;
  if (skb != NULL)
    if ((ring->head = skb->next) == NULL)
      ring->tail = NULL;
  return skb;
  }

/* Initialize a DMA descriptor ring. */
static int  /* Linux version */
create_ring(softc_t *sc, struct desc_ring *ring, int num_descs)
  {
  struct dma_desc *descs;
  int size_descs = sizeof(struct dma_desc)*num_descs;

  /* Allocate and map memory for DMA descriptor array. */
  if ((descs = pci_alloc_consistent(sc->pci_dev, size_descs,
   &ring->dma_addr)) == NULL)
    {
    printk("%s: pci_alloc_consistent() failed\n", NAME_UNIT);
    return ENOMEM;
    }
  memset(descs, 0, size_descs);

  ring->read  = descs;
  ring->write = descs;
  ring->first = descs;
  ring->last  = descs + num_descs -1;
  ring->last->control = TLP_DCTL_END_RING;
  ring->num_descs = num_descs;
  ring->size_descs = size_descs;
  ring->head = NULL;
  ring->tail = NULL;

  return 0;
  }

/* Destroy a DMA descriptor ring */
static void  /* Linux version */
destroy_ring(softc_t *sc, struct desc_ring *ring)
  {
  struct sk_buff *skb;

  /* Free queued skbuffs. */
  while ((skb = skbuff_dequeue(ring)) != NULL)
    dev_kfree_skb(skb);

  /* TX may have one pkt that is not on any queue. */
  if (sc->tx_skb != NULL)
    {
    dev_kfree_skb(sc->tx_skb);
    sc->tx_skb = NULL;
    }

  if (ring->first != NULL)
    {
    /* Unmap active DMA descriptors. */
    while (ring->read != ring->write)
      {
      pci_unmap_single(sc->pci_dev, ring->read->address1,
       ring->read->length1 + ring->read->length2, PCI_DMA_BIDIRECTIONAL);
      if (ring->read++ == ring->last) ring->read = ring->first;
      }

    /* Unmap and free memory for DMA descriptor array. */
    pci_free_consistent(sc->pci_dev, ring->size_descs, ring->first,
     ring->dma_addr);
    }
  }

static int  /* Linux version */
rxintr_cleanup(softc_t *sc)
  {
  struct desc_ring *ring = &sc->rxring;
  struct dma_desc *first_desc, *last_desc;
  struct sk_buff *first_skb=NULL, *last_skb=NULL;
  struct sk_buff *new_skb;
  int pkt_len, desc_len;

  /* Input packet flow control (livelock prevention): */
  /* Give pkts to higher levels only if quota is > 0. */
  if (sc->quota <= 0) return 0;

  /* This looks complicated, but remember: packets up to 4032 */
  /*  bytes long fit in one skbuff and use one DMA descriptor. */

  first_desc = last_desc = ring->read;

  /* ASSERTION: If there is a descriptor in the ring and the hardware has */
  /*  finished with it, then that descriptor will have RX_FIRST_DESC set. */
  if ((ring->read != ring->write) && /* descriptor ring not empty */
     ((ring->read->status & TLP_DSTS_OWNER) == 0) && /* hardware done */
     ((ring->read->status & TLP_DSTS_RX_FIRST_DESC) == 0)) /* should be set */
    panic("%s: rxintr_cleanup: rx-first-descriptor not set.\n", NAME_UNIT);

  /* First decide if a complete packet has arrived. */
  /* Run down DMA descriptors looking for one marked "last". */
  /* Bail out if an active descriptor is encountered. */
  /* Accumulate most significant bits of packet length. */
  pkt_len = 0;
  for (;;)
    {
    if (last_desc == ring->write) return 0;  /* no more descs */
    if (last_desc->status & TLP_DSTS_OWNER) return 0; /* still active */
    if (last_desc->status & TLP_DSTS_RX_LAST_DESC) break; /* end of packet */
    pkt_len += last_desc->length1 + last_desc->length2; /* entire desc filled */
    if (last_desc++->control & TLP_DCTL_END_RING) last_desc = ring->first; /* ring wrap */
    }

  /* A complete packet has arrived; how long is it? */
  /* H/w ref man shows RX pkt length as a 14-bit field. */
  /* An experiment found that only the 12 LSBs work. */
  if (((last_desc->status>>16)&0xFFF) == 0) pkt_len += 4096; /* carry-bit */
  pkt_len = (pkt_len & 0xF000) + ((last_desc->status>>16) & 0x0FFF);
  /* Subtract the CRC length unless doing so would underflow. */
  if (pkt_len >= sc->config.crc_len) pkt_len -= sc->config.crc_len;

  /* Run down DMA descriptors again doing the following:
   *  1) put pkt info in hdr of first skbuff.
   *  2) put additional skbuffs on frag_list.
   *  3) set skbuff lengths.
   */
  first_desc = ring->read;
  do
    {
    /* Read a DMA descriptor from the ring. */
    last_desc = ring->read;
    /* Advance the ring read pointer. */
    if (ring->read++ == ring->last) ring->read = ring->first;

    /* Dequeue the corresponding skbuff. */
    new_skb = skbuff_dequeue(ring);
    if (new_skb == NULL)
      panic("%s: rxintr_cleanup: expected an skbuff\n", NAME_UNIT);

    desc_len = last_desc->length1 + last_desc->length2;
    /* Unmap kernel virtual addresss to PCI address. */
    pci_unmap_single(sc->pci_dev, last_desc->address1,
     desc_len, PCI_DMA_FROMDEVICE);

    /* Set skbuff length. */
    skb_put(new_skb, (pkt_len >= desc_len) ? desc_len : pkt_len);
    pkt_len -= new_skb->len;

    /* 1) Put pkt info in hdr of first skbuff. */
    if (last_desc == first_desc)
      {
      first_skb = new_skb;
      if (sc->config.line_pkg == PKG_RAWIP)
        {
        if      (first_skb->data[0]>>4 == 4)
          first_skb->protocol = htons(ETH_P_IP);
        else if (first_skb->data[0]>>4 == 6)
          first_skb->protocol = htons(ETH_P_IPV6);
	}
      else
#if GEN_HDLC
        first_skb->protocol = hdlc_type_trans(first_skb, sc->net_dev);
#else
        first_skb->protocol = htons(ETH_P_HDLC);
#endif
      first_skb->mac.raw = first_skb->data;
      first_skb->dev = sc->net_dev;
      do_gettimeofday(&first_skb->stamp);
      sc->net_dev->last_rx = jiffies;
      }
    else /* 2) link skbuffs. */
      {
      /* Put this skbuff on the frag_list of the first skbuff. */
      new_skb->next = NULL;
      if (skb_shinfo(first_skb)->frag_list == NULL)
        skb_shinfo(first_skb)->frag_list = new_skb;
      else
        last_skb->next = new_skb;
      /* 3) set skbuff lengths. */
      first_skb->len      += new_skb->len;
      first_skb->data_len += new_skb->len;
      }
    last_skb = new_skb;
    } while ((last_desc->status & TLP_DSTS_RX_LAST_DESC) == 0);

  /* Decide whether to accept or to discard this packet. */
  /* RxHDLC sets MIIERR for bad CRC, abort and partial byte at pkt end. */
  if (((last_desc->status & TLP_DSTS_RX_BAD) == 0) &&
   (sc->status.oper_status == STATUS_UP) &&
   (first_skb->len > 0))
    {
    /* Optimization: copy a small pkt into a small skbuff. */
    if (first_skb->len <= COPY_BREAK)
      if ((new_skb = skb_copy(first_skb, GFP_ATOMIC)) != NULL)
        {
        dev_kfree_skb_any(first_skb);
        first_skb = new_skb;
	}

    /* Include CRC and one flag byte in input byte count. */
    sc->status.cntrs.ibytes += first_skb->len + sc->config.crc_len +1;
    sc->status.cntrs.ipackets++;

    /* Give this good packet to the network stacks. */
    netif_receive_skb(first_skb);  /* NAPI */
    sc->quota--;
    }
  else if (sc->status.oper_status != STATUS_UP)
    {
    /* If the link is down, this packet is probably noise. */
    sc->status.cntrs.idiscards++;
    dev_kfree_skb_any(first_skb);
    if (DRIVER_DEBUG)
      printk("%s: rxintr_cleanup: rx pkt discarded: link down\n", NAME_UNIT);
    }
  else /* Log and discard this bad packet. */
    {
    if (DRIVER_DEBUG)
      printk("%s: RX bad pkt; len=%d %s%s%s%s\n",
       NAME_UNIT, first_skb->len,
       (last_desc->status & TLP_DSTS_RX_MII_ERR)  ? " miierr"  : "",
       (last_desc->status & TLP_DSTS_RX_DRIBBLE)  ? " dribble" : "",
       (last_desc->status & TLP_DSTS_RX_DESC_ERR) ? " descerr" : "",
       (last_desc->status & TLP_DSTS_RX_OVERRUN)  ? " overrun" : "");
    if (last_desc->status & TLP_DSTS_RX_OVERRUN)
      sc->status.cntrs.fifo_over++;
    else
      sc->status.cntrs.ierrors++;
    dev_kfree_skb_any(first_skb);
    }

  return 1; /* did something */
  }

/* Setup (prepare) to receive a packet. */
/* Try to keep the RX descriptor ring full of empty buffers. */
static int  /* Linux version */
rxintr_setup(softc_t *sc)
  {
  struct desc_ring *ring = &sc->rxring;
  struct dma_desc *desc;
  struct sk_buff *skb;
  u_int32_t dma_addr;

  /* Ring is full if (wrap(write+1)==read) */
  if (((ring->write == ring->last) ? ring->first : ring->write+1) == ring->read)
    return 0;  /* ring is full; nothing to do */

  /* Allocate an skbuff. */
  if ((skb = dev_alloc_skb(MAX_DESC_LEN)) == NULL)
    {
    sc->status.cntrs.rxdma++;
    if (DRIVER_DEBUG)
      printk("%s: rxintr_setup: dev_alloc_skb() failed\n", NAME_UNIT);
    return 0;
    }
  skb->dev = sc->net_dev;

  /* Queue the skbuff for later processing by rxintr_cleanup. */
  skbuff_enqueue(ring, skb);

  /* Write a DMA descriptor into the ring. */
  /* Hardware won't see it until the OWNER bit is set. */
  desc = ring->write;
  /* Advance the ring write pointer. */
  if (ring->write++ == ring->last) ring->write = ring->first;

  /* Map kernel virtual addresses to PCI addresses. */
  dma_addr = pci_map_single(sc->pci_dev, skb->data,
   MAX_DESC_LEN, PCI_DMA_FROMDEVICE);
  /* Set up the DMA descriptor. */
  desc->address1 = dma_addr;
  desc->length1  = MAX_CHUNK_LEN;
  desc->address2 = desc->address1 + desc->length1;
  desc->length2  = MAX_CHUNK_LEN;

  /* Before setting the OWNER bit, flush the cache (memory barrier). */
  wmb(); /* write memory barrier */

  /* Commit the DMA descriptor to the hardware. */
  desc->status = TLP_DSTS_OWNER;

  /* Notify the receiver that there is another buffer available. */
  WRITE_CSR(TLP_RX_POLL, 1);

  return 1; /* did something */
  }

/* Clean up after a packet has been transmitted. */
/* Free the sk_buff and update the DMA descriptor ring. */
static int  /* Linux version */
txintr_cleanup(softc_t *sc)
  {
  struct desc_ring *ring = &sc->txring;
  struct dma_desc *desc;

  while ((ring->read != ring->write) && /* ring is not empty */
        ((ring->read->status & TLP_DSTS_OWNER) == 0))
    {
    /* Read a DMA descriptor from the ring. */
    desc = ring->read;
    /* Advance the ring read pointer. */
    if (ring->read++ == ring->last) ring->read = ring->first;
    /* Unmap kernel virtual address to PCI address. */
    pci_unmap_single(sc->pci_dev, desc->address1,
     desc->length1 + desc->length2, PCI_DMA_TODEVICE);

    /* If this descriptor is the last segment of a packet, */
    /*  then dequeue and free the corresponding skbuff. */
    if ((desc->control & TLP_DCTL_TX_LAST_SEG) != 0)
      {
      struct sk_buff *skb;
      if ((skb = skbuff_dequeue(ring)) == NULL)
        panic("%s: txintr_cleanup: expected an sk_buff\n", NAME_UNIT);

      /* Include CRC and one flag byte in output byte count. */
      sc->status.cntrs.obytes += skb->len + sc->config.crc_len +1;
      sc->status.cntrs.opackets++;

      /* The only bad TX status is fifo underrun. */
      if ((desc->status & TLP_DSTS_TX_UNDERRUN) != 0)
        {
        sc->status.cntrs.fifo_under++; /* also increment oerrors? */
        if (DRIVER_DEBUG)
          printk("%s: txintr_cleanup: tx fifo underrun\n", NAME_UNIT);
	}

      dev_kfree_skb_any(skb);
      return 1;  /* did something */
      }
    }

  return 0;
  }

/* Build DMA descriptors for a tranmit packet fragment, */
/* Assertion: fragment is contiguous in physical memory. */
static int /* 0=success; 1=error */ /* linux version */
txintr_setup_frag(softc_t *sc, char *data, int length)
  {
  struct desc_ring *ring = &sc->txring;
  struct dma_desc *desc;
  unsigned int desc_len;
  u_int32_t dma_addr;

  while (length > 0)
    {
    /* Ring is full if (wrap(write+1)==read) */
    if (((ring->temp==ring->last) ? ring->first : ring->temp+1) == ring->read)
      { /* Not enough DMA descriptors; try later. */
      for (; ring->temp!=ring->write;
       ring->temp = (ring->temp==ring->first)? ring->last : ring->temp-1)
        pci_unmap_single(sc->pci_dev, ring->temp->address1,
         ring->temp->length1 + ring->temp->length2, PCI_DMA_FROMDEVICE);
      sc->status.cntrs.txdma++;
      return 1;
      }

    /* Provisionally, write a DMA descriptor into the ring. */
    /* But don't change the REAL ring write pointer. */
    /* Hardware won't see it until the OWNER bit is set. */
    desc = ring->temp;
    /* Advance the temporary ring write pointer. */
    if (ring->temp++ == ring->last) ring->temp = ring->first;

    /* Clear all control bits except the END_RING bit. */
    desc->control &= TLP_DCTL_END_RING;
    /* Don't pad short packets up to 64 bytes */
    desc->control |= TLP_DCTL_TX_NO_PAD;
    /* Use Tulip's CRC-32 generator, if appropriate. */
    if (sc->config.crc_len != CFG_CRC_32)
      desc->control |= TLP_DCTL_TX_NO_CRC;
    /* Set the OWNER bit, except in the first descriptor. */
    if (desc != ring->write)
      desc->status = TLP_DSTS_OWNER;

    desc_len = (length >= MAX_DESC_LEN) ? MAX_DESC_LEN : length;
    /* Map kernel virtual address to PCI address. */
    dma_addr = pci_map_single(sc->pci_dev, data, desc_len, PCI_DMA_TODEVICE);
    /* If it will fit in one chunk, do so, otherwise split it. */
    if (desc_len <= MAX_CHUNK_LEN)
      {
      desc->address1 = dma_addr;
      desc->length1  = desc_len;
      desc->address2 = 0;
      desc->length2  = 0;
      }
    else
      {
      desc->address1 = dma_addr;
      desc->length1  = desc_len>>1;
      desc->address2 = desc->address1 + desc->length1;
      desc->length2  = desc_len>>1;
      if (desc_len & 1) desc->length2++;
      }

    data   += desc_len;
    length -= desc_len;
    } /* while (length > 0) */

  return 0; /* success */
  }

/* NB: this procedure is recursive! */
static int /* 0=success; 1=error */
txintr_setup_skb(softc_t *sc, struct sk_buff *skb)
  {
  struct sk_buff *list;
  int i;

  /* First, handle the data in the skbuff itself. */
  if (txintr_setup_frag(sc, skb->data, skb_headlen(skb)))
    return 1;

  /* Next, handle the VM pages in the Scatter/Gather list. */
  if (skb_shinfo(skb)->nr_frags != 0)
    for (i=0; i<skb_shinfo(skb)->nr_frags; i++)
      {
      skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
      if (txintr_setup_frag(sc, page_address(frag->page) +
       frag->page_offset, frag->size))
        return 1;
      }

  /* Finally, handle the skbuffs in the frag_list. */
  if ((list = skb_shinfo(skb)->frag_list) != NULL)
    for (; list; list=list->next)
      if (txintr_setup_skb(sc, list)) /* recursive! */
        return 1;

  return 0;
  }

/* Setup (prepare) to transmit a packet. */
/* Select a packet, build DMA descriptors and give packet to hardware. */
/* If DMA descriptors run out, abandon the attempt and return 0. */
static int  /* Linux version */
txintr_setup(softc_t *sc)
  {
  struct desc_ring *ring = &sc->txring;
  struct dma_desc *first_desc, *last_desc;

  /* Protect against half-up links: Don't transmit */
  /*  if the receiver can't hear the far end. */
  if (sc->status.oper_status != STATUS_UP) return 0;

  /* Pick a packet to transmit. */
  /* linux_start() puts packets in sc->tx_skb. */
  if (sc->tx_skb == NULL)
    {
    if (netif_queue_stopped(sc->net_dev) != 0)
      netif_wake_queue(sc->net_dev);
    return 0; /* no pkt to transmit */
    }

  /* Build DMA descriptors for an outgoing skbuff. */
  ring->temp = ring->write; /* temporary ring write pointer */
  if (txintr_setup_skb(sc, sc->tx_skb) != 0) return 0;

  /* Enqueue the skbuff; txintr_cleanup will free it. */
  skbuff_enqueue(ring, sc->tx_skb);

  /* The transmitter has room for another packet. */
  sc->tx_skb = NULL;

  /* Set first & last segment bits. */
  /* last_desc is the desc BEFORE the one pointed to by ring->temp. */
  first_desc = ring->write;
  first_desc->control |= TLP_DCTL_TX_FIRST_SEG;
  last_desc = (ring->temp==ring->first)? ring->last : ring->temp-1;
   last_desc->control |= TLP_DCTL_TX_LAST_SEG;
  /* Interrupt at end-of-transmission?  Why bother the poor computer! */
/* last_desc->control |= TLP_DCTL_TX_INTERRUPT; */

  /* Make sure the OWNER bit is not set in the next descriptor. */
  /* The OWNER bit may have been set if a previous call aborted. */
  ring->temp->status = 0;

  /* Commit the DMA descriptors to the software. */
  ring->write = ring->temp;

  /* Before setting the OWNER bit, flush the cache (memory barrier). */
  wmb(); /* write memory barrier */

  /* Commit the DMA descriptors to the hardware. */
  first_desc->status = TLP_DSTS_OWNER;

  /* Notify the transmitter that there is another packet to send. */
  WRITE_CSR(TLP_TX_POLL, 1);

  sc->net_dev->trans_start = jiffies;

  return 1; /* did something */
  }

#endif /* __linux__ */

static void
check_intr_status(softc_t *sc)
  {
  u_int32_t status, cfcs, op_mode;
  u_int32_t missed, overruns;

  /* Check for four unusual events:
   *  1) fatal PCI bus errors       - some are recoverable
   *  2) transmitter FIFO underruns - increase fifo threshold
   *  3) receiver FIFO overruns     - clear potential hangup
   *  4) no receive descs or bufs   - count missed packets
   */

  /* 1) A fatal bus error causes a Tulip to stop initiating bus cycles. */
  /* Module unload/load or boot are the only fixes for Parity Errors. */
  /* Master and Target Aborts can be cleared and life may continue. */
  status = READ_CSR(TLP_STATUS);
  if ((status & TLP_STAT_FATAL_ERROR) != 0)
    {
    u_int32_t fatal = (status & TLP_STAT_FATAL_BITS)>>TLP_STAT_FATAL_SHIFT;
    printf("%s: FATAL PCI BUS ERROR: %s%s%s%s\n", NAME_UNIT,
     (fatal == 0) ? "PARITY ERROR" : "",
     (fatal == 1) ? "MASTER ABORT" : "",
     (fatal == 2) ? "TARGET ABORT" : "",
     (fatal >= 3) ? "RESERVED (?)" : "");
    cfcs = READ_PCI_CFG(sc, TLP_CFCS);  /* try to clear it */
    cfcs &= ~(TLP_CFCS_MSTR_ABORT | TLP_CFCS_TARG_ABORT);
    WRITE_PCI_CFG(sc, TLP_CFCS, cfcs);
    }

  /* 2) If the transmitter fifo underruns, increase the transmit fifo */
  /*  threshold: the number of bytes required to be in the fifo */
  /*  before starting the transmitter (cost: increased tx delay). */
  /* The TX_FSM must be stopped to change this parameter. */
  if ((status & TLP_STAT_TX_UNDERRUN) != 0)
    {
    op_mode = READ_CSR(TLP_OP_MODE);
    /* enable store-and-forward mode if tx_threshold tops out? */
    if ((op_mode & TLP_OP_TX_THRESH) < TLP_OP_TX_THRESH)
      {
      op_mode += 0x4000;  /* increment TX_THRESH field; can't overflow */
      WRITE_CSR(TLP_OP_MODE, op_mode & ~TLP_OP_TX_RUN);
      /* Wait for the TX FSM to stop; it might be processing a pkt. */
      while (READ_CSR(TLP_STATUS) & TLP_STAT_TX_FSM); /* XXX HANG */
      WRITE_CSR(TLP_OP_MODE, op_mode); /* restart tx */
      if (DRIVER_DEBUG)
        printf("%s: tx underrun; tx fifo threshold now %d bytes\n",
         NAME_UNIT, 128<<((op_mode>>TLP_OP_TR_SHIFT)&3));
      }
    }

  /* 3) Errata memo from Digital Equipment Corp warns that 21140A */
  /* receivers through rev 2.2 can hang if the fifo overruns. */
  /* Recommended fix: stop and start the RX FSM after an overrun. */
  missed = READ_CSR(TLP_MISSED);
  if ((overruns = ((missed & TLP_MISS_OVERRUN)>>TLP_OVERRUN_SHIFT)) != 0)
    {
    if (DRIVER_DEBUG)
      printf("%s: rx overrun cntr=%d\n", NAME_UNIT, overruns);
    sc->status.cntrs.overruns += overruns;
    if ((READ_PCI_CFG(sc, TLP_CFRV) & 0xFF) <= 0x22)
      {
      op_mode = READ_CSR(TLP_OP_MODE);
      WRITE_CSR(TLP_OP_MODE, op_mode & ~TLP_OP_RX_RUN);
      /* Wait for the RX FSM to stop; it might be processing a pkt. */
      while (READ_CSR(TLP_STATUS) & TLP_STAT_RX_FSM); /* XXX HANG */
      WRITE_CSR(TLP_OP_MODE, op_mode);  /* restart rx */
      }
    }

  /* 4) When the receiver is enabled and a packet arrives, but no DMA */
  /*  descriptor is available, the packet is counted as 'missed'. */
  /* The receiver should never miss packets; warn if it happens. */
  if ((missed = (missed & TLP_MISS_MISSED)) != 0)
    {
    if (DRIVER_DEBUG)
      printf("%s: rx missed %d pkts\n", NAME_UNIT, missed);
    sc->status.cntrs.missed += missed;
    }
  }

static void /* This is where the work gets done. */
core_interrupt(void *arg, int check_status)
  {
  softc_t *sc = arg;
  int activity;

  /* If any CPU is inside this critical section, then */
  /* other CPUs should go away without doing anything. */
  if (BOTTOM_TRYLOCK == 0)
    {
    sc->status.cntrs.lck_intr++;
    return;
    }

  /* Clear pending card interrupts. */
  WRITE_CSR(TLP_STATUS, READ_CSR(TLP_STATUS));

  /* In Linux, pci_alloc_consistent() means DMA descriptors */
  /*  don't need explicit syncing. */
#if BSD
  {
  struct desc_ring *ring = &sc->txring;
  DMA_SYNC(sc->txring.map, sc->txring.size_descs,
   BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
  ring = &sc->rxring;
  DMA_SYNC(sc->rxring.map, sc->rxring.size_descs,
   BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
  }
#endif

  do  /* This is the main loop for interrupt processing. */
    {
    activity  = txintr_cleanup(sc);
    activity += txintr_setup(sc);
    activity += rxintr_cleanup(sc);
    activity += rxintr_setup(sc);
    } while (activity);

#if BSD
  {
  struct desc_ring *ring = &sc->txring;
  DMA_SYNC(sc->txring.map, sc->txring.size_descs,
   BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
  ring = &sc->rxring;
  DMA_SYNC(sc->rxring.map, sc->rxring.size_descs,
   BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
  }
#endif

  /* As the interrupt is dismissed, check for four unusual events. */
  if (check_status) check_intr_status(sc);

  BOTTOM_UNLOCK;
  }

/* user_interrupt() may be called from a syscall or a softirq */
static void
user_interrupt(softc_t *sc, int check_status)
  {
  DISABLE_INTR; /* noop on FreeBSD-5 and Linux */
  core_interrupt(sc, check_status);
  ENABLE_INTR;  /* noop on FreeBSD-5 and Linux */
  }

#if BSD

# if (defined(__FreeBSD__) && defined(DEVICE_POLLING))

/* Service the card from the kernel idle loop without interrupts. */
static void
fbsd_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
  {
  softc_t *sc = IFP2SC(ifp);

#if (__FreeBSD_version < 700000)
  if ((ifp->if_capenable & IFCAP_POLLING) == 0)
    {
    ether_poll_deregister(ifp);
    cmd = POLL_DEREGISTER;
    }

  if (cmd == POLL_DEREGISTER)
    {
    /* Last call -- reenable card interrupts. */
    WRITE_CSR(TLP_INT_ENBL, TLP_INT_TXRX);
    return;
    }
#endif

  sc->quota = count;
  core_interrupt(sc, (cmd==POLL_AND_CHECK_STATUS));
  }

# endif  /* (__FreeBSD__ && DEVICE_POLLING) */

/* BSD kernels call this procedure when an interrupt happens. */
static intr_return_t
bsd_interrupt(void *arg)
  {
  softc_t *sc = arg;

  /* Cut losses early if this is not our interrupt. */
  if ((READ_CSR(TLP_STATUS) & TLP_INT_TXRX) == 0)
    return IRQ_NONE;

# if (defined(__FreeBSD__) && defined(DEVICE_POLLING))
  if (sc->ifp->if_capenable & IFCAP_POLLING)
    return IRQ_NONE;

  if ((sc->ifp->if_capabilities & IFCAP_POLLING) &&
   (ether_poll_register(fbsd_poll, sc->ifp)))
    {
    WRITE_CSR(TLP_INT_ENBL, TLP_INT_DISABLE);
    return IRQ_NONE;
    }
  else
    sc->quota = sc->rxring.num_descs; /* input flow control */
# endif  /* (__FreeBSD__ && DEVICE_POLLING) */

  /* Disable card interrupts. */
  WRITE_CSR(TLP_INT_ENBL, TLP_INT_DISABLE);

  core_interrupt(sc, 0);

  /* Enable card interrupts. */
  WRITE_CSR(TLP_INT_ENBL, TLP_INT_TXRX);

  return IRQ_HANDLED;
  }

#endif /* BSD */

/* Administrative status of the driver (UP or DOWN) has changed. */
/* A card-specific action may be required: T1 and T3 cards: no-op. */
/* HSSI and SSI cards change the state of modem ready signals. */
static void
set_status(softc_t *sc, int status)
  {
  struct ioctl ioctl;

  ioctl.cmd = IOCTL_SET_STATUS;
  ioctl.data = status;

  sc->card->ioctl(sc, &ioctl);
  }

#if P2P

/* Callout from P2P: */
/* Get the state of DCD (Data Carrier Detect). */
static int
p2p_getmdm(struct p2pcom *p2p, caddr_t result)
  {
  softc_t *sc = IFP2SC(&p2p->p2p_if);

  /* Non-zero isn't good enough; TIOCM_CAR is 0x40. */
  *(int *)result = (sc->status.oper_status==STATUS_UP) ? TIOCM_CAR : 0;

  return 0;
  }

/* Callout from P2P: */
/* Set the state of DTR (Data Terminal Ready). */
static int
p2p_mdmctl(struct p2pcom *p2p, int flag)
  {
  softc_t *sc = IFP2SC(&p2p->p2p_if);

  set_status(sc, flag);

  return 0;
  }

#endif /* P2P */

#if NSPPP

# ifndef PP_FR
#  define PP_FR 0
# endif

/* Callout from SPPP: */
static void
sppp_tls(struct sppp *sppp)
  {
# ifdef __FreeBSD__
  if (!(sppp->pp_mode  & IFF_LINK2) &&
      !(sppp->pp_flags & PP_FR))
# elif defined(__NetBSD__) || defined(__OpenBSD__)
  if (!(sppp->pp_flags & PP_CISCO))
# endif
    sppp->pp_up(sppp);
  }

/* Callout from SPPP: */
static void
sppp_tlf(struct sppp *sppp)
  {
# ifdef __FreeBSD__
  if (!(sppp->pp_mode  & IFF_LINK2) &&
      !(sppp->pp_flags & PP_FR))
# elif defined(__NetBSD__) || defined(__OpenBSD__)
  if (!(sppp->pp_flags & PP_CISCO))
# endif
    sppp->pp_down(sppp);
  }

#endif /* NSPPP */

/* Configure line protocol stuff.
 * Called by attach_card() during module init.
 * Called by core_ioctl()  when lmcconfig writes sc->config.
 * Called by detach_card() during module shutdown.
 */
static void
config_proto(softc_t *sc, struct config *config)
  {
  /* Use line protocol stack instead of RAWIP mode. */
  if ((sc->config.line_pkg == PKG_RAWIP) &&
         (config->line_pkg != PKG_RAWIP))
    {
#if NSPPP
    LMC_BPF_DETACH;
    sppp_attach(sc->ifp);
    LMC_BPF_ATTACH(DLT_PPP, 4);
    sc->sppp->pp_tls = sppp_tls;
    sc->sppp->pp_tlf = sppp_tlf;
    /* Force reconfiguration of SPPP params. */
    sc->config.line_prot = 0;
    sc->config.keep_alive = config->keep_alive ? 0:1;
#elif P2P
    int error = 0;
    sc->p2p->p2p_proto = 0; /* force p2p_attach */
    if ((error = p2p_attach(sc->p2p))) /* calls bpfattach() */
      {
      printf("%s: p2p_attach() failed; error %d\n", NAME_UNIT, error);
      config->line_pkg = PKG_RAWIP;  /* still in RAWIP mode */
      }
    else
      {
      sc->p2p->p2p_mdmctl = p2p_mdmctl; /* set DTR */
      sc->p2p->p2p_getmdm = p2p_getmdm; /* get DCD */
      }
#elif GEN_HDLC
    int error = 0;
    sc->net_dev->mtu = HDLC_MAX_MTU;
    if ((error = hdlc_open(sc->net_dev)))
      {
      printf("%s: hdlc_open() failed; error %d\n", NAME_UNIT, error);
      printf("%s: Try 'sethdlc %s ppp'\n", NAME_UNIT, NAME_UNIT);
      config->line_pkg = PKG_RAWIP;  /* still in RAWIP mode */
      }
#else /* no line protocol stack was configured */
    config->line_pkg = PKG_RAWIP;  /* still in RAWIP mode */
#endif
    }

  /* Bypass line protocol stack and return to RAWIP mode. */
  if ((sc->config.line_pkg != PKG_RAWIP) &&
         (config->line_pkg == PKG_RAWIP))
    {
#if NSPPP
    LMC_BPF_DETACH;
    sppp_flush(sc->ifp);
    sppp_detach(sc->ifp);
    setup_ifnet(sc->ifp);
    LMC_BPF_ATTACH(DLT_RAW, 0);
#elif P2P
    int error = 0;
    if_qflush(&sc->p2p->p2p_isnd);
    if ((error = p2p_detach(sc->p2p)))
      {
      printf("%s: p2p_detach() failed; error %d\n",  NAME_UNIT, error);
      printf("%s: Try 'ifconfig %s down -remove'\n", NAME_UNIT, NAME_UNIT);
      config->line_pkg = PKG_P2P; /* not in RAWIP mode; still attached to P2P */
      }
    else
      {
      setup_ifnet(sc->ifp);
      LMC_BPF_ATTACH(DLT_RAW, 0);
      }
#elif GEN_HDLC
    hdlc_proto_detach(sc->hdlc_dev);
    hdlc_close(sc->net_dev);
    setup_netdev(sc->net_dev);
#endif
    }

#if NSPPP

  if (config->line_pkg != PKG_RAWIP)
    {
    /* Check for change to PPP protocol. */
    if ((sc->config.line_prot != PROT_PPP) &&
           (config->line_prot == PROT_PPP))
      {
      LMC_BPF_DETACH;
# if (defined(__NetBSD__) || defined(__OpenBSD__))
      sc->sppp->pp_flags &= ~PP_CISCO;
# elif defined(__FreeBSD__)
      sc->ifp->if_flags  &= ~IFF_LINK2;
      sc->sppp->pp_flags &= ~PP_FR;
# endif
      LMC_BPF_ATTACH(DLT_PPP, 4);
      sppp_ioctl(sc->ifp, SIOCSIFFLAGS, NULL);
      }

# ifndef DLT_C_HDLC
#  define DLT_C_HDLC DLT_PPP
# endif

    /* Check for change to C_HDLC protocol. */
    if ((sc->config.line_prot != PROT_C_HDLC) &&
           (config->line_prot == PROT_C_HDLC))
      {
      LMC_BPF_DETACH;
# if (defined(__NetBSD__) || defined(__OpenBSD__))
      sc->sppp->pp_flags |=  PP_CISCO;
# elif defined(__FreeBSD__)
      sc->ifp->if_flags  |=  IFF_LINK2;
      sc->sppp->pp_flags &= ~PP_FR;
# endif
      LMC_BPF_ATTACH(DLT_C_HDLC, 4);
      sppp_ioctl(sc->ifp, SIOCSIFFLAGS, NULL);
      }

    /* Check for change to Frame Relay protocol. */
    if ((sc->config.line_prot != PROT_FRM_RLY) &&
           (config->line_prot == PROT_FRM_RLY))
      {
      LMC_BPF_DETACH;
# if (defined(__NetBSD__) || defined(__OpenBSD__))
      sc->sppp->pp_flags &= ~PP_CISCO;
# elif defined(__FreeBSD__)
      sc->ifp->if_flags  &= ~IFF_LINK2;
      sc->sppp->pp_flags |= PP_FR;
# endif
      LMC_BPF_ATTACH(DLT_FRELAY, 4);
      sppp_ioctl(sc->ifp, SIOCSIFFLAGS, NULL);
      }

    /* Check for disabling keep-alives. */
    if ((sc->config.keep_alive != 0) &&
           (config->keep_alive == 0))
      sc->sppp->pp_flags &= ~PP_KEEPALIVE;

    /* Check for enabling keep-alives. */
    if ((sc->config.keep_alive == 0) &&
           (config->keep_alive != 0))
      sc->sppp->pp_flags |=  PP_KEEPALIVE;	
    }

#endif /* NSPPP */

  /* Loop back through the TULIP Ethernet chip; (no CRC). */
  /* Data sheet says stop DMA before changing OPMODE register. */
  /* But that's not as simple as it sounds; works anyway. */
  /* Check for enabling loopback thru Tulip chip. */
  if ((sc->config.loop_back != CFG_LOOP_TULIP) &&
         (config->loop_back == CFG_LOOP_TULIP))
    {
    u_int32_t op_mode = READ_CSR(TLP_OP_MODE);
    op_mode |= TLP_OP_INT_LOOP;
    WRITE_CSR(TLP_OP_MODE, op_mode);
    config->crc_len = CFG_CRC_0;
    }

  /* Check for disabling loopback thru Tulip chip. */
  if ((sc->config.loop_back == CFG_LOOP_TULIP) &&
         (config->loop_back != CFG_LOOP_TULIP))
    {
    u_int32_t op_mode = READ_CSR(TLP_OP_MODE);
    op_mode &= ~TLP_OP_LOOP_MODE;
    WRITE_CSR(TLP_OP_MODE, op_mode);
    config->crc_len = CFG_CRC_16;
    }
  }

/* This is the core ioctl procedure. */
/* It handles IOCTLs from lmcconfig(8). */
/* It must not run when card watchdogs run. */
/* Called from a syscall (user context; no spinlocks). */
/* This procedure can SLEEP. */
static int
core_ioctl(softc_t *sc, u_long cmd, caddr_t data)
  {
  struct iohdr  *iohdr  = (struct iohdr  *) data;
  struct ioctl  *ioctl  = (struct ioctl  *) data;
  struct status *status = (struct status *) data;
  struct config *config = (struct config *) data;
  int error = 0;

  /* All structs start with a string and a cookie. */
  if (((struct iohdr *)data)->cookie != NGM_LMC_COOKIE)
    return EINVAL;

  while (TOP_TRYLOCK == 0)
    {
    sc->status.cntrs.lck_ioctl++;
    SLEEP(10000); /* yield? */
    }
  switch (cmd)
    {
    case LMCIOCGSTAT:
      {
      *status = sc->status;
      iohdr->cookie = NGM_LMC_COOKIE;
      break;
      }
    case LMCIOCGCFG:
      {
      *config = sc->config;
      iohdr->cookie = NGM_LMC_COOKIE;
      break;
      }
    case LMCIOCSCFG:
      {
      if ((error = CHECK_CAP)) break;
      config_proto(sc, config);
      sc->config = *config;
      sc->card->config(sc);
      break;
      }
    case LMCIOCREAD:
      {
      if (ioctl->cmd == IOCTL_RW_PCI)
        {
        if (ioctl->address > 252) { error = EFAULT; break; }
        ioctl->data = READ_PCI_CFG(sc, ioctl->address);
	}
      else if (ioctl->cmd == IOCTL_RW_CSR)
        {
        if (ioctl->address > 15) { error = EFAULT; break; }
        ioctl->data = READ_CSR(ioctl->address*TLP_CSR_STRIDE);
	}
      else if (ioctl->cmd == IOCTL_RW_SROM)
        {
        if (ioctl->address > 63)  { error = EFAULT; break; }
        ioctl->data = read_srom(sc, ioctl->address);
	}
      else if (ioctl->cmd == IOCTL_RW_BIOS)
        ioctl->data = read_bios(sc, ioctl->address);
      else if (ioctl->cmd == IOCTL_RW_MII)
        ioctl->data = read_mii(sc, ioctl->address);
      else if (ioctl->cmd == IOCTL_RW_FRAME)
        ioctl->data = read_framer(sc, ioctl->address);
      else
        error = EINVAL;
      break;
      }
    case LMCIOCWRITE:
      {
      if ((error = CHECK_CAP)) break;
      if (ioctl->cmd == IOCTL_RW_PCI)
        {
        if (ioctl->address > 252) { error = EFAULT; break; }
        WRITE_PCI_CFG(sc, ioctl->address, ioctl->data);
	}
      else if (ioctl->cmd == IOCTL_RW_CSR)
        {
        if (ioctl->address > 15) { error = EFAULT; break; }
        WRITE_CSR(ioctl->address*TLP_CSR_STRIDE, ioctl->data);
	}
      else if (ioctl->cmd == IOCTL_RW_SROM)
        {
        if (ioctl->address > 63)  { error = EFAULT; break; }
        write_srom(sc, ioctl->address, ioctl->data); /* can sleep */
	}
      else if (ioctl->cmd == IOCTL_RW_BIOS)
        {
        if (ioctl->address == 0) erase_bios(sc);
        write_bios(sc, ioctl->address, ioctl->data); /* can sleep */
	}
      else if (ioctl->cmd == IOCTL_RW_MII)
        write_mii(sc, ioctl->address, ioctl->data);
      else if (ioctl->cmd == IOCTL_RW_FRAME)
        write_framer(sc, ioctl->address, ioctl->data);
      else if (ioctl->cmd == IOCTL_WO_SYNTH)
        write_synth(sc, (struct synth *)&ioctl->data);
      else if (ioctl->cmd == IOCTL_WO_DAC)
        {
        write_dac(sc, 0x9002); /* set Vref = 2.048 volts */
        write_dac(sc, ioctl->data & 0xFFF);
	}
      else
        error = EINVAL;
      break;
      }
    case LMCIOCTL:
      {
      if ((error = CHECK_CAP)) break;
      if (ioctl->cmd == IOCTL_XILINX_RESET)
        {
        reset_xilinx(sc);
        sc->card->config(sc);
	}
      else if (ioctl->cmd == IOCTL_XILINX_ROM)
        {
        load_xilinx_from_rom(sc); /* can sleep */
        sc->card->config(sc);
	}
      else if (ioctl->cmd == IOCTL_XILINX_FILE)
        {
        /* load_xilinx_from_file() can sleep. */
        error = load_xilinx_from_file(sc, ioctl->ucode, ioctl->data);
        if (error != 0) load_xilinx_from_rom(sc); /* try the rom */
        sc->card->config(sc);
        set_status(sc, (error==0));  /* XXX */
	}
      else if (ioctl->cmd == IOCTL_RESET_CNTRS)
        {
        memset(&sc->status.cntrs, 0, sizeof(struct event_cntrs));
        microtime(&sc->status.cntrs.reset_time);
        }
      else
        error = sc->card->ioctl(sc, ioctl); /* can sleep */
      break;
      }
    default:
      error = EINVAL;
      break;
    }
  TOP_UNLOCK;

  return error;
  }

/* This is the core watchdog procedure. */
/* It calculates link speed, and calls the card-specific watchdog code. */
/* Calls interrupt() in case one got lost; also kick-starts the device. */
/* ioctl syscalls and card watchdog routines must be interlocked.       */
/* This procedure must not sleep. */
static void
core_watchdog(softc_t *sc)
  {
  /* Read and restart the Tulip timer. */
  u_int32_t tx_speed = READ_CSR(TLP_TIMER);
  WRITE_CSR(TLP_TIMER, 0xFFFF);

  /* Measure MII clock using a timer in the Tulip chip.
   * This timer counts transmitter bits divided by 4096.
   * Since this is called once a second the math is easy.
   * This is only correct when the link is NOT sending pkts.
   * On a fully-loaded link, answer will be HALF actual rate.
   * Clock rate during pkt is HALF clk rate between pkts.
   * Measuring clock rate really measures link utilization!
   */
  sc->status.tx_speed = (0xFFFF - (tx_speed & 0xFFFF)) << 12;

  /* The first status reset time is when the calendar clock is set. */
  if (sc->status.cntrs.reset_time.tv_sec < 1000)
    microtime(&sc->status.cntrs.reset_time);

  /* Update hardware (operational) status. */
  /* Call the card-specific watchdog routines. */
  if (TOP_TRYLOCK != 0)
    {
    sc->status.oper_status = sc->card->watchdog(sc);

    /* Increment a counter which tells user-land */
    /*  observers that SNMP state has been updated. */
    sc->status.ticks++;

    TOP_UNLOCK;
    }
  else
    sc->status.cntrs.lck_watch++;

  /* In case an interrupt gets lost... */
  user_interrupt(sc, 1);
  }

#if IFNET

/* Called from a syscall (user context; no spinlocks). */
static int
lmc_raw_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
  {
  struct ifreq *ifr = (struct ifreq *) data;
  int error = 0;

  switch (cmd)
    {
# if (defined(__FreeBSD__) && defined(DEVICE_POLLING))  /* XXX necessary? */
    case SIOCSIFCAP:
# endif
    case SIOCSIFDSTADDR:
    case SIOCAIFADDR:
    case SIOCSIFFLAGS:
#if 0
    case SIOCADDMULTI:
    case SIOCDELMULTI:
      break;
#endif
    case SIOCSIFADDR:
      ifp->if_flags |= IFF_UP;	/* a Unix tradition */
      break;
    case SIOCSIFMTU:
      ifp->if_mtu = ifr->ifr_mtu;
      break;
    default:
      error = EINVAL;
      break;
    }
  return error;
  }

/* Called from a syscall (user context; no spinlocks). */
static int
lmc_ifnet_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
  {
  softc_t *sc = IFP2SC(ifp);
# ifdef __OpenBSD__
  struct ifreq *ifr = (struct ifreq *) data;
# endif
  int error = 0;

  switch (cmd)
    {
    /* Catch the IOCTLs used by lmcconfig. */
    case LMCIOCGSTAT:
    case LMCIOCGCFG:
    case LMCIOCSCFG:
    case LMCIOCREAD:
    case LMCIOCWRITE:
    case LMCIOCTL:
      error = core_ioctl(sc, cmd, data);
      break;
# ifdef __OpenBSD__
    /* Catch the IOCTLs used by ifconfig. */
    case SIOCSIFMEDIA:
      if ((error = CHECK_CAP)) break;
    case SIOCGIFMEDIA:
      error = ifmedia_ioctl(ifp, ifr, &sc->ifm, cmd);
      break;
    case SIOCSIFTIMESLOT:
      if ((error = CHECK_CAP)) break;
      if (sc->status.card_type == TLP_CSID_T1E1)
        {
        struct config config = sc->config;
        if ((error = copyin(ifr->ifr_data, &config.time_slots,
         sizeof config.time_slots))) break;
        config.iohdr.cookie = NGM_LMC_COOKIE;
        error = core_ioctl(sc, LMCIOCSCFG, (caddr_t)&config);
	}
      else
        error = EINVAL;
      break;
    case SIOCGIFTIMESLOT:
      if (sc->status.card_type == TLP_CSID_T1E1)
        error = copyout(&sc->config.time_slots, ifr->ifr_data,
         sizeof sc->config.time_slots);
      else
        error = EINVAL;
      break;
# endif
    /* Pass the rest to the line protocol. */
    default:
      if (sc->config.line_pkg == PKG_RAWIP)
        error =  lmc_raw_ioctl(ifp, cmd, data);
      else
# if NSPPP
        error = sppp_ioctl(ifp, cmd, data);
# elif P2P
        error =  p2p_ioctl(ifp, cmd, data);
# else
        error = EINVAL;
# endif
      break;
    }

  if (DRIVER_DEBUG && (error!=0))
    printf("%s: lmc_ifnet_ioctl; cmd=0x%08lx error=%d\n",
     NAME_UNIT, cmd, error);

  return error;
  }

/* Called from a syscall (user context; no spinlocks). */
static void
lmc_ifnet_start(struct ifnet *ifp)
  {
  softc_t *sc = IFP2SC(ifp);

  /* Start the transmitter; incoming pkts are NOT processed. */
  user_interrupt(sc, 0);
  }

/* sppp and p2p replace this with their own proc. */
/* RAWIP mode is the only time this is used. */
/* Called from a syscall (user context; no spinlocks). */
static int
lmc_raw_output(struct ifnet *ifp, struct mbuf *m,
 struct sockaddr *dst, struct rtentry *rt)
  {
  softc_t *sc = IFP2SC(ifp);
  int error = 0;

  /* Fail if the link is down. */
  if (sc->status.oper_status != STATUS_UP)
    {
    m_freem(m);
    sc->status.cntrs.odiscards++;
    if (DRIVER_DEBUG)
      printf("%s: lmc_raw_output: tx pkt discarded: link down\n", NAME_UNIT);
    return ENETDOWN;
    }

# if NETGRAPH
  /* Netgraph has priority over the ifnet kernel interface. */
  if (sc->ng_hook != NULL)
    {
    m_freem(m);
    sc->status.cntrs.odiscards++;
    if (DRIVER_DEBUG)
      printf("%s: lmc_raw_output: tx pkt discarded: netgraph active\n",
	NAME_UNIT);
    return EBUSY;
    }
# endif

  /* lmc_raw_output() ENQUEUEs in a syscall or softirq. */
  /* txintr_setup() DEQUEUEs in a hard interrupt. */
  /* Some BSD QUEUE routines are not interrupt-safe. */
  {
  DISABLE_INTR;
# if (__FreeBSD_version >= 503000)
  IFQ_ENQUEUE(&ifp->if_snd, m, error);
# else
  IFQ_ENQUEUE(&ifp->if_snd, m, NULL, error);
# endif
  ENABLE_INTR;
  }

  if (error==0)
    user_interrupt(sc, 0); /* start the transmitter */
  else
    {
    m_freem(m);
    sc->status.cntrs.odiscards++;
    if (DRIVER_DEBUG)
      printf("%s: lmc_raw_output: IFQ_ENQUEUE() failed; error %d\n",
       NAME_UNIT, error);
    }

  return error;
  }

/* Called from a softirq once a second. */
static void
lmc_ifnet_watchdog(struct ifnet *ifp)
  {
  softc_t *sc = IFP2SC(ifp);
  u_int8_t old_oper_status = sc->status.oper_status;
  struct event_cntrs *cntrs = &sc->status.cntrs;

  core_watchdog(sc); /* updates oper_status */

#if NETGRAPH
  if (sc->ng_hook != NULL)
    {
    sc->status.line_pkg  = PKG_NG;
    sc->status.line_prot = 0;
    }
  else
#endif
  if (sc->config.line_pkg == PKG_RAWIP)
    {
    sc->status.line_pkg  = PKG_RAWIP;
    sc->status.line_prot = PROT_IP_HDLC;
    }
  else
    {
# if P2P
    /* Notice change in link status. */
    if ((old_oper_status != sc->status.oper_status) && (sc->p2p->p2p_modem))
      (*sc->p2p->p2p_modem)(sc->p2p, sc->status.oper_status==STATUS_UP);

    /* Notice change in line protocol. */
    sc->status.line_pkg = PKG_P2P;
    switch (sc->ifp->if_type)
      {
      case IFT_PPP:
        sc->status.line_prot = PROT_PPP;
        break;
      case IFT_PTPSERIAL:
        sc->status.line_prot = PROT_C_HDLC;
        break;
      case IFT_FRELAY:
        sc->status.line_prot = PROT_FRM_RLY;
        break;
      default:
        sc->status.line_prot = 0;
        break;
      }

# elif NSPPP
    /* Notice change in link status. */
    if     ((old_oper_status != STATUS_UP) &&
     (sc->status.oper_status == STATUS_UP))  /* link came up */
      sppp_tls(sc->sppp);
    if     ((old_oper_status == STATUS_UP) &&
     (sc->status.oper_status != STATUS_UP))  /* link went down */
      sppp_tlf(sc->sppp);

    /* Notice change in line protocol. */
    sc->status.line_pkg = PKG_SPPP;
#  ifdef __FreeBSD__
    if (sc->sppp->pp_flags & PP_FR)
      sc->status.line_prot = PROT_FRM_RLY;
    else if (sc->ifp->if_flags  & IFF_LINK2)
#  elif (defined(__NetBSD__) || defined(__OpenBSD__))
    if (sc->sppp->pp_flags & PP_CISCO)
#  endif
      sc->status.line_prot = PROT_C_HDLC;
    else
      sc->status.line_prot = PROT_PPP;

# else
    /* Suppress compiler warning. */
    if (old_oper_status == STATUS_UP);
# endif
    }

  /* Copy statistics from sc to ifp. */
  ifp->if_baudrate = sc->status.tx_speed;
  ifp->if_ipackets = cntrs->ipackets;
  ifp->if_opackets = cntrs->opackets;
  ifp->if_ibytes   = cntrs->ibytes;
  ifp->if_obytes   = cntrs->obytes;
  ifp->if_ierrors  = cntrs->ierrors;
  ifp->if_oerrors  = cntrs->oerrors;
  ifp->if_iqdrops  = cntrs->idiscards;

# if ((__FreeBSD_version >= 500000) || defined(__OpenBSD__) || defined(__NetBSD__))
  if (sc->status.oper_status == STATUS_UP)
    ifp->if_link_state = LINK_STATE_UP;
  else
    ifp->if_link_state = LINK_STATE_DOWN;
# endif

  /* Call this procedure again after one second. */
  ifp->if_timer = 1;
  }

# ifdef __OpenBSD__

/* Callback from ifmedia. */
static int
ifmedia_change(struct ifnet *ifp)
  {
  softc_t *sc = IFP2SC(ifp);
  struct config config = sc->config;
  int media = sc->ifm.ifm_media;
  int error;

  /* ifconfig lmc0 media t1 */
  if      (sc->status.card_type == TLP_CSID_T3)
    {
    if      ((media & IFM_TMASK) == IFM_TDM_T3)
      config.format = CFG_FORMAT_T3CPAR;
    else if ((media & IFM_TMASK) == IFM_TDM_T3_M13)
      config.format = CFG_FORMAT_T3M13;
    }
  else if (sc->status.card_type == TLP_CSID_T1E1)
    {
    if      ((media & IFM_TMASK) == IFM_TDM_T1)
      config.format = CFG_FORMAT_T1ESF;
    else if ((media & IFM_TMASK) == IFM_TDM_T1_AMI)
      config.format = CFG_FORMAT_T1SF;
    else if ((media & IFM_TMASK) == IFM_TDM_E1)
      config.format = CFG_FORMAT_E1NONE;
    else if ((media & IFM_TMASK) == IFM_TDM_E1_G704)
      config.format = CFG_FORMAT_E1FASCRC;
    }

  /* ifconfig lmc0 mediaopt loopback */
  if (media & IFM_LOOP)
    config.loop_back = CFG_LOOP_TULIP;
  else
    config.loop_back = CFG_LOOP_NONE;

  /* ifconfig lmc0 mediaopt crc16 */
  if (media & IFM_TDM_HDLC_CRC16)
    config.crc_len = CFG_CRC_16;
  else
    config.crc_len = CFG_CRC_32;

  /* Set ConFiGuration. */
  config.iohdr.cookie = NGM_LMC_COOKIE;
  error = core_ioctl(sc, LMCIOCSCFG, (caddr_t)&config);

  return error;
  }

/* Callback from ifmedia. */
static void
ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
  {
  softc_t *sc = IFP2SC(ifp);

  /* ifconfig wants to know if the hardware link is up. */
  ifmr->ifm_status = IFM_AVALID;
  if (sc->status.oper_status == STATUS_UP)
    ifmr->ifm_status |= IFM_ACTIVE;

  ifmr->ifm_active = sc->ifm.ifm_cur->ifm_media;

  if (sc->config.loop_back != CFG_LOOP_NONE)
    ifmr->ifm_active |= IFM_LOOP;

  if (sc->config.crc_len == CFG_CRC_16)
    ifmr->ifm_active |= IFM_TDM_HDLC_CRC16;
  }

# endif  /* __OpenBSD__ */

static void
setup_ifnet(struct ifnet *ifp)
  {
  softc_t *sc = ifp->if_softc;

  /* Initialize the generic network interface. */
  /* Note similarity to linux's setup_netdev(). */
  ifp->if_flags    = IFF_POINTOPOINT;
  ifp->if_flags   |= IFF_RUNNING;
  ifp->if_ioctl    = lmc_ifnet_ioctl;
  ifp->if_start    = lmc_ifnet_start;	/* sppp changes this */
  ifp->if_output   = lmc_raw_output;	/* sppp & p2p change this */
  ifp->if_input    = lmc_raw_input;
  ifp->if_watchdog = lmc_ifnet_watchdog;
  ifp->if_timer    = 1;
  ifp->if_mtu      = MAX_DESC_LEN;	/* sppp & p2p change this */
  ifp->if_type     = IFT_PTPSERIAL;	/* p2p changes this */

# if (defined(__FreeBSD__) && defined(DEVICE_POLLING))
  ifp->if_capabilities |= IFCAP_POLLING;
# if (__FreeBSD_version < 500000)
  ifp->if_capenable    |= IFCAP_POLLING;
# endif
# endif

  /* Every OS does it differently! */
# if (defined(__FreeBSD__) && (__FreeBSD_version < 502000))
  (const char *)ifp->if_name = device_get_name(sc->dev);
  ifp->if_unit  = device_get_unit(sc->dev);
# elif (__FreeBSD_version >= 502000)
  if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
# elif defined(__NetBSD__)
  strcpy(ifp->if_xname, sc->dev.dv_xname);
# elif __OpenBSD__
  bcopy(sc->dev.dv_xname, ifp->if_xname, IFNAMSIZ);
# elif defined(__bsdi__)
  ifp->if_name  = sc->dev.dv_cfdata->cf_driver->cd_name;
  ifp->if_unit  = sc->dev.dv_unit;
# endif
  }

static int
lmc_ifnet_attach(softc_t *sc)
  {
# if (__FreeBSD_version >= 600000)
  sc->ifp  = if_alloc(NSPPP ? IFT_PPP : IFT_OTHER);
  if (sc->ifp == NULL) return ENOMEM;
# endif
# if NSPPP
#  if (__FreeBSD_version >= 600000)
  sc->sppp = sc->ifp->if_l2com;
#  else
  sc->ifp  = &sc->spppcom.pp_if;
  sc->sppp = &sc->spppcom;
#  endif
# elif P2P
  sc->ifp  = &sc->p2pcom.p2p_if;
  sc->p2p  = &sc->p2pcom;
# elif (__FreeBSD_version < 600000)
  sc->ifp  = &sc->ifnet;
# endif

  /* Initialize the network interface struct. */
  sc->ifp->if_softc = sc;
  setup_ifnet(sc->ifp);

  /* ALTQ output queue initialization. */
  IFQ_SET_MAXLEN(&sc->ifp->if_snd, SNDQ_MAXLEN);
  IFQ_SET_READY(&sc->ifp->if_snd);

  /* Attach to the ifnet kernel interface. */
  if_attach(sc->ifp);

# if ((defined(__NetBSD__) && __NetBSD_Version__ >= 106000000) || \
     (defined(__OpenBSD__) && OpenBSD >= 200211))
  if_alloc_sadl(sc->ifp);
# endif

  /* Attach Berkeley Packet Filter. */
  LMC_BPF_ATTACH(DLT_RAW, 0);

# ifdef __OpenBSD__
  /* Initialize ifmedia mechanism. */
  ifmedia_init(&sc->ifm, IFM_OMASK | IFM_GMASK | IFM_IMASK,
   ifmedia_change, ifmedia_status);
  if       (sc->status.card_type == TLP_CSID_T3)
    {
    ifmedia_add(&sc->ifm, IFM_TDM | IFM_TDM_T3, 0, NULL);
    ifmedia_add(&sc->ifm, IFM_TDM | IFM_TDM_T3_M13, 0, NULL);
    ifmedia_set(&sc->ifm, IFM_TDM | IFM_TDM_T3);
    }
  else if  (sc->status.card_type == TLP_CSID_T1E1)
    {
    ifmedia_add(&sc->ifm, IFM_TDM | IFM_TDM_T1, 0, NULL);
    ifmedia_add(&sc->ifm, IFM_TDM | IFM_TDM_T1_AMI, 0, NULL);
    ifmedia_add(&sc->ifm, IFM_TDM | IFM_TDM_E1, 0, NULL);
    ifmedia_add(&sc->ifm, IFM_TDM | IFM_TDM_E1_G704, 0, NULL);
    ifmedia_set(&sc->ifm, IFM_TDM | IFM_TDM_T1);
    }
  else if ((sc->status.card_type == TLP_CSID_HSSI) ||
           (sc->status.card_type == TLP_CSID_SSI))
    {
    ifmedia_add(&sc->ifm, IFM_TDM | IFM_NONE, 0, NULL);
    ifmedia_set(&sc->ifm, IFM_TDM | IFM_NONE);
    }
# endif  /* __OpenBSD__ */

  return 0;
  }

static void
lmc_ifnet_detach(softc_t *sc)
  {
# ifdef __OpenBSD__
  ifmedia_delete_instance(&sc->ifm, IFM_INST_ANY);
# endif

# if (defined(__FreeBSD__) && defined(DEVICE_POLLING))
  if (sc->ifp->if_capenable & IFCAP_POLLING)
    ether_poll_deregister(sc->ifp);
# endif

  /* Detach Berkeley Packet Filter. */
  LMC_BPF_DETACH;

# if ((defined(__NetBSD__) && __NetBSD_Version__ >= 106000000) || \
     (defined(__OpenBSD__) && OpenBSD >= 200211))
  if_free_sadl(sc->ifp);
# endif

  /* Detach from the ifnet kernel interface. */
  if_detach(sc->ifp);

# if (__FreeBSD_version >= 600000)
  if_free_type(sc->ifp, NSPPP ? IFT_PPP : IFT_OTHER);
# endif
  }

#endif  /* IFNET */

#if NETGRAPH

/* Netgraph changed significantly between FreeBSD-4 and -5. */
/* These are backward compatibility hacks for FreeBSD-4. */
# if (__FreeBSD_version >= 500000)
/* These next two macros should be added to netgraph */
#  define NG_TYPE_REF(type) atomic_add_int(&(type)->refs, 1)
#  define NG_TYPE_UNREF(type)	\
do {				\
  if ((type)->refs == 1)	\
    ng_rmtype(type);		\
  else				\
    atomic_subtract_int(&(type)->refs, 1); \
   } while (0)
# else /* FreeBSD-4 */
#  define NGI_GET_MSG(item, msg)	/* nothing */
#  define NG_HOOK_FORCE_QUEUE(hook)	/* nothing */
#  define NG_TYPE_REF(type) atomic_add_int(&(type)->refs, 1)
#  define NG_TYPE_UNREF(type)	\
do {				\
  if ((type)->refs == 1)	\
    LIST_REMOVE(type, types);	\
  else				\
    atomic_subtract_int(&(type)->refs, 1); \
   } while (0)
# endif

/* It is an error to construct new copies of this Netgraph node. */
/* All instances are constructed by ng_attach and are persistent. */
# if (__FreeBSD_version >= 500000)
static int ng_constructor(node_p  node) { return EINVAL; }
# else /* FreeBSD-4 */
static int ng_constructor(node_p *node) { return EINVAL; }
# endif

/* Incoming Netgraph control message. */
# if (__FreeBSD_version >= 500000)
static int
ng_rcvmsg(node_p node, item_p item, hook_p lasthook)
  {
  struct ng_mesg *msg;
# else /* FreeBSD-4 */
static int
ng_rcvmsg(node_p node, struct ng_mesg *msg,
 const char *retaddr,  struct ng_mesg **rptr)
  {
# endif
  struct ng_mesg *resp = NULL;
  softc_t *sc = NG_NODE_PRIVATE(node);
  int error = 0;

  NGI_GET_MSG(item, msg);
  if (msg->header.typecookie == NGM_LMC_COOKIE)
    {
    switch (msg->header.cmd)
      {
      case LMCIOCGSTAT:
      case LMCIOCGCFG:
      case LMCIOCSCFG:
      case LMCIOCREAD:
      case LMCIOCWRITE:
      case LMCIOCTL:
        {
        /* Call the core ioctl procedure. */
        error = core_ioctl(sc, msg->header.cmd, msg->data);
        if ((msg->header.cmd & IOC_OUT) != 0)
          { /* synchronous response */
          NG_MKRESPONSE(resp, msg, sizeof(struct ng_mesg) +
           IOCPARM_LEN(msg->header.cmd), M_NOWAIT);
          if (resp == NULL)
            error = ENOMEM;
          else
            memcpy(resp->data, msg->data, IOCPARM_LEN(msg->header.cmd));
          }
        break;
        }
      default:
        error = EINVAL;
        break;
      }
    }
  else if ((msg->header.typecookie == NGM_GENERIC_COOKIE) &&
           (msg->header.cmd == NGM_TEXT_STATUS))
    {  /* synchronous response */
    NG_MKRESPONSE(resp, msg, sizeof(struct ng_mesg) +
     NG_TEXTRESPONSE, M_NOWAIT);
    if (resp == NULL)
      error = ENOMEM;
    else
      {
      char *s = resp->data;
      sprintf(s, "Card type = <%s>\n"
       "This driver considers the link to be %s.\n"
       "Use lmcconfig to configure this interface.\n",
       sc->dev_desc, (sc->status.oper_status==STATUS_UP) ? "UP" : "DOWN");
      resp->header.arglen = strlen(s) +1;
      }
    }
  else
/* Netgraph should be able to read and write these
 *  parameters with text-format control messages:
 *  SSI	     HSSI     T1E1     T3
 *  crc	     crc      crc      crc      
 *  loop     loop     loop     loop
 *           clksrc   clksrc
 *  dte	     dte      format   format
 *  synth    synth    cablen   cablen
 *  cable             timeslot scram
 *                    gain
 *                    pulse
 *                    lbo
 * Someday I'll implement this...
 */
    error = EINVAL;

  /* Handle synchronous response. */
# if (__FreeBSD_version >= 500000)
  NG_RESPOND_MSG(error, node, item, resp);
  NG_FREE_MSG(msg);
# else /* FreeBSD-4 */
  if (rptr != NULL)
    *rptr = resp;
  else if (resp != NULL)
    free(resp, M_NETGRAPH);
  free(msg, M_NETGRAPH);
# endif

  return error;
  }

/* This is a persistent netgraph node. */
static int
ng_shutdown(node_p node)
  {
# if (__FreeBSD_version >= 500000)
  /* unless told to really die, bounce back to life */
  if ((node->nd_flags & NG_REALLY_DIE)==0)
    node->nd_flags &= ~NG_INVALID; /* bounce back to life */
# else /* FreeBSD-4 */
  ng_cutlinks(node);
  node->flags &= ~NG_INVALID;  /* bounce back to life */
# endif

  return 0;
  }

/* ng_disconnect is the opposite of this procedure. */
static int
ng_newhook(node_p node, hook_p hook, const char *name)
  {
  softc_t *sc = NG_NODE_PRIVATE(node);

  /* Hook name must be 'rawdata'. */
  if (strncmp(name, "rawdata", 7) != 0)	return EINVAL;

  /* Is our hook connected? */
  if (sc->ng_hook != NULL) return EBUSY;

  /* Accept the hook. */
  sc->ng_hook = hook;

  return 0;
  }

/* Both ends have accepted their hooks and the links have been made. */
/* This is the last chance to reject the connection request. */
static int
ng_connect(hook_p hook)
  {
  /* Probably not at splnet, force outward queueing. (huh?) */
  NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));
  return 0; /* always accept */
  }

/* Receive data in mbufs from another Netgraph node. */
/* Transmit an mbuf-chain on the communication link. */
/* This procedure is very similar to lmc_raw_output(). */
/* Called from a syscall (user context; no spinlocks). */
# if (__FreeBSD_version >= 500000)
static int
ng_rcvdata(hook_p hook, item_p item)
  {
  softc_t *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
  int error = 0;
  struct mbuf *m;
  meta_p meta = NULL;

  NGI_GET_M(item, m);
  NGI_GET_META(item, meta);
  NG_FREE_ITEM(item);
# else /* FreeBSD-4 */
static int
ng_rcvdata(hook_p hook, struct mbuf *m, meta_p meta)
  {
  softc_t *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
  int error = 0;
# endif

  /* This macro must not store into meta! */
  NG_FREE_META(meta);

  /* Fail if the link is down. */
  if (sc->status.oper_status  != STATUS_UP)
    {
    m_freem(m);
    sc->status.cntrs.odiscards++;
    if (DRIVER_DEBUG)
      printf("%s: ng_rcvdata: tx pkt discarded: link down\n", NAME_UNIT);
    return ENETDOWN;
    }

  /* ng_rcvdata() ENQUEUEs in a syscall or softirq. */
  /* txintr_setup() DEQUEUEs in a hard interrupt. */
  /* Some BSD QUEUE routines are not interrupt-safe. */
  {
  DISABLE_INTR;
# if (__FreeBSD_version >= 503000)
  if (meta==NULL)
    IFQ_ENQUEUE(&sc->ng_sndq, m, error);
  else
    IFQ_ENQUEUE(&sc->ng_fastq, m, error);
# else
  if (meta==NULL)
    IFQ_ENQUEUE(&sc->ng_sndq, m, NULL, error);
  else
    IFQ_ENQUEUE(&sc->ng_fastq, m, NULL, error);
# endif
  ENABLE_INTR;
  }

  if (error==0)
    user_interrupt(sc, 0); /* start the transmitter */
  else
    {
    m_freem(m);
    sc->status.cntrs.odiscards++;
    if (DRIVER_DEBUG)
      printf("%s: ng_rcvdata: IFQ_ENQUEUE() failed; error %d\n",
       NAME_UNIT, error);
    }

  return error;
  }

/* ng_newhook is the opposite of this procedure, not */
/*  ng_connect, as you might expect from the names. */
static int
ng_disconnect(hook_p hook)
  {
  softc_t *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));

  /* Disconnect the hook. */
  sc->ng_hook = NULL;

  return 0;
  }

static
struct ng_type ng_type =
  {
  .version	= NG_ABI_VERSION,
  .name		= NG_LMC_NODE_TYPE,
  .mod_event	= NULL,
  .constructor	= ng_constructor,
  .rcvmsg	= ng_rcvmsg,
# if (__FreeBSD_version >=503000)
  .close	= NULL,
# endif
  .shutdown	= ng_shutdown,
  .newhook	= ng_newhook,
  .findhook	= NULL,
  .connect	= ng_connect,
  .rcvdata	= ng_rcvdata,
# if (defined(__FreeBSD__) && (__FreeBSD_version < 500000))
  .rcvdataq	= ng_rcvdata,
# endif
  .disconnect	= ng_disconnect,
  };

# if (IFNET == 0)
/* Called from a softirq once a second. */
static void
ng_watchdog(void *arg)
  {
  softc_t *sc = arg;

  /* Call the core watchdog procedure. */
  core_watchdog(sc);

  /* Set line protocol and package status. */
  sc->status.line_pkg  = PKG_NG;
  sc->status.line_prot = 0;

  /* Call this procedure again after one second. */
  callout_reset(&sc->ng_callout, hz, ng_watchdog, sc);
  }
# endif

/* Attach to the Netgraph kernel interface (/sys/netgraph).
 * It is called once for each physical card during device attach.
 * This is effectively ng_constructor.
 */
static int
ng_attach(softc_t *sc)
  {
  int error;

  /* If this node type is not known to Netgraph then register it. */
  if (ng_type.refs == 0) /* or: if (ng_findtype(&ng_type) == NULL) */
    {
    if ((error = ng_newtype(&ng_type)))
      {
      printf("%s: ng_newtype() failed; error %d\n", NAME_UNIT, error);
      return error;
      }
    }
  else
    NG_TYPE_REF(&ng_type);

  /* Call the superclass node constructor. */
  if ((error = ng_make_node_common(&ng_type, &sc->ng_node)))
    {
    NG_TYPE_UNREF(&ng_type);
    printf("%s: ng_make_node_common() failed; error %d\n", NAME_UNIT, error);
    return error;
    }

  /* Associate a name with this netgraph node. */
  if ((error = ng_name_node(sc->ng_node, NAME_UNIT)))
    {
    NG_NODE_UNREF(sc->ng_node);
    NG_TYPE_UNREF(&ng_type);
    printf("%s: ng_name_node() failed; error %d\n", NAME_UNIT, error);
    return error;
    }

# if (__FreeBSD_version >= 500000)
  /* Initialize the send queue mutexes. */
  mtx_init(&sc->ng_sndq.ifq_mtx,  NAME_UNIT, "sndq",  MTX_DEF);
  mtx_init(&sc->ng_fastq.ifq_mtx, NAME_UNIT, "fastq", MTX_DEF);
# endif

  /* Put a backpointer to the softc in the netgraph node. */
  NG_NODE_SET_PRIVATE(sc->ng_node, sc);

  /* ALTQ output queue initialization. */
  IFQ_SET_MAXLEN(&sc->ng_fastq, SNDQ_MAXLEN);
  IFQ_SET_READY(&sc->ng_fastq);
  IFQ_SET_MAXLEN(&sc->ng_sndq,  SNDQ_MAXLEN);
  IFQ_SET_READY(&sc->ng_sndq);

  /* If ifnet is present, it will call watchdog. */
  /* Otherwise, arrange to call watchdog here. */
# if (IFNET == 0)
  /* Arrange to call ng_watchdog() once a second. */
#  if (__FreeBSD_version >= 500000)
  callout_init(&sc->ng_callout, 0);
#  else  /* FreeBSD-4 */
  callout_init(&sc->ng_callout);
#  endif
  callout_reset(&sc->ng_callout, hz, ng_watchdog, sc);
# endif

  return 0;
  }

static void
ng_detach(softc_t *sc)
  {
# if (IFNET == 0)
  callout_stop(&sc->ng_callout);
# endif
# if (__FreeBSD_version >= 500000)
  mtx_destroy(&sc->ng_sndq.ifq_mtx);
  mtx_destroy(&sc->ng_fastq.ifq_mtx);
  ng_rmnode_self(sc->ng_node); /* free hook */
  NG_NODE_UNREF(sc->ng_node);  /* free node */
  NG_TYPE_UNREF(&ng_type);
# else /* FreeBSD-4 */
  ng_unname(sc->ng_node);      /* free name */
  ng_cutlinks(sc->ng_node);    /* free hook */
  NG_NODE_UNREF(sc->ng_node);  /* free node */
  NG_TYPE_UNREF(&ng_type);
# endif
  }

#endif /* NETGRAPH */

/* The next few procedures initialize the card. */

/* Returns 0 on success; error code on failure. */
static int
startup_card(softc_t *sc)
  {
  int num_rx_descs, error = 0;
  u_int32_t tlp_bus_pbl, tlp_bus_cal, tlp_op_tr;
  u_int32_t tlp_cfdd, tlp_cfcs;
  u_int32_t tlp_cflt, tlp_csid, tlp_cfit;

  /* Make sure the COMMAND bits are reasonable. */
  tlp_cfcs = READ_PCI_CFG(sc, TLP_CFCS);
  tlp_cfcs &= ~TLP_CFCS_MWI_ENABLE;
  tlp_cfcs |=  TLP_CFCS_BUS_MASTER;
  tlp_cfcs |=  TLP_CFCS_MEM_ENABLE;
  tlp_cfcs |=  TLP_CFCS_IO_ENABLE;
  tlp_cfcs |=  TLP_CFCS_PAR_ERROR;
  tlp_cfcs |=  TLP_CFCS_SYS_ERROR;
  WRITE_PCI_CFG(sc, TLP_CFCS, tlp_cfcs);

  /* Set the LATENCY TIMER to the recommended value, */
  /*  and make sure the CACHE LINE SIZE is reasonable. */
  tlp_cfit = READ_PCI_CFG(sc, TLP_CFIT);
  tlp_cflt = READ_PCI_CFG(sc, TLP_CFLT);
  tlp_cflt &= ~TLP_CFLT_LATENCY;
  tlp_cflt |= (tlp_cfit & TLP_CFIT_MAX_LAT)>>16;
  /* "prgmbl burst length" and "cache alignment" used below. */
  switch(tlp_cflt & TLP_CFLT_CACHE)
    {
    case 8: /* 8 bytes per cache line */
      { tlp_bus_pbl = 32; tlp_bus_cal = 1; break; }
    case 16:
      { tlp_bus_pbl = 32; tlp_bus_cal = 2; break; }
    case 32:
      { tlp_bus_pbl = 32; tlp_bus_cal = 3; break; }
    default:
      {
      tlp_bus_pbl = 32; tlp_bus_cal = 1;
      tlp_cflt &= ~TLP_CFLT_CACHE;
      tlp_cflt |= 8;
      break;
      }
    }
  WRITE_PCI_CFG(sc, TLP_CFLT, tlp_cflt);

  /* Make sure SNOOZE and SLEEP modes are disabled. */
  tlp_cfdd = READ_PCI_CFG(sc, TLP_CFDD);
  tlp_cfdd &= ~TLP_CFDD_SLEEP;
  tlp_cfdd &= ~TLP_CFDD_SNOOZE;
  WRITE_PCI_CFG(sc, TLP_CFDD, tlp_cfdd);
  DELAY(11*1000); /* Tulip wakes up in 10 ms max */

  /* Software Reset the Tulip chip; stops DMA and Interrupts. */
  /* This does not change the PCI config regs just set above. */
  WRITE_CSR(TLP_BUS_MODE, TLP_BUS_RESET); /* self-clearing */
  DELAY(5);  /* Tulip is dead for 50 PCI cycles after reset. */

  /* Reset the Xilinx Field Programmable Gate Array. */
  reset_xilinx(sc); /* side effect: turns on all four LEDs */

  /* Configure card-specific stuff (framers, line interfaces, etc.). */
  sc->card->config(sc);

  /* Initializing cards can glitch clocks and upset fifos. */
  /* Reset the FIFOs between the Tulip and Xilinx chips. */
  set_mii16_bits(sc, MII16_FIFO);
  clr_mii16_bits(sc, MII16_FIFO);

  /* Initialize the PCI busmode register. */
  /* The PCI bus cycle type "Memory Write and Invalidate" does NOT */
  /*  work cleanly in any version of the 21140A, so don't enable it! */
  WRITE_CSR(TLP_BUS_MODE,
        (tlp_bus_cal ? TLP_BUS_READ_LINE : 0) |
        (tlp_bus_cal ? TLP_BUS_READ_MULT : 0) |
        (tlp_bus_pbl<<TLP_BUS_PBL_SHIFT) |
        (tlp_bus_cal<<TLP_BUS_CAL_SHIFT) |
   ((BYTE_ORDER == BIG_ENDIAN) ? TLP_BUS_DESC_BIGEND : 0) |
   ((BYTE_ORDER == BIG_ENDIAN) ? TLP_BUS_DATA_BIGEND : 0) |
                TLP_BUS_DSL_VAL |
                TLP_BUS_ARB);

  /* Pick number of RX descriptors and TX fifo threshold. */
  /* tx_threshold in bytes: 0=128, 1=256, 2=512, 3=1024 */
  tlp_csid = READ_PCI_CFG(sc, TLP_CSID);
  switch(tlp_csid)
    {
    case TLP_CSID_HSSI:		/* 52 Mb/s */
    case TLP_CSID_HSSIc:	/* 52 Mb/s */
    case TLP_CSID_T3:		/* 45 Mb/s */
      { num_rx_descs = 48; tlp_op_tr = 2; break; }
    case TLP_CSID_SSI:		/* 10 Mb/s */
      { num_rx_descs = 32; tlp_op_tr = 1; break; }
    case TLP_CSID_T1E1:		/*  2 Mb/s */
      { num_rx_descs = 16; tlp_op_tr = 0; break; }
    default:
      { num_rx_descs = 16; tlp_op_tr = 0; break; }
    }

  /* Create DMA descriptors and initialize list head registers. */
  if ((error = create_ring(sc, &sc->txring, NUM_TX_DESCS))) return error;
  WRITE_CSR(TLP_TX_LIST, sc->txring.dma_addr);
  if ((error = create_ring(sc, &sc->rxring, num_rx_descs))) return error;
  WRITE_CSR(TLP_RX_LIST, sc->rxring.dma_addr);

  /* Initialize the operating mode register. */
  WRITE_CSR(TLP_OP_MODE, TLP_OP_INIT | (tlp_op_tr<<TLP_OP_TR_SHIFT));

  /* Read the missed frame register (result ignored) to zero it. */
  error = READ_CSR( TLP_MISSED); /* error is used as a bit-dump */

  /* Disable rx watchdog and tx jabber features. */
  WRITE_CSR(TLP_WDOG, TLP_WDOG_INIT);

  /* Enable card interrupts. */
  WRITE_CSR(TLP_INT_ENBL, TLP_INT_TXRX);

  return 0;
  }

/* Stop DMA and Interrupts; free descriptors and buffers. */
static void
shutdown_card(void *arg)
  {
  softc_t *sc = arg;

  /* Leave the LEDs in the state they were in after power-on. */
  led_on(sc, MII16_LED_ALL);

  /* Software reset the Tulip chip; stops DMA and Interrupts */
  WRITE_CSR(TLP_BUS_MODE, TLP_BUS_RESET); /* self-clearing */
  DELAY(5);  /* Tulip is dead for 50 PCI cycles after reset. */

  /* Disconnect from the PCI bus except for config cycles. */
  /* Hmmm; Linux syslogs a warning that IO and MEM are disabled. */
  WRITE_PCI_CFG(sc, TLP_CFCS, TLP_CFCS_MEM_ENABLE | TLP_CFCS_IO_ENABLE);

  /* Free the DMA descriptor rings. */
  destroy_ring(sc, &sc->txring);
  destroy_ring(sc, &sc->rxring);
  }

/* Start the card and attach a kernel interface and line protocol. */
static int
attach_card(softc_t *sc, const char *intrstr)
  {
  struct config config;
  u_int32_t tlp_cfrv;
  u_int16_t mii3;
  u_int8_t *ieee;
  int i, error = 0;

  /* Start the card. */
  if ((error = startup_card(sc))) return error;

  /* Attach a kernel interface. */
#if NETGRAPH
  if ((error = ng_attach(sc))) return error;
  sc->flags |= FLAG_NETGRAPH;
#endif
#if IFNET
  if ((error = lmc_ifnet_attach(sc))) return error;
  sc->flags |= FLAG_IFNET;
#endif

  /* Attach a line protocol stack. */
  sc->config.line_pkg = PKG_RAWIP;
  config = sc->config;	/* get current config */
  config.line_pkg = 0;	/* select external stack */
  config.line_prot = PROT_C_HDLC;
  config.keep_alive = 1;
  config_proto(sc, &config); /* reconfigure */
  sc->config = config;	/* save new configuration */

  /* Print interesting hardware-related things. */
  mii3 = read_mii(sc, 3);
  tlp_cfrv = READ_PCI_CFG(sc, TLP_CFRV);
  printf("%s: PCI rev %d.%d, MII rev %d.%d", NAME_UNIT,
   (tlp_cfrv>>4) & 0xF, tlp_cfrv & 0xF, (mii3>>4) & 0xF, mii3 & 0xF);
  ieee = (u_int8_t *)sc->status.ieee;
  for (i=0; i<3; i++) sc->status.ieee[i] = read_srom(sc, 10+i);
  printf(", IEEE addr %02x:%02x:%02x:%02x:%02x:%02x",
   ieee[0], ieee[1], ieee[2], ieee[3], ieee[4], ieee[5]);
  sc->card->ident(sc);
  printf(" %s\n", intrstr);

  /* Print interesting software-related things. */
  printf("%s: Driver rev %d.%d.%d", NAME_UNIT,
   DRIVER_MAJOR_VERSION, DRIVER_MINOR_VERSION, DRIVER_SUB_VERSION);
  printf(", Options %s%s%s%s%s%s%s%s%s\n",
   NETGRAPH ? "NETGRAPH " : "", GEN_HDLC ? "GEN_HDLC " : "",
   NSPPP ? "SPPP " : "", P2P ? "P2P " : "",
   ALTQ_PRESENT ? "ALTQ " : "", NBPFILTER ? "BPF " : "",
   DEV_POLL ? "POLL " : "", IOREF_CSR ? "IO_CSR " : "MEM_CSR ",
   (BYTE_ORDER == BIG_ENDIAN) ? "BIG_END " : "LITTLE_END ");

  /* Make the local hardware ready. */
  set_status(sc, 1);

  return 0;
  }

/* Detach from the kernel in all ways. */
static void
detach_card(softc_t *sc)
  {
  struct config config;

  /* Make the local hardware NOT ready. */
  set_status(sc, 0);

  /* Detach external line protocol stack. */
  if (sc->config.line_pkg != PKG_RAWIP)
    {
    config = sc->config;
    config.line_pkg = PKG_RAWIP;
    config_proto(sc, &config);
    sc->config = config;
    }

  /* Detach kernel interfaces. */
#if NETGRAPH
  if (sc->flags & FLAG_NETGRAPH)
    {
    IFQ_PURGE(&sc->ng_fastq);
    IFQ_PURGE(&sc->ng_sndq);
    ng_detach(sc);
    sc->flags &= ~FLAG_NETGRAPH;
    }
#endif
#if IFNET
  if (sc->flags & FLAG_IFNET)
    {
    IFQ_PURGE(&sc->ifp->if_snd);
    lmc_ifnet_detach(sc);
    sc->flags &= ~FLAG_IFNET;
    }
#endif

  /* Reset the Tulip chip; stops DMA and Interrupts. */
  shutdown_card(sc);
  }

/* This is the I/O configuration interface for FreeBSD */

#ifdef __FreeBSD__

static int
fbsd_probe(device_t dev)
  {
  u_int32_t cfid = pci_read_config(dev, TLP_CFID, 4);
  u_int32_t csid = pci_read_config(dev, TLP_CSID, 4);

  /* Looking for a DEC 21140A chip on any Lan Media Corp card. */
  if (cfid != TLP_CFID_TULIP) return ENXIO;
  switch (csid)
    {
    case TLP_CSID_HSSI:
    case TLP_CSID_HSSIc:
      device_set_desc(dev, HSSI_DESC);
      break;
    case TLP_CSID_T3:
      device_set_desc(dev,   T3_DESC);
      break;
    case TLP_CSID_SSI:
      device_set_desc(dev,  SSI_DESC);
      break;
    case TLP_CSID_T1E1:
      device_set_desc(dev, T1E1_DESC);
      break;
    default:
      return ENXIO;
    }
  return 0;
  }

static int
fbsd_detach(device_t dev)
  {
  softc_t *sc = device_get_softc(dev);

  /* Stop the card and detach from the kernel. */
  detach_card(sc);

  /* Release resources. */
  if (sc->irq_cookie != NULL)
    {
    bus_teardown_intr(dev, sc->irq_res, sc->irq_cookie);
    sc->irq_cookie = NULL;
    }
  if (sc->irq_res != NULL)
    {
    bus_release_resource(dev, SYS_RES_IRQ, sc->irq_res_id, sc->irq_res);
    sc->irq_res = NULL;
    }
  if (sc->csr_res != NULL)
    {
    bus_release_resource(dev, sc->csr_res_type, sc->csr_res_id, sc->csr_res);
    sc->csr_res = NULL;
    }

# if (__FreeBSD_version >= 500000)
  mtx_destroy(&sc->top_mtx);
  mtx_destroy(&sc->bottom_mtx);
# endif
  return 0; /* no error */
  }

static void
fbsd_shutdown(device_t dev)
  {
  shutdown_card(device_get_softc(dev));
  }

static int
fbsd_attach(device_t dev)
  {
  softc_t *sc = device_get_softc(dev);
  int error;

  /* READ/WRITE_PCI_CFG need this. */
  sc->dev = dev;

  /* What kind of card are we driving? */
  switch (READ_PCI_CFG(sc, TLP_CSID))
    {
    case TLP_CSID_HSSI:
    case TLP_CSID_HSSIc:
      sc->card = &hssi_card;
      break;
    case TLP_CSID_T3:
      sc->card =   &t3_card;
      break;
    case TLP_CSID_SSI:
      sc->card =  &ssi_card;
      break;
    case TLP_CSID_T1E1:
      sc->card =   &t1_card;
      break;
    default:
      return ENXIO;
    }
  sc->dev_desc = device_get_desc(dev);

  /* Allocate PCI memory or IO resources to access the Tulip chip CSRs. */
# if IOREF_CSR
  sc->csr_res_id   = TLP_CBIO;
  sc->csr_res_type = SYS_RES_IOPORT;
# else
  sc->csr_res_id   = TLP_CBMA;
  sc->csr_res_type = SYS_RES_MEMORY;
# endif
  sc->csr_res = bus_alloc_resource(dev, sc->csr_res_type, &sc->csr_res_id,
   0, ~0, 1, RF_ACTIVE);
  if (sc->csr_res == NULL)
    {
    printf("%s: bus_alloc_resource(csr) failed.\n", NAME_UNIT);
    return ENXIO;
    }
  sc->csr_tag    = rman_get_bustag(sc->csr_res);
  sc->csr_handle = rman_get_bushandle(sc->csr_res); 

  /* Allocate PCI interrupt resources for the card. */
  sc->irq_res_id = 0;
  sc->irq_res = bus_alloc_resource(dev, SYS_RES_IRQ, &sc->irq_res_id,
   0, ~0, 1, RF_ACTIVE | RF_SHAREABLE);
  if (sc->irq_res == NULL)
    {
    printf("%s: bus_alloc_resource(irq) failed.\n", NAME_UNIT);
    fbsd_detach(dev);
    return ENXIO;
    }
  if ((error = bus_setup_intr(dev, sc->irq_res, INTR_TYPE_NET | INTR_MPSAFE,
   NULL, bsd_interrupt, sc, &sc->irq_cookie)))
    {
    printf("%s: bus_setup_intr() failed; error %d\n", NAME_UNIT, error);
    fbsd_detach(dev);
    return error;
    }

# if (__FreeBSD_version >= 500000)
  /* Initialize the top-half and bottom-half locks. */
  mtx_init(&sc->top_mtx,    NAME_UNIT, "top half lock",    MTX_DEF);
  mtx_init(&sc->bottom_mtx, NAME_UNIT, "bottom half lock", MTX_DEF);
# endif

  /* Start the card and attach a kernel interface and line protocol. */
  if ((error = attach_card(sc, ""))) detach_card(sc);
  return error;
  }

static device_method_t methods[] =
  {
  DEVMETHOD(device_probe,    fbsd_probe),
  DEVMETHOD(device_attach,   fbsd_attach),
  DEVMETHOD(device_detach,   fbsd_detach),
  DEVMETHOD(device_shutdown, fbsd_shutdown),
  /* This driver does not suspend and resume. */
  { 0, 0 }
  };

static driver_t driver =
  {
  .name    = DEVICE_NAME,
  .methods = methods,
# if (__FreeBSD_version >= 500000)
  .size    = sizeof(softc_t),
# else /* FreeBSD-4 */
  .softc   = sizeof(softc_t),
# endif
  };

static devclass_t devclass;

DRIVER_MODULE(if_lmc, pci, driver, devclass, 0, 0);
MODULE_VERSION(if_lmc, 2);
MODULE_DEPEND(if_lmc, pci, 1, 1, 1);
# if NETGRAPH
MODULE_DEPEND(if_lmc, netgraph, NG_ABI_VERSION, NG_ABI_VERSION, NG_ABI_VERSION);
# endif
# if NSPPP
MODULE_DEPEND(if_lmc, sppp, 1, 1, 1);
# endif

#endif  /* __FreeBSD__ */

/* This is the I/O configuration interface for NetBSD. */

#ifdef __NetBSD__

static int
nbsd_match(struct device *parent, struct cfdata *match, void *aux)
  {
  struct pci_attach_args *pa = aux;
  u_int32_t cfid = pci_conf_read(pa->pa_pc, pa->pa_tag, TLP_CFID);
  u_int32_t csid = pci_conf_read(pa->pa_pc, pa->pa_tag, TLP_CSID);	

  /* Looking for a DEC 21140A chip on any Lan Media Corp card. */
  if (cfid != TLP_CFID_TULIP) return 0;
  switch (csid)
    {
    case TLP_CSID_HSSI:
    case TLP_CSID_HSSIc:
    case TLP_CSID_T3:
    case TLP_CSID_SSI:
    case TLP_CSID_T1E1:
      return 100;
    default:
      return 0;
    }
  }

static int
nbsd_detach(struct device *self, int flags)
  {
  softc_t *sc = (softc_t *)self; /* device is first in softc */

  /* Stop the card and detach from the kernel. */
  detach_card(sc);

  /* Release resources. */
  if (sc->sdh_cookie != NULL)
    {
    shutdownhook_disestablish(sc->sdh_cookie);
    sc->sdh_cookie = NULL;
    }
  if (sc->irq_cookie != NULL)
    {
    pci_intr_disestablish(sc->pa_pc, sc->irq_cookie);
    sc->irq_cookie = NULL;
    }
  if (sc->csr_handle)
    {
    bus_space_unmap(sc->csr_tag, sc->csr_handle, TLP_CSR_SIZE);
    sc->csr_handle = 0;
    }

  return 0; /* no error */
  }

static void
nbsd_attach(struct device *parent, struct device *self, void *aux)
  {
  softc_t *sc = (softc_t *)self; /* device is first in softc */
  struct pci_attach_args *pa = aux;
  const char *intrstr;
  bus_addr_t csr_addr;
  int error;

  /* READ/WRITE_PCI_CFG need these. */
  sc->pa_pc   = pa->pa_pc;
  sc->pa_tag  = pa->pa_tag;
  /* bus_dma needs this. */
  sc->pa_dmat = pa->pa_dmat;

  /* What kind of card are we driving? */
  switch (READ_PCI_CFG(sc, TLP_CSID))
    {
    case TLP_CSID_HSSI:
    case TLP_CSID_HSSIc:
      sc->dev_desc =  HSSI_DESC;
      sc->card     = &hssi_card;
      break;
    case TLP_CSID_T3:
      sc->dev_desc =    T3_DESC;
      sc->card     =   &t3_card;
      break;
    case TLP_CSID_SSI:
      sc->dev_desc =   SSI_DESC;
      sc->card     =  &ssi_card;
      break;
    case TLP_CSID_T1E1:
      sc->dev_desc =  T1E1_DESC;
      sc->card     =   &t1_card;
      break;
    default:
      return;
    }
  printf(": %s\n", sc->dev_desc);

  /* Allocate PCI resources to access the Tulip chip CSRs. */
# if IOREF_CSR
  csr_addr = (bus_addr_t)READ_PCI_CFG(sc, TLP_CBIO) & -2;
  sc->csr_tag = pa->pa_iot;	/* bus_space tag for IO refs */
# else
  csr_addr = (bus_addr_t)READ_PCI_CFG(sc, TLP_CBMA);
  sc->csr_tag = pa->pa_memt;	/* bus_space tag for MEM refs */
# endif
  if ((error = bus_space_map(sc->csr_tag, csr_addr,
   TLP_CSR_SIZE, 0, &sc->csr_handle)))
    {
    printf("%s: bus_space_map() failed; error %d\n", NAME_UNIT, error);
    return;
    }

  /* Allocate PCI interrupt resources. */
  if ((error = pci_intr_map(pa, &sc->intr_handle)))
    {
    printf("%s: pci_intr_map() failed; error %d\n", NAME_UNIT, error);
    nbsd_detach(self, 0);
    return;
    }
  sc->irq_cookie = pci_intr_establish(pa->pa_pc, sc->intr_handle,
   IPL_NET, bsd_interrupt, sc);
  if (sc->irq_cookie == NULL)
    {
    printf("%s: pci_intr_establish() failed\n", NAME_UNIT);
    nbsd_detach(self, 0);
    return;
    }
  intrstr = pci_intr_string(pa->pa_pc, sc->intr_handle);

  /* Install a shutdown hook. */
  sc->sdh_cookie = shutdownhook_establish(shutdown_card, sc);
  if (sc->sdh_cookie == NULL)
    {
    printf("%s: shutdown_hook_establish() failed\n", NAME_UNIT);
    nbsd_detach(self, 0);
    return;
    }

  /* Initialize the top-half and bottom-half locks. */
  simple_lock_init(&sc->top_lock);
  simple_lock_init(&sc->bottom_lock);

  /* Start the card and attach a kernel interface and line protocol. */
  if ((error = attach_card(sc, intrstr))) detach_card(sc);
  }

# if (__NetBSD_Version__ >= 106080000) /* 1.6H */
CFATTACH_DECL(lmc, sizeof(softc_t),
 nbsd_match, nbsd_attach, nbsd_detach, NULL);
# else
struct cfattach lmc_ca =
  {
/*.ca_name	= DEVICE_NAME, */
  .ca_devsize	= sizeof(softc_t),
  .ca_match	= nbsd_match,
  .ca_attach	= nbsd_attach,
  .ca_detach	= nbsd_detach,
  .ca_activate	= NULL,
  };
# endif

# if (__NetBSD_Version__ >= 106080000)
CFDRIVER_DECL(lmc, DV_IFNET, NULL);
# else
static struct cfdriver lmc_cd =
  {
  .cd_name	= DEVICE_NAME,
  .cd_class	= DV_IFNET,
  .cd_ndevs	= 0,
  .cd_devs	= NULL,
  };
# endif

/* cfdata is declared static, unseen outside this module. */
/* It is used for LKM; config builds its own in ioconf.c. */
static struct cfdata lmc_cf =
  {
# if (__NetBSD_Version__ >= 106080000)
  .cf_name	= DEVICE_NAME,
  .cf_atname    = DEVICE_NAME,
# else
  .cf_driver	= &lmc_cd,
  .cf_attach	= &lmc_ca,
# endif
  .cf_unit	= 0,
  .cf_fstate	= FSTATE_STAR,
  };

# if (__NetBSD_Version__ >= 106080000)
MOD_MISC(DEVICE_NAME)
# else
static struct lkm_misc _module =
  {
  .lkm_name	= DEVICE_NAME,
  .lkm_type	= LM_MISC,
  .lkm_offset	= 0,
  .lkm_ver	= LKM_VERSION,
  };
# endif

/* From /sys/dev/pci/pci.c (no public prototype). */
int pciprint(void *, const char *);

static int lkm_nbsd_match(struct pci_attach_args *pa)
  { return nbsd_match(0, 0, pa); }

/* LKM loader finds this by appending "_lkmentry" to filename "if_lmc". */
int if_lmc_lkmentry(struct lkm_table *lkmtp, int cmd, int ver)
  {
  int i, error = 0;

  if (ver != LKM_VERSION) return EINVAL;
  switch (cmd)
    {
    case LKM_E_LOAD:
      {
      struct cfdriver* pcicd;

      lkmtp->private.lkm_misc = &_module;
      if ((pcicd = config_cfdriver_lookup("pci")) == NULL)
        {
        printf("%s: config_cfdriver_lookup(pci) failed; error %d\n",
         lmc_cd.cd_name, error);
        return error;
	}
# if (__NetBSD_Version__ >= 106080000)
      if ((error = config_cfdriver_attach(&lmc_cd)))
        {
        printf("%s: config_cfdriver_attach() failed; error %d\n",
         lmc_cd.cd_name, error);
        return error;
        }
      if ((error = config_cfattach_attach(lmc_cd.cd_name, &lmc_ca)))
        {
        printf("%s: config_cfattach_attach() failed; error %d\n",
         lmc_cd.cd_name, error);
        config_cfdriver_detach(&lmc_cd);
        return error;
        }
# endif
      for (i=0; i<pcicd->cd_ndevs; i++)
        {
        int dev;
        /* A pointer to a device is a pointer to its softc. */
        struct pci_softc *sc = pcicd->cd_devs[i];
        if (sc == NULL) continue;
        for (dev=0; dev<sc->sc_maxndevs; dev++)
          {
          struct pci_attach_args pa;
          pcitag_t tag = pci_make_tag(sc->sc_pc, sc->sc_bus, dev, 0);
          if (pci_probe_device(sc, tag, lkm_nbsd_match, &pa) != 0)
            config_attach(pcicd->cd_devs[i], &lmc_cf, &pa, pciprint);
            /* config_attach doesn't return on failure; it calls panic. */
          }
	}
      break;
      }
    case LKM_E_UNLOAD:
      {
      for (i=lmc_cd.cd_ndevs-1; i>=0; i--)
        {
        struct device *dev = lmc_cd.cd_devs[i];
        if (dev == NULL) continue;
        if ((error = config_detach(dev, 0)))
          {
          printf("%s: config_detach() failed; error %d\n",
           dev->dv_xname, error);
          return error;
	  }
	}
# if (__NetBSD_Version__ >= 106080000)
      if ((error = config_cfattach_detach(lmc_cd.cd_name, &lmc_ca)))
        {
        printf("%s: config_cfattach_detach() failed; error %d\n",
         lmc_cd.cd_name, error);
        return error;
        }
      if ((error = config_cfdriver_detach(&lmc_cd)))
        {
        printf("%s: config_cfdriver_detach() failed; error %d\n",
         lmc_cd.cd_name, error);
        return error;
        }
# endif
      break;
      }
    case LKM_E_STAT:
      break;
    }

  return error;
  }

#endif  /* __NetBSD__ */

/* This is the I/O configuration interface for OpenBSD. */

#ifdef __OpenBSD__

static int
obsd_match(struct device *parent, void *match, void *aux)
  {
  struct pci_attach_args *pa = aux;
  u_int32_t cfid = pci_conf_read(pa->pa_pc, pa->pa_tag, TLP_CFID);
  u_int32_t csid = pci_conf_read(pa->pa_pc, pa->pa_tag, TLP_CSID);	

  /* Looking for a DEC 21140A chip on any Lan Media Corp card. */
  if (cfid != TLP_CFID_TULIP) return 0;
  switch (csid)
    {
    case TLP_CSID_HSSI:
    case TLP_CSID_HSSIc:
    case TLP_CSID_T3:
    case TLP_CSID_SSI:
    case TLP_CSID_T1E1:
      return 100; /* match better than other 21140 drivers */
    default:
      return 0;
    }
  }

static int
obsd_detach(struct device *self, int flags)
  {
  softc_t *sc = (softc_t *)self; /* device is first in softc */

  /* Stop the card and detach from the kernel. */
  detach_card(sc);

  /* Release resources. */
  if (sc->sdh_cookie != NULL)
    {
    shutdownhook_disestablish(sc->sdh_cookie);
    sc->sdh_cookie = NULL;
    }
  if (sc->irq_cookie != NULL)
    {
    pci_intr_disestablish(sc->pa_pc, sc->irq_cookie);
    sc->irq_cookie = NULL;
    }
  if (sc->csr_handle)
    {
    bus_space_unmap(sc->csr_tag, sc->csr_handle, TLP_CSR_SIZE);
    sc->csr_handle = 0;
    }

  return 0; /* no error */
  }

static void
obsd_attach(struct device *parent, struct device *self, void *aux)
  {
  softc_t *sc = (softc_t *)self; /* device is first in softc */
  struct pci_attach_args *pa = aux;
  const char *intrstr;
  bus_addr_t csr_addr;
  int error;

  /* READ/WRITE_PCI_CFG need these. */
  sc->pa_pc   = pa->pa_pc;
  sc->pa_tag  = pa->pa_tag;
  /* bus_dma needs this. */
  sc->pa_dmat = pa->pa_dmat;

  /* What kind of card are we driving? */
  switch (READ_PCI_CFG(sc, TLP_CSID))
    {
    case TLP_CSID_HSSI:
    case TLP_CSID_HSSIc:
      sc->dev_desc =  HSSI_DESC;
      sc->card     = &hssi_card;
      break;
    case TLP_CSID_T3:
      sc->dev_desc =    T3_DESC;
      sc->card     =   &t3_card;
      break;
    case TLP_CSID_SSI:
      sc->dev_desc =   SSI_DESC;
      sc->card     =  &ssi_card;
      break;
    case TLP_CSID_T1E1:
      sc->dev_desc =  T1E1_DESC;
      sc->card     =   &t1_card;
      break;
    default:
      return;
    }
  printf(": %s\n", sc->dev_desc);

  /* Allocate PCI resources to access the Tulip chip CSRs. */
# if IOREF_CSR
  csr_addr = (bus_addr_t)READ_PCI_CFG(sc, TLP_CBIO) & -2;
  sc->csr_tag = pa->pa_iot;	/* bus_space tag for IO refs */
# else
  csr_addr = (bus_addr_t)READ_PCI_CFG(sc, TLP_CBMA);
  sc->csr_tag = pa->pa_memt;	/* bus_space tag for MEM refs */
# endif
  if ((error = bus_space_map(sc->csr_tag, csr_addr,
   TLP_CSR_SIZE, 0, &sc->csr_handle)))
    {
    printf("%s: bus_space_map() failed; error %d\n", NAME_UNIT, error);
    return;
    }

  /* Allocate PCI interrupt resources. */
  if ((error = pci_intr_map(pa, &sc->intr_handle)))
    {
    printf("%s: pci_intr_map() failed; error %d\n", NAME_UNIT, error);
    obsd_detach(self, 0);
    return;
    }
  sc->irq_cookie = pci_intr_establish(pa->pa_pc, sc->intr_handle,
   IPL_NET, bsd_interrupt, sc, self->dv_xname);
  if (sc->irq_cookie == NULL)
    {
    printf("%s: pci_intr_establish() failed\n", NAME_UNIT);
    obsd_detach(self, 0);
    return;
    }
  intrstr = pci_intr_string(pa->pa_pc, sc->intr_handle);

  /* Install a shutdown hook. */
  sc->sdh_cookie = shutdownhook_establish(shutdown_card, sc);
  if (sc->sdh_cookie == NULL)
    {
    printf("%s: shutdown_hook_establish() failed\n", NAME_UNIT);
    obsd_detach(self, 0);
    return;
    }

  /* Initialize the top-half and bottom-half locks. */
  simple_lock_init(&sc->top_lock);
  simple_lock_init(&sc->bottom_lock);

  /* Start the card and attach a kernel interface and line protocol. */
  if ((error = attach_card(sc, intrstr))) detach_card(sc);
  }

struct cfattach lmc_ca =
  {
  .ca_devsize	= sizeof(softc_t),
  .ca_match	= obsd_match,
  .ca_attach	= obsd_attach,
  .ca_detach	= obsd_detach,
  .ca_activate	= NULL,
  };

struct cfdriver lmc_cd =
  {
  .cd_name	= DEVICE_NAME,
  .cd_devs	= NULL,
  .cd_class	= DV_IFNET,
  .cd_indirect	= 0,
  .cd_ndevs	= 0,
  };

/* cfdata is declared static, unseen outside this module. */
/* It is used for LKM; config builds its own in ioconf.c. */
static struct cfdata lmc_cfdata =
  {
  .cf_attach	= &lmc_ca,
  .cf_driver	= &lmc_cd,
  .cf_unit	= 0,
  .cf_fstate	= FSTATE_STAR,
  };

static struct lkm_any _module =
  {
  .lkm_name	= DEVICE_NAME,
  .lkm_type	= LM_MISC,
  .lkm_offset	= 0,
  .lkm_ver	= LKM_VERSION,
  };

/* From /sys/dev/pci/pci.c (no public prototype). */
int pciprint(void *, const char *);

extern struct cfdriver pci_cd;

/* LKM loader finds this by appending "_lkmentry" to filename "if_lmc". */
int if_lmc_lkmentry(struct lkm_table *lkmtp, int cmd, int ver)
  {
  int i, error = 0;

  if (ver != LKM_VERSION) return EINVAL;
  switch (cmd)
    {
    case LKM_E_LOAD:
      {  /* XXX This works for ONE card on pci0 of a i386 machine! XXX */
      lkmtp->private.lkm_any = &_module;
      for (i=0; i<pci_cd.cd_ndevs; i++)
        {
        struct pci_attach_args pa;
        struct device *parent = pci_cd.cd_devs[i];
        if (parent == NULL) continue; /* dead clone? */
        if ((parent->dv_unit)!=0) continue; /* only bus zero */
        /* XXX For machine independence, need: pcibus_attach_args. XXX */
        /* XXX See NetBSD's sys/dev/pci/pci.c/pci_probe_device.    XXX */
        /* XXX Why isn't there an LKM network interface module?    XXX */
        pa.pa_pc    = NULL;					/* XXX */
        pa.pa_bus   = 0;					/* XXX */
        pa.pa_iot   = I386_BUS_SPACE_IO;			/* XXX */
        pa.pa_memt  = I386_BUS_SPACE_MEM;			/* XXX */
        pa.pa_dmat  = &pci_bus_dma_tag;				/* XXX */
        for (pa.pa_device=0; pa.pa_device<32; pa.pa_device++)	/* XXX */
          {
          int intr;
          pa.pa_function = 0; /* DEC-21140A has function 0 only    XXX */
          pa.pa_tag = pci_make_tag(pa.pa_pc, pa.pa_bus, pa.pa_device, 0);
          pa.pa_id = pci_conf_read(pa.pa_pc, pa.pa_tag, PCI_ID_REG);
          if ((pa.pa_id & 0xFFFF) == 0xFFFF) continue;
          if ((pa.pa_id & 0xFFFF) == 0) continue;
          /* XXX this only works for pci0 -- no swizzelling        XXX */
          pa.pa_intrswiz = 0;
          pa.pa_intrtag = pa.pa_tag;
          intr = pci_conf_read(pa.pa_pc, pa.pa_tag, PCI_INTERRUPT_REG);
          pa.pa_intrline = PCI_INTERRUPT_LINE(intr);
          pa.pa_intrpin = ((PCI_INTERRUPT_PIN(intr) -1) % 4) +1;
          if (obsd_match(parent, &lmc_cfdata, &pa))
            config_attach(parent, &lmc_cfdata, &pa, pciprint);
          /* config_attach doesn't return on failure; it calls panic. */
          }
	}
      break;
      }
    case LKM_E_UNLOAD:
      {
      for (i=lmc_cd.cd_ndevs-1; i>=0; i--)
        {
        struct device *dev = lmc_cd.cd_devs[i];
        if (dev == NULL) continue;
        if ((error = config_detach(dev, 0)))
          printf("%s: config_detach() failed; error %d\n", dev->dv_xname, error);
        }
      break;
      }
    case LKM_E_STAT:
      break;
    }

  return error;
  }

#endif  /* __OpenBSD__ */

/* This is the I/O configuration interface for BSD/OS. */

#ifdef __bsdi__

static int
bsdi_match(pci_devaddr_t *pa)
  {
  u_int32_t cfid = pci_inl(pa, TLP_CFID);
  u_int32_t csid = pci_inl(pa, TLP_CSID);

  /* Looking for a DEC 21140A chip on any Lan Media Corp card. */
  if (cfid != TLP_CFID_TULIP) return 0;
  switch (csid)
    {
    case TLP_CSID_HSSI:
    case TLP_CSID_HSSIc:
    case TLP_CSID_T3:
    case TLP_CSID_SSI:
    case TLP_CSID_T1E1:
      return 1;
    default:
      return 0;
    }
  }

static int
bsdi_probe(struct device *parent, struct cfdata *cf, void *aux)
  {
  struct isa_attach_args *ia = aux;
  pci_devaddr_t *pa = NULL;
  pci_devres_t res;

  /* This must be a PCI bus. */
  if (ia->ia_bustype != BUS_PCI) return 0;

  /* Scan PCI bus for our boards. */
  if ((pa = pci_scan(bsdi_match)) == 0) return 0;

  /* Scan config space for IO and MEM base registers and IRQ info. */
  pci_getres(pa, &res, 1, ia);

  /* Crucial: pass pci_devaddr to bsdi_attach in ia_aux. */
  ia->ia_aux = (void *)pa;

  return 1;
  }

static void
bsdi_attach(struct device *parent, struct device *self, void *aux)
  {
  softc_t *sc = (softc_t *)self; /* device is first in softc */
  struct isa_attach_args *ia = aux;
  pci_devaddr_t *pa = ia->ia_aux; /* this is crucial! */
  int error;

  /* READ/WRITE_PCI_CFG need this. */
  sc->cfgbase = *pa;

  /* What kind of card are we driving? */
  switch (READ_PCI_CFG(sc, TLP_CSID))
    {
    case TLP_CSID_HSSI:
    case TLP_CSID_HSSIc:
      sc->dev_desc =  HSSI_DESC;
      sc->card     = &hssi_card;
      break;
    case TLP_CSID_T3:
      sc->dev_desc =    T3_DESC;
      sc->card     =   &t3_card;
      break;
    case TLP_CSID_SSI:
      sc->dev_desc =   SSI_DESC;
      sc->card     =  &ssi_card;
      break;
    case TLP_CSID_T1E1:
      sc->dev_desc =  T1E1_DESC;
      sc->card     =   &t1_card;
      break;
    default:
      return;
    }
  printf(": %s\n", sc->dev_desc);

  /* Allocate PCI memory or IO resources to access the Tulip chip CSRs. */
  sc->csr_iobase  = ia->ia_iobase;
  sc->csr_membase = (u_int32_t *)mapphys((vm_offset_t)ia->ia_maddr, TLP_CSR_SIZE);

  /* Attach to the PCI bus. */
  isa_establish(&sc->id, &sc->dev);

  /* Allocate PCI interrupt resources for the card. */
  sc->ih.ih_fun = bsd_interrupt;
  sc->ih.ih_arg = sc;
  intr_establish(ia->ia_irq, &sc->ih, DV_NET);

  /* Install a shutdown hook. */
  sc->ats.func = shutdown_card;
  sc->ats.arg = sc;
  atshutdown(&sc->ats, ATSH_ADD);

  /* Initialize the top-half and bottom-half locks. */
  simple_lock_init(&sc->top_lock);
  simple_lock_init(&sc->bottom_lock);

  /* Start the card and attach a kernel interface and line protocol. */
  if ((error = attach_card(sc, ""))) detach_card(sc);
  }

struct cfdriver lmccd =
  {
  .cd_devs	= NULL,
  .cd_name	= DEVICE_NAME,
  .cd_match	= bsdi_probe,
  .cd_attach	= bsdi_attach,
  .cd_class	= DV_IFNET,
  .cd_devsize	= sizeof(softc_t),
  };
#endif  /* __bsdi__ */

#ifdef __linux__

/* The kernel calls this procedure when an interrupt happens. */
static irqreturn_t
linux_interrupt(int irq, void *dev, struct pt_regs *regs)
  {
  struct net_device *net_dev = dev;
  softc_t *sc = dev_to_hdlc(net_dev)->priv;

  /* Cut losses early if this is not our interrupt. */
  if ((READ_CSR(TLP_STATUS) & TLP_INT_TXRX) == 0)
    return IRQ_NONE;

  /* Disable card interrupts. */
  WRITE_CSR(TLP_INT_ENBL, TLP_INT_DISABLE);

  /* Handle the card interrupt with the dev->poll method. */
  if (netif_rx_schedule_prep(net_dev))
    __netif_rx_schedule(net_dev);  /* NAPI - add to poll list */
  else
    printk("%s: interrupt while on poll list\n", NAME_UNIT);

  return IRQ_HANDLED;
  }

/* This net_device method services interrupts in a softirq. */
/* With rxintr_cleanup(), it implements input flow control. */
static int
linux_poll(struct net_device *net_dev, int *budget)
  {
  softc_t *sc = dev_to_hdlc(net_dev)->priv;
  int received;

  /* Yes, we do NAPI. */
  /* Allow processing up to net_dev->quota incoming packets. */
  /* This is the ONLY time core_interrupt() may process rx pkts. */
  /* Otherwise (sc->quota == 0) and rxintr_cleanup() is a NOOP. */
  sc->quota = net_dev->quota;

  /* Handle the card interrupt with kernel ints enabled. */
  /* Process rx pkts (and tx pkts, too). */
  /* Card interrupts are disabled. */
  core_interrupt(sc, 0);

  /* Report number of rx packets processed. */
  received = net_dev->quota - sc->quota;
  net_dev->quota -= received;
  *budget        -= received;

  /* if quota prevented processing all rx pkts, leave rx ints disabled */
  if (sc->quota == 0)  /* this is off by one...but harmless */
    {
    WRITE_CSR(TLP_INT_ENBL, TLP_INT_TX);
    return 1; /* more pkts to handle -- reschedule */
    }

  sc->quota = 0;  /* disable rx pkt processing by rxintr_cleanup() */
  netif_rx_complete(net_dev); /* NAPI - remove from poll list */

  /* Enable card interrupts. */
  WRITE_CSR(TLP_INT_ENBL, TLP_INT_TXRX);
  return 0;
  }

/* These next routines are similar to BSD's ifnet kernel/driver interface. */

/* This net_device method hands outgoing packets to the transmitter. */
/* With txintr_setup(), it implements output flow control. */
/* Called from a syscall (user context; no spinlocks). */
static int
linux_start(struct sk_buff *skb, struct net_device *net_dev)
  {
  softc_t *sc = dev_to_hdlc(net_dev)->priv;

  if (sc->tx_skb == NULL)
    {
    /* Put this skb where the transmitter will see it. */
    sc->tx_skb = skb;

    /* Start the transmitter; incoming pkts are NOT processed. */
    user_interrupt(sc, 0);

    /* If the tx didn't take the skb then stop the queue. */
    /* This can happen if another CPU is in core_interrupt(). */
    if (sc->tx_skb != NULL) netif_stop_queue(net_dev);

    return 0;
    }

  /* This shouldn't happen; skb is NOT consumed. */
  if (netif_queue_stopped(net_dev))
    printk("%s: dev->start() called with queue stopped\n", NAME_UNIT);
  else
    netif_stop_queue(net_dev);

  return 1;
  }

/* This net_device method restarts the transmitter if it hangs. */
/* Called from a softirq. */
static void
linux_timeout(struct net_device *net_dev)
  {
  softc_t *sc = dev_to_hdlc(net_dev)->priv;

  /* Start the transmitter; incoming packets are NOT processed. */
  user_interrupt(sc, 1);
  }

/* This net_device method handles IOCTL syscalls. */
/* Called from a syscall (user context; no spinlocks; can sleep). */
static int
linux_ioctl(struct net_device *net_dev, struct ifreq *ifr, int cmd)
  {
  softc_t *sc = dev_to_hdlc(net_dev)->priv;
  int error = 0;

  if ((cmd >= SIOCDEVPRIVATE) && (cmd <= SIOCDEVPRIVATE+15))
    {
    struct iohdr *iohdr = (struct iohdr *)ifr;
    u_int16_t direction = iohdr->direction;
    u_int16_t length = iohdr->length;
    char *user_addr = (char *)iohdr->iohdr;
    char *kern_addr;

    if (iohdr->cookie != NGM_LMC_COOKIE) return -EINVAL;

    /* Emulate a BSD-style IOCTL syscall. */
    kern_addr = kmalloc(length, GFP_KERNEL);
    if (kern_addr == NULL)
      error = -ENOMEM;
    if ((error == 0) && ((direction & DIR_IOW) != 0))
      error = copy_from_user(kern_addr, user_addr, length);
    if (error == 0)
      error = -core_ioctl(sc, (unsigned long)cmd, kern_addr);
    if ((error == 0) && ((direction & DIR_IOR) != 0))
      error = copy_to_user(user_addr, kern_addr, length);
    kfree(kern_addr);
    }
# if GEN_HDLC
  else if (cmd == SIOCWANDEV)
    {
    const size_t size = sizeof(sync_serial_settings);

    switch (ifr->ifr_settings.type)
      {
      case IF_GET_IFACE: /* get interface config */
        {
        ifr->ifr_settings.type = IF_IFACE_SYNC_SERIAL;
        if (ifr->ifr_settings.size < size)
          {
          ifr->ifr_settings.size = size;
          error = -ENOBUFS;
	  }
        else
          {
          if (sc->config.tx_clk_src == CFG_CLKMUX_ST)
            sc->hdlc_settings.clock_type = CLOCK_EXT;
          if (sc->config.tx_clk_src == CFG_CLKMUX_INT)
            sc->hdlc_settings.clock_type = CLOCK_TXINT;
          if (sc->config.tx_clk_src == CFG_CLKMUX_RT)
            sc->hdlc_settings.clock_type = CLOCK_TXFROMRX;
          sc->hdlc_settings.loopback = (sc->config.loop_back != CFG_LOOP_NONE) ? 1:0;
          sc->hdlc_settings.clock_rate = sc->status.tx_speed;
          error = copy_to_user(ifr->ifr_settings.ifs_ifsu.sync,
           &sc->hdlc_settings, size);
	  }
        break;
	}
      case IF_IFACE_SYNC_SERIAL: /* set interface config */
        {
        if (!capable(CAP_NET_ADMIN))
          error = -EPERM;
        if (error == 0) 
          error = copy_from_user(&sc->hdlc_settings,
          ifr->ifr_settings.ifs_ifsu.sync, size);
        /* hdlc_settings are currently ignored. */
        break;
	}
      default:  /* Pass the rest to the line protocol code. */
        {
        error = hdlc_ioctl(net_dev, ifr, cmd);
        break;
	}
      }
    }
# endif /* GEN_HDLC */
  else /* unknown IOCTL command */
    error = -EINVAL;

  if (DRIVER_DEBUG)
    printk("%s: linux_ioctl; cmd=0x%08x error=%d\n",
     NAME_UNIT, cmd, error);

  return error;
  }

/* This net_device method returns a pointer to device statistics. */
static struct net_device_stats *
linux_stats(struct net_device *net_dev)
  {
# if GEN_HDLC
  return &dev_to_hdlc(net_dev)->stats;
# else
  softc_t *sc = net_dev->priv;
  return &sc->net_stats;
# endif
  }

/* Called from a softirq once a second. */
static void
linux_watchdog(unsigned long softc)
  {
  softc_t *sc = (softc_t *)softc;
  u_int8_t old_oper_status = sc->status.oper_status;
  struct event_cntrs *cntrs = &sc->status.cntrs;
  struct net_device_stats *stats = linux_stats(sc->net_dev);

  core_watchdog(sc); /* updates oper_status */

  /* Notice change in link status. */
  if     ((old_oper_status != STATUS_UP) &&
   (sc->status.oper_status == STATUS_UP))  /* link came up */
    {
    hdlc_set_carrier(1, sc->net_dev);
    netif_wake_queue(sc->net_dev);
    }
  if     ((old_oper_status == STATUS_UP) &&
   (sc->status.oper_status != STATUS_UP))  /* link went down */
    {
    hdlc_set_carrier(0, sc->net_dev);
    netif_stop_queue(sc->net_dev);
    }

  /* Notice change in line protocol. */
  if (sc->config.line_pkg == PKG_RAWIP)
    {
    sc->status.line_pkg  = PKG_RAWIP;
    sc->status.line_prot = PROT_IP_HDLC;
    }
# if GEN_HDLC
  else
    {
    sc->status.line_pkg  = PKG_GEN_HDLC;
    switch (sc->hdlc_dev->proto.id)
      {
      case IF_PROTO_PPP:
        sc->status.line_prot = PROT_PPP;
        break;
      case IF_PROTO_CISCO:
        sc->status.line_prot = PROT_C_HDLC;
        break;
      case IF_PROTO_FR:
        sc->status.line_prot = PROT_FRM_RLY;
        break;
      case IF_PROTO_HDLC:
        sc->status.line_prot = PROT_IP_HDLC;
        break;
      case IF_PROTO_X25:
        sc->status.line_prot = PROT_X25;
        break;
      case IF_PROTO_HDLC_ETH:
        sc->status.line_prot = PROT_ETH_HDLC;
        break;
      default:
        sc->status.line_prot = 0;
        break;
      }
    }
# endif /* GEN_HDLC */

  /* Copy statistics from sc to net_dev for get_stats(). */
  stats->rx_packets       = cntrs->ipackets;
  stats->tx_packets       = cntrs->opackets;
  stats->rx_bytes         = cntrs->ibytes;
  stats->tx_bytes         = cntrs->obytes;
  stats->rx_errors        = cntrs->ierrors;
  stats->tx_errors        = cntrs->oerrors;
  stats->rx_dropped       = cntrs->idiscards;
  stats->tx_dropped       = cntrs->odiscards;
  stats->rx_fifo_errors   = cntrs->fifo_over;
  stats->tx_fifo_errors   = cntrs->fifo_under;
  stats->rx_missed_errors = cntrs->missed;
  stats->rx_over_errors   = cntrs->overruns;

  /* Call this procedure again after one second. */
  sc->wd_timer.expires = jiffies + HZ; /* now plus one second */
  add_timer(&sc->wd_timer);
  }

/* This is the I/O configuration interface for Linux. */

/* This net_device method is called when IFF_UP goes false. */
static int
linux_stop(struct net_device *net_dev)
  {
  softc_t *sc = dev_to_hdlc(net_dev)->priv;

  /* Stop the card and detach from the kernel. */
  detach_card(sc);  /* doesn't fail */

  free_irq(net_dev->irq, net_dev); /* doesn't fail */

  del_timer(&sc->wd_timer); /* return value ignored */

  return 0;
  }

/* This net_device method is called when IFF_UP goes true. */
static int
linux_open(struct net_device *net_dev)
  {
  softc_t *sc = dev_to_hdlc(net_dev)->priv;
  int error;

  /* Allocate PCI interrupt resources for the card. */
  if ((error = request_irq(net_dev->irq, &linux_interrupt, SA_SHIRQ,
   NAME_UNIT, net_dev)))
    {
    printk("%s: request_irq() failed; error %d\n", NAME_UNIT, error);
    return error;
    }

  /* Arrange to call linux_watchdog() once a second. */
  init_timer(&sc->wd_timer);
  sc->wd_timer.expires  = jiffies + HZ; /* now plus one second */
  sc->wd_timer.function = &linux_watchdog;
  sc->wd_timer.data     = (unsigned long) sc;
  add_timer(&sc->wd_timer);

  /* Start the card and attach a kernel interface and line protocol. */
  if ((error = -attach_card(sc, "")))
    linux_stop(net_dev);
  else
    {
    net_dev->weight = sc->rxring.num_descs; /* input flow control */
    netif_start_queue(net_dev);            /* output flow control */
    }

  return error;
  }

# if GEN_HDLC
static int
hdlc_attach(struct net_device *net_dev,
 unsigned short encoding, unsigned short parity)
  { return 0; }
# endif

/* This pci_driver method is called during shutdown or module-unload. */
/* This is called from user context; can sleep; no spinlocks! */
static void __exit
linux_remove(struct pci_dev *pci_dev)
  {
  struct net_device *net_dev = (struct net_device *)pci_get_drvdata(pci_dev);
  softc_t *sc = dev_to_hdlc(net_dev)->priv;

  if (net_dev == NULL) return;

  /* Assume that linux_stop() has already been called. */
  if (sc->flags & FLAG_NETDEV)
# if GEN_HDLC
    unregister_hdlc_device(net_dev);
# else
    unregister_netdev(net_dev);
# endif

# if (IOREF_CSR == 0)
  if (sc->csr_membase != NULL)
    iounmap(sc->csr_membase);
# endif

  pci_disable_device(pci_dev);

  if (sc->csr_iobase != 0)
    pci_release_regions(pci_dev);

  pci_set_drvdata(pci_dev, NULL);

  kfree(sc);
  free_netdev(net_dev);
  }

static void
setup_netdev(struct net_device *net_dev)
  {
  /* Initialize the generic network device. */
  /* Note similarity to BSD's lmc_ifnet_attach(). */
  net_dev->flags           = IFF_POINTOPOINT;
  net_dev->flags          |= IFF_RUNNING;
  net_dev->open            = linux_open;
  net_dev->stop            = linux_stop;
  net_dev->hard_start_xmit = linux_start;
  net_dev->do_ioctl        = linux_ioctl;
  net_dev->get_stats       = linux_stats;
  net_dev->tx_timeout      = linux_timeout;
  net_dev->poll            = linux_poll;
  net_dev->watchdog_timeo  = 1 * HZ;
  net_dev->tx_queue_len    = SNDQ_MAXLEN;
  net_dev->mtu             = MAX_DESC_LEN;
  net_dev->type            = ARPHRD_RAWHDLC;
/* The receiver generates frag-lists for packets >4032 bytes.   */
/* The transmitter accepts scatter/gather lists and frag-lists. */
/* However Linux linearizes outgoing packets since our hardware */
/*  doesn't compute soft checksums.  All that work for nothing! */
/*net_dev->features       |= NETIF_F_SG; */
/*net_dev->features       |= NETIF_F_FRAGLIST; */
  }

/* This pci_driver method is called during boot or module-load. */
/* This is called from user context; can sleep; no spinlocks! */
static int __init
linux_probe(struct pci_dev *pci_dev, const struct pci_device_id *id)
  {
  u_int32_t cfid, csid;
  struct net_device *net_dev;
  softc_t *sc;
  int error;

  /* Looking for a DEC 21140A chip on any Lan Media Corp card. */
  pci_read_config_dword(pci_dev, TLP_CFID, &cfid);
  if (cfid != TLP_CFID_TULIP) return -ENXIO;
  pci_read_config_dword(pci_dev, TLP_CSID, &csid);
  switch (csid)
    {
    case TLP_CSID_HSSI:
    case TLP_CSID_HSSIc:
    case TLP_CSID_T3:
    case TLP_CSID_SSI:
    case TLP_CSID_T1E1:
      break;
    default:
      return -ENXIO;
    }

  /* Declare that these cards use 32-bit single-address PCI cycles. */
  if ((error = pci_set_dma_mask(pci_dev, DMA_32BIT_MASK)))
    {
    printk("%s: pci_set_dma_mask() failed; error %d\n", DEVICE_NAME, error);
    return error;
    }
  pci_set_consistent_dma_mask(pci_dev, DMA_32BIT_MASK); /* can't fail */

# if GEN_HDLC /* generic-hdlc line protocols */

  /* device driver instance data, aka Soft Context or sc */
  if ((sc = kmalloc(sizeof(softc_t), GFP_KERNEL)) == NULL)
    {
    printk("%s: kmalloc() failed\n", DEVICE_NAME);
    return -ENOMEM;
    }
  memset(sc, 0, sizeof(softc_t));

  /* Allocate space for the HDLC network device struct. */
  if ((net_dev = alloc_hdlcdev(sc)) == NULL)
    {
    printk("%s: alloc_hdlcdev() failed\n", DEVICE_NAME);
    kfree(sc);
    return -ENOMEM;
    }

  /* Initialize the network device struct. */
  setup_netdev(net_dev);

  /* Initialize the HDLC extension to the network device. */
  sc->hdlc_dev         = dev_to_hdlc(net_dev);
  sc->hdlc_dev->attach = hdlc_attach; /* noop for this driver */
  sc->hdlc_dev->xmit   = linux_start; /* the REAL hard_start_xmit() */

# else /* GEN_HDLC */ /* no line protocol. */

  /* Allocate space for the bare network device struct. */
  net_dev = alloc_netdev(sizeof(softc_t), DEVICE_NAME"%d", setup_netdev);
  if (net_dev == NULL)
    {
    printk("%s: alloc_netdev() failed\n", DEVICE_NAME);
    return -ENOMEM;
    }
  /* device driver instance data, aka Soft Context or sc */
  sc = net_dev->priv;

# endif /* GEN_HDLC */

  sc->net_dev = net_dev;  /* NAME_UNIT macro needs this */
  sc->pci_dev = pci_dev;  /* READ/WRITE_PCI_CFG macros need this */

  /* Cross-link pci_dev and net_dev. */
  pci_set_drvdata(pci_dev, net_dev);      /* pci_dev->driver_data = net_dev */
  SET_NETDEV_DEV(net_dev, &pci_dev->dev); /* net_dev->class_dev.dev = &pci_dev->dev */
  SET_MODULE_OWNER(net_dev);              /* ??? NOOP in linux-2.6.3. ??? */

  /* Sets cfcs.io and cfcs.mem; sets pci_dev->irq based on cfit.int */
  if ((error = pci_enable_device(pci_dev)))
    {
    printk("%s: pci_enable_device() failed; error %d\n", DEVICE_NAME, error);
    linux_remove(pci_dev);
    return error;
    }
  net_dev->irq = pci_dev->irq; /* linux_open/stop need this */

  /* Allocate PCI memory and IO resources to access the Tulip chip CSRs. */
  if ((error = pci_request_regions(pci_dev, DEVICE_NAME)))
    {
    printk("%s: pci_request_regions() failed; error %d\n", DEVICE_NAME, error);
    linux_remove(pci_dev);
    return error;
    }
  net_dev->base_addr = pci_resource_start(pci_dev, 0);
  net_dev->mem_start = pci_resource_start(pci_dev, 1);
  net_dev->mem_end   = pci_resource_end(pci_dev, 1);
  sc->csr_iobase     = net_dev->base_addr;

# if (IOREF_CSR == 0)
  sc->csr_membase = ioremap_nocache(net_dev->mem_start, TLP_CSR_SIZE);
  if (sc->csr_membase == NULL)
    {
    printk("%s: ioremap_nocache() failed\n", DEVICE_NAME);
    linux_remove(pci_dev);
    return -EFAULT;
    }
# endif

  /* Sets cfcs.master, enabling PCI DMA; checks latency timer value. */
  pci_set_master(pci_dev); /* Later, attach_card() does this too. */

  /* Initialize the top-half and bottom-half locks. */
  /* Top_lock must be initialized before net_dev is registered. */
  init_MUTEX(&sc->top_lock);
  spin_lock_init(&sc->bottom_lock);

# if GEN_HDLC
  if ((error = register_hdlc_device(net_dev)))
    {
    printk("%s: register_hdlc_device() failed; error %d\n", DEVICE_NAME, error);
    linux_remove(pci_dev);
    return error;
    }
# else
  if ((error = register_netdev(net_dev)))
    {
    printk("%s: register_netdev() failed; error %d\n", DEVICE_NAME, error);
    linux_remove(pci_dev);
    return error;
    }
# endif
  /* The NAME_UNIT macro now works.  Use DEVICE_NAME before this. */
  sc->flags |= FLAG_NETDEV;

  /* What kind of card are we driving? */
  switch (READ_PCI_CFG(sc, TLP_CSID))
    {
    case TLP_CSID_HSSI:
    case TLP_CSID_HSSIc:
      sc->dev_desc =  HSSI_DESC;
      sc->card     = &hssi_card;
      break;
    case TLP_CSID_T3:
      sc->dev_desc =    T3_DESC;
      sc->card     =   &t3_card;
      break;
    case TLP_CSID_SSI:
      sc->dev_desc =   SSI_DESC;
      sc->card     =  &ssi_card;
      break;
    case TLP_CSID_T1E1:
      sc->dev_desc =  T1E1_DESC;
      sc->card     =   &t1_card;
      break;
    default: /* shouldn't happen! */
      linux_remove(pci_dev);
      return -ENXIO;
    }

  /* Announce the hardware on the console. */
  printk("%s: <%s> io 0x%04lx/9 mem 0x%08lx/25 rom 0x%08lx/14 irq %d pci %s\n",
   NAME_UNIT, sc->dev_desc, pci_resource_start(pci_dev, 0),
   pci_resource_start(pci_dev, 1), pci_resource_start(pci_dev, 6),
   pci_dev->irq, pci_name(pci_dev));

  return 0;
  }

/* This pci driver knows how to drive these devices: */
static __initdata struct pci_device_id pci_device_id_tbl[] =
  {
  /* Looking for a DEC 21140A chip on any Lan Media Corp card. */
    { 0x1011, 0x0009, 0x1376, PCI_ANY_ID, 0, 0, 0 },
    {      0,      0,      0,          0, 0, 0, 0 }
  };
MODULE_DEVICE_TABLE(pci, pci_device_id_tbl);

static struct pci_driver pci_driver =
  {
  .name	    = DEVICE_NAME,
  .id_table = pci_device_id_tbl,
  .probe    = linux_probe,
  .remove   = __devexit_p(linux_remove),
  /* This driver does not suspend and resume. */
  };

/* This ultimately calls our pci_driver.probe() method. */
static int  __init linux_modload(void)
  { return pci_module_init(&pci_driver); }
module_init(linux_modload);

/* This ultimately calls our pci_driver.remove() method. */
static void __exit linux_modunload(void)
  { pci_unregister_driver(&pci_driver); }
module_exit(linux_modunload);

MODULE_LICENSE("Dual BSD/GPL");
MODULE_DESCRIPTION("Device driver for SBE/LMC Wide-Area Network cards");
MODULE_AUTHOR("David Boggs <boggs@boggs.palo-alto.ca.us>");

#endif /* __linux__ */