aboutsummaryrefslogtreecommitdiffstats
path: root/arch/ia64/sn/io/l1.c
blob: fb7d48539e7843d90cdd195c679750dbb2139b57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
/* $Id$
 *
 * This file is subject to the terms and conditions of the GNU General Public
 * License.  See the file "COPYING" in the main directory of this archive
 * for more details.
 *
 * Copyright (C) 1992-1997, 2000-2002 Silicon Graphics, Inc.  All rights reserved.
 */

/* In general, this file is organized in a hierarchy from lower-level
 * to higher-level layers, as follows:
 *
 *	UART routines
 *	Bedrock/L1 "PPP-like" protocol implementation
 *	System controller "message" interface (allows multiplexing
 *		of various kinds of requests and responses with
 *		console I/O)
 *	Console interface:
 *	  "l1_cons", the glue that allows the L1 to act
 *		as the system console for the stdio libraries
 *
 * Routines making use of the system controller "message"-style interface
 * can be found in l1_command.c.
 */


#include <linux/types.h>
#include <linux/config.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <asm/sn/sgi.h>
#include <asm/sn/io.h>
#include <asm/sn/iograph.h>
#include <asm/sn/invent.h>
#include <asm/sn/hcl.h>
#include <asm/sn/hcl_util.h>
#include <asm/sn/labelcl.h>
#include <asm/sn/eeprom.h>
#include <asm/sn/router.h>
#include <asm/sn/module.h>
#include <asm/sn/ksys/l1.h>
#include <asm/sn/nodepda.h>
#include <asm/sn/clksupport.h>
#include <asm/sn/sn_sal.h>
#include <asm/sn/sn_cpuid.h>
#include <asm/sn/uart16550.h>
#include <asm/sn/simulator.h>


/* Make all console writes atomic */
#define SYNC_CONSOLE_WRITE	1


/*********************************************************************
 * Hardware-level (UART) driver routines.
 */

/* macros for reading/writing registers */

#define LD(x)			(*(volatile uint64_t *)(x))
#define SD(x, v)        	(LD(x) = (uint64_t) (v))

/* location of uart receive/xmit data register */
#if defined(CONFIG_IA64_SGI_SN1)
#define L1_UART_BASE(n)		((ulong)REMOTE_HSPEC_ADDR((n), 0x00000080))
#define LOCK_HUB		REMOTE_HUB_ADDR
#elif defined(CONFIG_IA64_SGI_SN2)
#define L1_UART_BASE(n)		((ulong)REMOTE_HUB((n), SH_JUNK_BUS_UART0))
#define LOCK_HUB		REMOTE_HUB
typedef u64 rtc_time_t;
#endif


#define ADDR_L1_REG(n, r)	( L1_UART_BASE(n) | ( (r) << 3 ) )
#define READ_L1_UART_REG(n, r)	( LD(ADDR_L1_REG((n), (r))) )
#define WRITE_L1_UART_REG(n, r, v) ( SD(ADDR_L1_REG((n), (r)), (v)) )

/* upper layer interface calling methods */
#define SERIAL_INTERRUPT_MODE	0
#define SERIAL_POLLED_MODE	1


/* UART-related #defines */

#define UART_BAUD_RATE		57600
#define UART_FIFO_DEPTH		16
#define UART_DELAY_SPAN		10
#define UART_PUTC_TIMEOUT	50000
#define UART_INIT_TIMEOUT	100000

/* error codes */
#define UART_SUCCESS		  0
#define UART_TIMEOUT		(-1)
#define UART_LINK		(-2)
#define UART_NO_CHAR		(-3)
#define UART_VECTOR		(-4)

#define UART_DELAY(x)		udelay(x)

/* Some debug counters */
#define L1C_INTERRUPTS		0
#define L1C_OUR_R_INTERRUPTS	1
#define L1C_OUR_X_INTERRUPTS	2
#define L1C_SEND_CALLUPS	3
#define L1C_RECEIVE_CALLUPS	4
#define L1C_SET_BAUD		5
#define L1C_ALREADY_LOCKED	L1C_SET_BAUD
#define L1C_R_IRQ		6
#define L1C_R_IRQ_RET		7
#define L1C_LOCK_TIMEOUTS	8
#define L1C_LOCK_COUNTER	9
#define L1C_UNLOCK_COUNTER	10
#define L1C_REC_STALLS		11
#define L1C_CONNECT_CALLS	12
#define L1C_SIZE		L1C_CONNECT_CALLS	/* Set to the last one */

uint64_t L1_collectibles[L1C_SIZE + 1];


/*
 *	Some macros for handling Endian-ness
 */

#define COPY_INT_TO_BUFFER(_b, _i, _n)		\
	{					\
		_b[_i++] = (_n >> 24) & 0xff;	\
		_b[_i++] = (_n >> 16) & 0xff;	\
		_b[_i++] = (_n >>  8) & 0xff;	\
		_b[_i++] =  _n        & 0xff;	\
	}

#define COPY_BUFFER_TO_INT(_b, _i, _n)		\
	{					\
		_n  = (_b[_i++] << 24) & 0xff;	\
		_n |= (_b[_i++] << 16) & 0xff;	\
		_n |= (_b[_i++] <<  8) & 0xff;	\
		_n |=  _b[_i++]        & 0xff;	\
	}

#define COPY_BUFFER_TO_BUFFER(_b, _i, _bn)	\
	{					\
	    char *_xyz = (char *)_bn;		\
	    _xyz[3] = _b[_i++];			\
	    _xyz[2] = _b[_i++];			\
	    _xyz[1] = _b[_i++];			\
	    _xyz[0] = _b[_i++];			\
	}

void snia_kmem_free(void *where, int size);

#define ALREADY_LOCKED		1
#define NOT_LOCKED		0
static int early_l1_serial_out(nasid_t, char *, int, int /* defines above*/ );

#define BCOPY(x,y,z)	memcpy(y,x,z)

uint8_t L1_interrupts_connected;		/* Non-zero when we are in interrupt mode */


/*
 * Console locking defines and functions.
 *
 */

uint8_t L1_cons_is_inited = 0;			/* non-zero when console is init'd */
nasid_t Master_console_nasid = (nasid_t)-1;
extern nasid_t console_nasid;

u64 ia64_sn_get_console_nasid(void);

inline nasid_t
get_master_nasid(void)
{
#if defined(CONFIG_IA64_SGI_SN1)
	nasid_t nasid = Master_console_nasid;

	if ( nasid == (nasid_t)-1 ) {
		nasid = (nasid_t)ia64_sn_get_console_nasid();
		if ( (nasid < 0) || (nasid >= MAX_NASIDS) ) {
			/* Out of bounds, use local */
			console_nasid = nasid = get_nasid();
		}
		else {
			/* Got a valid nasid, set the console_nasid */
			char xx[100];
/* zzzzzz - force nasid to 0 for now */
			sprintf(xx, "Master console is set to nasid %d (%d)\n", 0, (int)nasid);
nasid = 0;
/* end zzzzzz */
			xx[99] = (char)0;
			early_l1_serial_out(nasid, xx, strlen(xx), NOT_LOCKED);
			Master_console_nasid = console_nasid = nasid;
		}
	}
	return(nasid);
#else
	return((nasid_t)0);
#endif	/* CONFIG_IA64_SGI_SN1 */
}


#if defined(CONFIG_IA64_SGI_SN1)

#define HUB_LOCK		16

#define PRIMARY_LOCK_TIMEOUT    10000000
#define HUB_LOCK_REG(n)         LOCK_HUB(n, MD_PERF_CNT0)

#define SET_BITS(reg, bits)     SD(reg, LD(reg) |  (bits))
#define CLR_BITS(reg, bits)     SD(reg, LD(reg) & ~(bits))
#define TST_BITS(reg, bits)     ((LD(reg) & (bits)) != 0)

#define HUB_TEST_AND_SET(n)	LD(LOCK_HUB(n,LB_SCRATCH_REG3_RZ))
#define HUB_CLEAR(n)		SD(LOCK_HUB(n,LB_SCRATCH_REG3),0)

#define RTC_TIME_MAX		((rtc_time_t) ~0ULL)

/*
 * primary_lock
 *
 *   Allows CPU's 0-3  to mutually exclude the hub from one another by
 *   obtaining a blocking lock.  Does nothing if only one CPU is active.
 *
 *   This lock should be held just long enough to set or clear a global
 *   lock bit.  After a relatively short timeout period, this routine
 *   figures something is wrong, and steals the lock. It does not set
 *   any other CPU to "dead".
 */
inline void
primary_lock(nasid_t nasid)
{
	rtc_time_t          expire;

	expire = rtc_time() + PRIMARY_LOCK_TIMEOUT;

	while (HUB_TEST_AND_SET(nasid)) {
		if (rtc_time() > expire) {
			HUB_CLEAR(nasid);
		}
	}
}

/*
 * primary_unlock (internal)
 *
 *   Counterpart to primary_lock
 */

inline void
primary_unlock(nasid_t nasid)
{
	HUB_CLEAR(nasid);
}

/*
 * hub_unlock
 *
 *   Counterpart to hub_lock_timeout and hub_lock
 */

inline void
hub_unlock(nasid_t nasid, int level)
{
	uint64_t mask = 1ULL << level;

	primary_lock(nasid);
	CLR_BITS(HUB_LOCK_REG(nasid), mask);
	primary_unlock(nasid);
}

/*
 * hub_lock_timeout
 *
 *   Uses primary_lock to implement multiple lock levels.
 *
 *   There are 20 lock levels from 0 to 19 (limited by the number of bits
 *   in HUB_LOCK_REG).  To prevent deadlock, multiple locks should be
 *   obtained in order of increasingly higher level, and released in the
 *   reverse order.
 *
 *   A timeout value of 0 may be used for no timeout.
 *
 *   Returns 0 if successful, -1 if lock times out.
 */

inline int
hub_lock_timeout(nasid_t nasid, int level, rtc_time_t timeout)
{
	uint64_t mask = 1ULL << level;
	rtc_time_t expire = (timeout ?  rtc_time() + timeout : RTC_TIME_MAX);
	int done    = 0;

	while (! done) {
		while (TST_BITS(HUB_LOCK_REG(nasid), mask)) {
			if (rtc_time() > expire)
				return -1;
		}

		primary_lock(nasid);

		if (! TST_BITS(HUB_LOCK_REG(nasid), mask)) {
			SET_BITS(HUB_LOCK_REG(nasid), mask);
			done = 1;
		}
		primary_unlock(nasid);
	}
	return 0;
}


#define LOCK_TIMEOUT	(0x1500000 * 1) /* 0x1500000 is ~30 sec */

void
lock_console(nasid_t nasid)
{
	int ret;

	/* If we already have it locked, just return */
	L1_collectibles[L1C_LOCK_COUNTER]++;

	ret = hub_lock_timeout(nasid, HUB_LOCK, (rtc_time_t)LOCK_TIMEOUT);
	if ( ret != 0 ) {
		L1_collectibles[L1C_LOCK_TIMEOUTS]++;
		/* timeout */
		hub_unlock(nasid, HUB_LOCK);
		/* If the 2nd lock fails, just pile ahead.... */
		hub_lock_timeout(nasid, HUB_LOCK, (rtc_time_t)LOCK_TIMEOUT);
		L1_collectibles[L1C_LOCK_TIMEOUTS]++;
	}
}

inline void
unlock_console(nasid_t nasid)
{
	L1_collectibles[L1C_UNLOCK_COUNTER]++;
	hub_unlock(nasid, HUB_LOCK);
}

#else /* SN2 */
inline void lock_console(nasid_t n)	{}
inline void unlock_console(nasid_t n)	{}

#endif	/* CONFIG_IA64_SGI_SN1 */

int 
get_L1_baud(void)
{
    return UART_BAUD_RATE;
}


/* uart driver functions */

static inline void
uart_delay( rtc_time_t delay_span )
{
    UART_DELAY( delay_span );
}

#define UART_PUTC_READY(n)      (READ_L1_UART_REG((n), REG_LSR) & LSR_XHRE)

static int
uart_putc( l1sc_t *sc ) 
{
    WRITE_L1_UART_REG( sc->nasid, REG_DAT, sc->send[sc->sent] );
    return UART_SUCCESS;
}


static int
uart_getc( l1sc_t *sc )
{
    u_char lsr_reg = 0;
    nasid_t nasid = sc->nasid;

    if( (lsr_reg = READ_L1_UART_REG( nasid, REG_LSR )) & 
	(LSR_RCA | LSR_PARERR | LSR_FRMERR) ) 
    {
	if( lsr_reg & LSR_RCA ) 
	    return( (u_char)READ_L1_UART_REG( nasid, REG_DAT ) );
	else if( lsr_reg & (LSR_PARERR | LSR_FRMERR) ) {
	    return UART_LINK;
	}
    }

    return UART_NO_CHAR;
}


#define PROM_SER_CLK_SPEED	12000000
#define PROM_SER_DIVISOR(x)	(PROM_SER_CLK_SPEED / ((x) * 16))

static void
uart_init( l1sc_t *sc, int baud )
{
    rtc_time_t expire;
    int clkdiv;
    nasid_t nasid;

    clkdiv = PROM_SER_DIVISOR(baud);
    expire = rtc_time() + UART_INIT_TIMEOUT;
    nasid = sc->nasid;
    
    /* make sure the transmit FIFO is empty */
    while( !(READ_L1_UART_REG( nasid, REG_LSR ) & LSR_XSRE) ) {
	uart_delay( UART_DELAY_SPAN );
	if( rtc_time() > expire ) {
	    break;
	}
    }

    if ( sc->uart == BRL1_LOCALHUB_UART )
	lock_console(nasid);

    /* Setup for the proper baud rate */
    WRITE_L1_UART_REG( nasid, REG_LCR, LCR_DLAB );
	uart_delay( UART_DELAY_SPAN );
    WRITE_L1_UART_REG( nasid, REG_DLH, (clkdiv >> 8) & 0xff );
	uart_delay( UART_DELAY_SPAN );
    WRITE_L1_UART_REG( nasid, REG_DLL, clkdiv & 0xff );
	uart_delay( UART_DELAY_SPAN );

    /* set operating parameters and set DLAB to 0 */

    /* 8bit, one stop, clear request to send, auto flow control */
    WRITE_L1_UART_REG( nasid, REG_LCR, LCR_BITS8 | LCR_STOP1 );
	uart_delay( UART_DELAY_SPAN );
    WRITE_L1_UART_REG( nasid, REG_MCR, MCR_RTS | MCR_AFE );
	uart_delay( UART_DELAY_SPAN );

    /* disable interrupts */
    WRITE_L1_UART_REG( nasid, REG_ICR, 0x0 );
	uart_delay( UART_DELAY_SPAN );

    /* enable FIFO mode and reset both FIFOs, trigger on 1 */
    WRITE_L1_UART_REG( nasid, REG_FCR, FCR_FIFOEN );
	uart_delay( UART_DELAY_SPAN );
    WRITE_L1_UART_REG( nasid, REG_FCR, FCR_FIFOEN | FCR_RxFIFO | FCR_TxFIFO | RxLVL0);

    if ( sc->uart == BRL1_LOCALHUB_UART )
	unlock_console(nasid);
}

/* This requires the console lock */

#if	defined(CONFIG_IA64_SGI_SN1)

static void
uart_intr_enable( l1sc_t *sc, u_char mask )
{
    u_char lcr_reg, icr_reg;
    nasid_t nasid = sc->nasid;

    if ( sc->uart == BRL1_LOCALHUB_UART )
	lock_console(nasid);

    /* make sure that the DLAB bit in the LCR register is 0
     */
    lcr_reg = READ_L1_UART_REG( nasid, REG_LCR );
    lcr_reg &= ~(LCR_DLAB);
    WRITE_L1_UART_REG( nasid, REG_LCR, lcr_reg );

    /* enable indicated interrupts
     */
    icr_reg = READ_L1_UART_REG( nasid, REG_ICR );
    icr_reg |= mask;
    WRITE_L1_UART_REG( nasid, REG_ICR, icr_reg /*(ICR_RIEN | ICR_TIEN)*/ );

    if ( sc->uart == BRL1_LOCALHUB_UART )
	unlock_console(nasid);
}

/* This requires the console lock */
static void
uart_intr_disable( l1sc_t *sc, u_char mask )
{
    u_char lcr_reg, icr_reg;
    nasid_t nasid = sc->nasid;

    if ( sc->uart == BRL1_LOCALHUB_UART )
	lock_console(nasid);

    /* make sure that the DLAB bit in the LCR register is 0
     */
    lcr_reg = READ_L1_UART_REG( nasid, REG_LCR );
    lcr_reg &= ~(LCR_DLAB);
    WRITE_L1_UART_REG( nasid, REG_LCR, lcr_reg );

    /* enable indicated interrupts
     */
    icr_reg = READ_L1_UART_REG( nasid, REG_ICR );
    icr_reg &= mask;
    WRITE_L1_UART_REG( nasid, REG_ICR, icr_reg /*(ICR_RIEN | ICR_TIEN)*/ );

    if ( sc->uart == BRL1_LOCALHUB_UART )
	unlock_console(nasid);
}
#endif	/* CONFIG_IA64_SGI_SN1 */

#define uart_enable_xmit_intr(sc) \
	uart_intr_enable((sc), ICR_TIEN)

#define uart_disable_xmit_intr(sc) \
        uart_intr_disable((sc), ~(ICR_TIEN))

#define uart_enable_recv_intr(sc) \
        uart_intr_enable((sc), ICR_RIEN)

#define uart_disable_recv_intr(sc) \
        uart_intr_disable((sc), ~(ICR_RIEN))


/*********************************************************************
 * Routines for accessing a remote (router) UART
 */

#define READ_RTR_L1_UART_REG(p, n, r, v)		\
    {							\
	if( vector_read_node( (p), (n), 0,		\
			      RR_JBUS1(r), (v) ) ) {	\
	    return UART_VECTOR;				\
	}						\
    }

#define WRITE_RTR_L1_UART_REG(p, n, r, v)		\
    {							\
	if( vector_write_node( (p), (n), 0,		\
			       RR_JBUS1(r), (v) ) ) {	\
	    return UART_VECTOR;				\
	}						\
    }

#define RTR_UART_PUTC_TIMEOUT	UART_PUTC_TIMEOUT*10
#define RTR_UART_DELAY_SPAN	UART_DELAY_SPAN
#define RTR_UART_INIT_TIMEOUT	UART_INIT_TIMEOUT*10

static int
rtr_uart_putc( l1sc_t *sc )
{
    uint64_t regval, c;
    nasid_t nasid = sc->nasid;
    net_vec_t path = sc->uart;
    rtc_time_t expire = rtc_time() + RTR_UART_PUTC_TIMEOUT;

    c = (sc->send[sc->sent] & 0xffULL);
    
    while( 1 ) 
    {
        /* Check for "tx hold reg empty" bit. */
	READ_RTR_L1_UART_REG( path, nasid, REG_LSR, &regval );
	if( regval & LSR_XHRE )
	{
	    WRITE_RTR_L1_UART_REG( path, nasid, REG_DAT, c );
	    return UART_SUCCESS;
	}

	if( rtc_time() >= expire ) 
	{
	    return UART_TIMEOUT;
	}
	uart_delay( RTR_UART_DELAY_SPAN );
    }
}


static int
rtr_uart_getc( l1sc_t *sc )
{
    uint64_t regval;
    nasid_t nasid = sc->nasid;
    net_vec_t path = sc->uart;

    READ_RTR_L1_UART_REG( path, nasid, REG_LSR, &regval );
    if( regval & (LSR_RCA | LSR_PARERR | LSR_FRMERR) )
    {
	if( regval & LSR_RCA )
	{
	    READ_RTR_L1_UART_REG( path, nasid, REG_DAT, &regval );
	    return( (int)regval );
	}
	else
	{
	    return UART_LINK;
	}
    }

    return UART_NO_CHAR;
}


static int
rtr_uart_init( l1sc_t *sc, int baud )
{
    rtc_time_t expire;
    int clkdiv;
    nasid_t nasid;
    net_vec_t path;
    uint64_t regval;

    clkdiv = PROM_SER_DIVISOR(baud);
    expire = rtc_time() + RTR_UART_INIT_TIMEOUT;
    nasid = sc->nasid;
    path = sc->uart;

    /* make sure the transmit FIFO is empty */
    while(1) {
	READ_RTR_L1_UART_REG( path, nasid, REG_LSR, &regval );
	if( regval & LSR_XSRE ) {
	    break;
	}
	if( rtc_time() > expire ) {
	    break;
	}
	uart_delay( RTR_UART_DELAY_SPAN );
    }

    WRITE_RTR_L1_UART_REG( path, nasid, REG_LCR, LCR_DLAB  );
	uart_delay( UART_DELAY_SPAN );
    WRITE_RTR_L1_UART_REG( path, nasid, REG_DLH, (clkdiv >> 8) & 0xff  );
	uart_delay( UART_DELAY_SPAN );
    WRITE_RTR_L1_UART_REG( path, nasid, REG_DLL, clkdiv & 0xff  );
	uart_delay( UART_DELAY_SPAN );

    /* set operating parameters and set DLAB to 0 */
    WRITE_RTR_L1_UART_REG( path, nasid, REG_LCR, LCR_BITS8 | LCR_STOP1  );
	uart_delay( UART_DELAY_SPAN );
    WRITE_RTR_L1_UART_REG( path, nasid, REG_MCR, MCR_RTS | MCR_AFE  );
	uart_delay( UART_DELAY_SPAN );

    /* disable interrupts */
    WRITE_RTR_L1_UART_REG( path, nasid, REG_ICR, 0x0  );
	uart_delay( UART_DELAY_SPAN );

    /* enable FIFO mode and reset both FIFOs */
    WRITE_RTR_L1_UART_REG( path, nasid, REG_FCR, FCR_FIFOEN  );
	uart_delay( UART_DELAY_SPAN );
    WRITE_RTR_L1_UART_REG( path, nasid, REG_FCR,
	FCR_FIFOEN | FCR_RxFIFO | FCR_TxFIFO );

    return 0;
}

/*********************************************************************
 * locking macros 
 */

#define L1SC_SEND_LOCK(l,p)   { if ((l)->uart == BRL1_LOCALHUB_UART) spin_lock_irqsave(&((l)->send_lock),p); }
#define L1SC_SEND_UNLOCK(l,p) { if ((l)->uart == BRL1_LOCALHUB_UART) spin_unlock_irqrestore(&((l)->send_lock), p); }
#define L1SC_RECV_LOCK(l,p)   { if ((l)->uart == BRL1_LOCALHUB_UART) spin_lock_irqsave(&((l)->recv_lock), p); } 
#define L1SC_RECV_UNLOCK(l,p) { if ((l)->uart == BRL1_LOCALHUB_UART) spin_unlock_irqrestore(&((l)->recv_lock), p); }


/*********************************************************************
 * subchannel manipulation 
 *
 * The SUBCH_[UN]LOCK macros are used to arbitrate subchannel
 * allocation.  SUBCH_DATA_[UN]LOCK control access to data structures
 * associated with particular subchannels (e.g., receive queues).
 *
 */
#define SUBCH_LOCK(sc, p)		spin_lock_irqsave( &((sc)->subch_lock), p )
#define SUBCH_UNLOCK(sc, p)		spin_unlock_irqrestore( &((sc)->subch_lock), p )
#define SUBCH_DATA_LOCK(sbch, p) 	spin_lock_irqsave( &((sbch)->data_lock), p )
#define SUBCH_DATA_UNLOCK(sbch, p)	spin_unlock_irqrestore( &((sbch)->data_lock), p )


/*
 * set a function to be called for subchannel ch in the event of
 * a transmission low-water interrupt from the uart
 */
void
subch_set_tx_notify( l1sc_t *sc, int ch, brl1_notif_t func )
{
    unsigned long pl = 0;

    L1SC_SEND_LOCK( sc, pl );
#if	!defined(SYNC_CONSOLE_WRITE)
    if ( func && !sc->send_in_use )
	uart_enable_xmit_intr( sc );
#endif
    sc->subch[ch].tx_notify = func;
    L1SC_SEND_UNLOCK(sc, pl );
}

/*
 * set a function to be called for subchannel ch when data is received
 */
void
subch_set_rx_notify( l1sc_t *sc, int ch, brl1_notif_t func )
{
    unsigned long pl = 0;
    brl1_sch_t *subch = &(sc->subch[ch]);

    SUBCH_DATA_LOCK( subch, pl );
    sc->subch[ch].rx_notify = func;
    SUBCH_DATA_UNLOCK( subch, pl );
}

/*********************************************************************
 * Queue manipulation macros
 *
 *
 */
#define NEXT(p)         (((p) + 1) & (BRL1_QSIZE-1)) /* assume power of 2 */

#define cq_init(q)      bzero((q), sizeof (*(q)))
#define cq_empty(q)     ((q)->ipos == (q)->opos)
#define cq_full(q)      (NEXT((q)->ipos) == (q)->opos)
#define cq_used(q)      ((q)->opos <= (q)->ipos ?                       \
                         (q)->ipos - (q)->opos :                        \
                         BRL1_QSIZE + (q)->ipos - (q)->opos)
#define cq_room(q)      ((q)->opos <= (q)->ipos ?                       \
                         BRL1_QSIZE - 1 + (q)->opos - (q)->ipos :       \
                         (q)->opos - (q)->ipos - 1)
#define cq_add(q, c)    ((q)->buf[(q)->ipos] = (u_char) (c),            \
                         (q)->ipos = NEXT((q)->ipos))
#define cq_rem(q, c)    ((c) = (q)->buf[(q)->opos],                     \
                         (q)->opos = NEXT((q)->opos))
#define cq_discard(q)	((q)->opos = NEXT((q)->opos))

#define cq_tent_full(q)	(NEXT((q)->tent_next) == (q)->opos)
#define cq_tent_len(q)	((q)->ipos <= (q)->tent_next ?			\
			 (q)->tent_next - (q)->ipos :			\
			 BRL1_QSIZE + (q)->tent_next - (q)->ipos)
#define cq_tent_add(q, c)						\
			((q)->buf[(q)->tent_next] = (u_char) (c),	\
			 (q)->tent_next = NEXT((q)->tent_next))
#define cq_commit_tent(q)						\
			((q)->ipos = (q)->tent_next)
#define cq_discard_tent(q)						\
			((q)->tent_next = (q)->ipos)




/*********************************************************************
 * CRC-16 (for checking bedrock/L1 packets).
 *
 * These are based on RFC 1662 ("PPP in HDLC-like framing").
 */

static unsigned short fcstab[256] = {
      0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
      0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
      0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
      0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
      0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
      0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
      0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
      0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
      0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
      0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
      0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
      0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
      0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
      0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
      0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
      0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
      0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
      0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
      0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
      0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
      0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
      0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
      0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
      0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
      0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
      0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
      0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
      0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
      0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
      0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
      0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
      0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
};

#define INIT_CRC	0xFFFF	/* initial CRC value	  */
#define	GOOD_CRC	0xF0B8	/* "good" final CRC value */

static unsigned short crc16_calc( unsigned short crc, u_char c )
{
    return( (crc >> 8) ^ fcstab[(crc ^ c) & 0xff] );
}


/***********************************************************************
 * The following functions implement the PPP-like bedrock/L1 protocol
 * layer.
 *
 */

#define BRL1_FLAG_CH	0x7e
#define BRL1_ESC_CH	0x7d
#define BRL1_XOR_CH	0x20

/* L1<->Bedrock packet types */
#define BRL1_REQUEST    0x00
#define BRL1_RESPONSE   0x20
#define BRL1_EVENT      0x40

#define BRL1_PKT_TYPE_MASK      0xE0
#define BRL1_SUBCH_MASK         0x1F

#define PKT_TYPE(tsb)   ((tsb) & BRL1_PKT_TYPE_MASK)
#define SUBCH(tsb)	((tsb) & BRL1_SUBCH_MASK)

/* timeouts */
#define BRL1_INIT_TIMEOUT	500000

/*
 * brl1_discard_packet is a dummy "receive callback" used to get rid
 * of packets we don't want
 */
void brl1_discard_packet( int dummy0, void *dummy1, struct pt_regs *dummy2, l1sc_t *sc, int ch )
{
    unsigned long pl = 0;
    brl1_sch_t *subch = &sc->subch[ch];

    sc_cq_t *q = subch->iqp;
    SUBCH_DATA_LOCK( subch, pl );
    q->opos = q->ipos;
    atomic_set(&(subch->packet_arrived), 0);
    SUBCH_DATA_UNLOCK( subch, pl );
}


/*
 * brl1_send_chars sends the send buffer in the l1sc_t structure
 * out through the uart.  Assumes that the caller has locked the
 * UART (or send buffer in the kernel).
 *
 * This routine doesn't block-- if you want it to, call it in
 * a loop.
 */
static int
brl1_send_chars( l1sc_t *sc )
{
    /* We track the depth of the C brick's UART's
     * fifo in software, and only check if the UART is accepting
     * characters when our count indicates that the fifo should
     * be full.
     *
     * For remote (router) UARTs, we check with the UART before sending every
     * character.
     */
    if( sc->uart == BRL1_LOCALHUB_UART ) {
	if( !(sc->fifo_space) && UART_PUTC_READY( sc->nasid ) )
	    sc->fifo_space = UART_FIFO_DEPTH;
	
	while( (sc->sent < sc->send_len) && (sc->fifo_space) ) {
	    uart_putc( sc );
	    sc->fifo_space--;
	    sc->sent++;
	}
    }
    else {

	/* remote (router) UARTs */

	int result;
	int tries = 0;

	while( sc->sent < sc->send_len ) {
	    result = sc->putc_f( sc );
	    if( result >= 0 ) {
		(sc->sent)++;
		continue;
	    }
	    if( result == UART_TIMEOUT ) {
		tries++;
		/* send this character in TIMEOUT_RETRIES... */
		if( tries < 30 /* TIMEOUT_RETRIES */ ) {
		    continue;
		}
		/* ...or else... */
		else {
		    /* ...drop the packet. */
		    sc->sent = sc->send_len;
		    return sc->send_len;
		}
	    }
	    if( result < 0 ) {
		return result;
	    }
	}
    }
    return sc->sent;
}


/* brl1_send formats up a packet and (at least begins to) send it
 * to the uart.  If the send buffer is in use when this routine obtains
 * the lock, it will behave differently depending on the "wait" parameter.
 * For wait == 0 (most I/O), it will return 0 (as in "zero bytes sent"),
 * hopefully encouraging the caller to back off (unlock any high-level 
 * spinlocks) and allow the buffer some time to drain.  For wait==1 (high-
 * priority I/O along the lines of kernel error messages), we will flush
 * the current contents of the send buffer and beat on the uart
 * until our message has been completely transmitted.
 */

static int
brl1_send( l1sc_t *sc, char *msg, int len, u_char type_and_subch, int wait )
{
    unsigned long pl = 0;
    int index;
    int pkt_len = 0;
    unsigned short crc = INIT_CRC;
    char *send_ptr = sc->send;


    if( sc->send_in_use && !(wait) ) {
	/* We are in the middle of sending, but can wait until done */
	return 0;
    }
    else if( sc->send_in_use ) {
	/* buffer's in use, but we're synchronous I/O, so we're going
	 * to send whatever's in there right now and take the buffer
	 */
	int counter = 0;

	if ( sc->uart == BRL1_LOCALHUB_UART )
		lock_console(sc->nasid);
	L1SC_SEND_LOCK(sc, pl);
	while( sc->sent < sc->send_len ) {
		brl1_send_chars( sc );
		if ( counter++ > 0xfffff ) {
			char *str = "Looping waiting for uart to clear (1)\n";
			early_l1_serial_out(sc->nasid, str, strlen(str), ALREADY_LOCKED);
			break;
		}
	}
    }
    else {
	if ( sc->uart == BRL1_LOCALHUB_UART )
		lock_console(sc->nasid);
	L1SC_SEND_LOCK(sc, pl);
	sc->send_in_use = 1;
    }
    *send_ptr++ = BRL1_FLAG_CH;
    *send_ptr++ = type_and_subch;
    pkt_len += 2;
    crc = crc16_calc( crc, type_and_subch );

    /* limit number of characters accepted to max payload size */
    if( len > (BRL1_QSIZE - 1) )
	len = (BRL1_QSIZE - 1);

    /* copy in the message buffer (inserting PPP 
     * framing info where necessary)
     */
    for( index = 0; index < len; index++ ) {

	switch( *msg ) {
	    
	  case BRL1_FLAG_CH:
	    *send_ptr++ = BRL1_ESC_CH;
	    *send_ptr++ = (*msg) ^ BRL1_XOR_CH;
	    pkt_len += 2;
	    break;
	    
	  case BRL1_ESC_CH:
	    *send_ptr++ = BRL1_ESC_CH;
	    *send_ptr++ = (*msg) ^ BRL1_XOR_CH;
	    pkt_len += 2;
	    break;
	    
	  default:
	    *send_ptr++ = *msg;
	    pkt_len++;
	}
	crc = crc16_calc( crc, *msg );
	msg++;
    }
    crc ^= 0xffff;

    for( index = 0; index < sizeof(crc); index++ ) {
	char crc_char = (char)(crc & 0x00FF);
	if( (crc_char == BRL1_ESC_CH) || (crc_char == BRL1_FLAG_CH) ) {
	    *send_ptr++ = BRL1_ESC_CH;
	    pkt_len++;
	    crc_char ^= BRL1_XOR_CH;
	}
	*send_ptr++ = crc_char;
	pkt_len++;
	crc >>= 8;
    }
    
    *send_ptr++ = BRL1_FLAG_CH;
    pkt_len++;

    sc->send_len = pkt_len;
    sc->sent = 0;

    {
	int counter = 0;
	do {
		brl1_send_chars( sc );
		if ( counter++ > 0xfffff ) {
			char *str = "Looping waiting for uart to clear (2)\n";
			early_l1_serial_out(sc->nasid, str, strlen(str), ALREADY_LOCKED);
			break;
		}
	} while( (sc->sent < sc->send_len) && wait );
    }

    if ( sc->uart == BRL1_LOCALHUB_UART )
	unlock_console(sc->nasid);

    if( sc->sent == sc->send_len ) {
	/* success! release the send buffer and call the callup */
#if	!defined(SYNC_CONSOLE_WRITE)
	brl1_notif_t callup;
#endif

	sc->send_in_use = 0;
	/* call any upper layer that's asked for notification */
#if	defined(XX_SYNC_CONSOLE_WRITE)
	/*
	 * This is probably not a good idea - since the l1_ write func can be called multiple
	 * time within the callup function.
	 */
	callup = subch->tx_notify;
	if( callup && (SUBCH(type_and_subch) == SC_CONS_SYSTEM) ) {
		L1_collectibles[L1C_SEND_CALLUPS]++;
		(*callup)(sc->subch[SUBCH(type_and_subch)].irq_frame.bf_irq,
				sc->subch[SUBCH(type_and_subch)].irq_frame.bf_dev_id,
				sc->subch[SUBCH(type_and_subch)].irq_frame.bf_regs, sc, SUBCH(type_and_subch));
	}
#endif	/* SYNC_CONSOLE_WRITE */
    }
#if	!defined(SYNC_CONSOLE_WRITE)
    else if ( !wait ) {
	/* enable low-water interrupts so buffer will be drained */
	uart_enable_xmit_intr(sc);
    }
#endif

    L1SC_SEND_UNLOCK(sc, pl);

    return len;
}

/* brl1_send_cont is intended to be called as an interrupt service
 * routine.  It sends until the UART won't accept any more characters,
 * or until an error is encountered (in which case we surrender the
 * send buffer and give up trying to send the packet).  Once the
 * last character in the packet has been sent, this routine releases
 * the send buffer and calls any previously-registered "low-water"
 * output routines.
 */

#if	!defined(SYNC_CONSOLE_WRITE)

int
brl1_send_cont( l1sc_t *sc )
{
    unsigned long pl = 0;
    int done = 0;
    brl1_notif_t callups[BRL1_NUM_SUBCHANS];
    brl1_notif_t *callup;
    brl1_sch_t *subch;
    int index;

    /*
     * I'm not sure how I think this is to be handled - whether the lock is held
     * over the interrupt - but it seems like it is a bad idea....
     */

    if ( sc->uart == BRL1_LOCALHUB_UART )
	lock_console(sc->nasid);
    L1SC_SEND_LOCK(sc, pl);
    brl1_send_chars( sc );
    done = (sc->sent == sc->send_len);
    if( done ) {
	sc->send_in_use = 0;
#if	!defined(SYNC_CONSOLE_WRITE)
	uart_disable_xmit_intr(sc);
#endif
    }
    if ( sc->uart == BRL1_LOCALHUB_UART )
	unlock_console(sc->nasid);
    /* Release the lock */
    L1SC_SEND_UNLOCK(sc, pl);

    return 0;
}
#endif	/* SYNC_CONSOLE_WRITE */

/* internal function -- used by brl1_receive to read a character 
 * from the uart and check whether errors occurred in the process.
 */
static int
read_uart( l1sc_t *sc, int *c, int *result )
{
    *c = sc->getc_f( sc );

    /* no character is available */
    if( *c == UART_NO_CHAR ) {
	*result = BRL1_NO_MESSAGE;
	return 0;
    }

    /* some error in UART */
    if( *c < 0 ) {
	*result = BRL1_LINK;
	return 0;
    }

    /* everything's fine */
    *result = BRL1_VALID;
    return 1;
}


/*
 * brl1_receive
 *
 * This function reads a Bedrock-L1 protocol packet into the l1sc_t
 * response buffer.
 *
 * The operation of this function can be expressed as a finite state
 * machine:
 *

START STATE			INPUT		TRANSITION
==========================================================
BRL1_IDLE (reset or error)	flag		BRL1_FLAG
				other		BRL1_IDLE@

BRL1_FLAG (saw a flag (0x7e))	flag		BRL1_FLAG
				escape		BRL1_IDLE@
				header byte	BRL1_HDR
				other		BRL1_IDLE@

BRL1_HDR (saw a type/subch byte)(see below)	BRL1_BODY
						BRL1_HDR

BRL1_BODY (reading packet body)	flag		BRL1_FLAG
				escape		BRL1_ESC
				other		BRL1_BODY

BRL1_ESC (saw an escape (0x7d))	flag		BRL1_FLAG@
				escape		BRL1_IDLE@
				other		BRL1_BODY
==========================================================

"@" denotes an error transition.

 * The BRL1_HDR state is a transient state which doesn't read input,
 * but just provides a way in to code which decides to whom an
 * incoming packet should be directed.
 *
 * brl1_receive can be used to poll for input from the L1, or as 
 * an interrupt service routine.  It reads as much data as is
 * ready from the junk bus UART and places into the appropriate
 * input queues according to subchannel.  The header byte is
 * stripped from console-type data, but is retained for message-
 * type data (L1 responses).  A length byte will also be
 * prepended to message-type packets.
 *
 * This routine is non-blocking; if the caller needs to block
 * for input, it must call brl1_receive in a loop.
 *
 * brl1_receive returns when there is no more input, the queue
 * for the current incoming message is full, or there is an
 * error (parity error, bad header, bad CRC, etc.).
 */

#define STATE_SET(l,s)		((l)->brl1_state = (s))
#define STATE_GET(l)		((l)->brl1_state)

#define LAST_HDR_SET(l,h)	((l)->brl1_last_hdr = (h))
#define LAST_HDR_GET(l)		((l)->brl1_last_hdr)

#define VALID_HDR(c)				\
    ( SUBCH((c)) <= SC_CONS_SYSTEM		\
	? PKT_TYPE((c)) == BRL1_REQUEST		\
	: ( PKT_TYPE((c)) == BRL1_RESPONSE ||	\
	    PKT_TYPE((c)) == BRL1_EVENT ) )

#define IS_TTY_PKT(l)		( SUBCH(LAST_HDR_GET(l)) <= SC_CONS_SYSTEM ? 1 : 0 )


int
brl1_receive( l1sc_t *sc, int mode )
{
    int result;		/* value to be returned by brl1_receive */
    int c;		/* most-recently-read character	     	*/
    int done;		/* set done to break out of recv loop	*/
    unsigned long pl = 0, cpl = 0;
    sc_cq_t *q;		/* pointer to queue we're working with	*/

    result = BRL1_NO_MESSAGE;

    L1SC_RECV_LOCK(sc, cpl);

    done = 0;
    while( !done )
    {
	switch( STATE_GET(sc) )
	{

	  case BRL1_IDLE:
	    /* Initial or error state.  Waiting for a flag character
             * to resynchronize with the L1.
             */

	    if( !read_uart( sc, &c, &result ) ) {

		/* error reading uart */
		done = 1;
		continue;
	    }
	    
	    if( c == BRL1_FLAG_CH ) {
		/* saw a flag character */
		STATE_SET( sc, BRL1_FLAG );
		continue;
	    }
	    break;
	    
	  case BRL1_FLAG:
	    /* One or more flag characters have been read; look for
	     * the beginning of a packet (header byte).
	     */
	    
	    if( !read_uart( sc, &c, &result ) ) {

		/* error reading uart */
		if( c != UART_NO_CHAR )
		    STATE_SET( sc, BRL1_IDLE );

		done = 1;
		continue;
	    }
	    
	    if( c == BRL1_FLAG_CH ) {
		/* multiple flags are OK */
		continue;
	    }

	    if( !VALID_HDR( c ) ) {
		/* if c isn't a flag it should have been
		 * a valid header, so we have an error
		 */
		result = BRL1_PROTOCOL;
		STATE_SET( sc, BRL1_IDLE );
		done = 1;
		continue;
	    }

	    /* we have a valid header byte */
	    LAST_HDR_SET( sc, c );
	    STATE_SET( sc, BRL1_HDR );

	    break; 

	  case BRL1_HDR:
	    /* A header byte has been read. Do some bookkeeping. */
	    q = sc->subch[ SUBCH( LAST_HDR_GET(sc) ) ].iqp;
	    ASSERT(q);
	    
	    if( !IS_TTY_PKT(sc) ) {
		/* if this is an event or command response rather
		 * than console I/O, we need to reserve a couple
		 * of extra spaces in the queue for the header
		 * byte and a length byte; if we can't, stay in
		 * the BRL1_HDR state.
		 */
		if( cq_room( q ) < 2 ) {
		    result = BRL1_FULL_Q;
		    done = 1;
		    continue;
		}
		cq_tent_add( q, 0 );			/* reserve length byte */
		cq_tent_add( q, LAST_HDR_GET( sc ) );	/* record header byte  */
	    }
	    STATE_SET( sc, BRL1_BODY );

	    break;

	  case BRL1_BODY:
	    /* A header byte has been read.  We are now attempting
	     * to receive the packet body.
	     */

	    q = sc->subch[ SUBCH( LAST_HDR_GET(sc) ) ].iqp;
	    ASSERT(q);

	    /* if the queue we want to write into is full, don't read from
	     * the uart (this provides backpressure to the L1 side)
	     */
	    if( cq_tent_full( q ) ) {
		result = BRL1_FULL_Q;
		done = 1;
		continue;
	    }
	    
	    if( !read_uart( sc, &c, &result ) ) {

		/* error reading uart */
		if( c != UART_NO_CHAR )
		    STATE_SET( sc, BRL1_IDLE );
		done = 1;
		continue;
	    }

	    if( c == BRL1_ESC_CH ) {
		/* prepare to unescape the next character */
		STATE_SET( sc, BRL1_ESC );
		continue;
	    }
	    
	    if( c == BRL1_FLAG_CH ) {
		/* flag signifies the end of a packet */

		unsigned short crc;	/* holds the crc as we calculate it */
		int i;			/* index variable */
		brl1_sch_t *subch;      /* subchannel for received packet */
		brl1_notif_t callup;	/* "data ready" callup */

		/* whatever else may happen, we've seen a flag and we're
		 * starting a new packet
		 */
		STATE_SET( sc, BRL1_FLAG );

		/* if the packet body has less than 2 characters,
		 * it can't be a well-formed packet.  Discard it.
		 */
		if( cq_tent_len( q ) < /* 2 + possible length byte */
		    (2 + (IS_TTY_PKT(sc) ? 0 : 1)) )
		{
		    result = BRL1_PROTOCOL;
		    cq_discard_tent( q );
		    STATE_SET( sc, BRL1_FLAG );
		    done = 1;
		    continue;
		}
		
		/* check CRC */

		/* accumulate CRC, starting with the header byte and
		 * ending with the transmitted CRC.  This should
		 * result in a known good value.
		 */
		crc = crc16_calc( INIT_CRC, LAST_HDR_GET(sc) );
		for( i = (q->ipos + (IS_TTY_PKT(sc) ? 0 : 2)) % BRL1_QSIZE;
		     i != q->tent_next;
		     i = (i + 1) % BRL1_QSIZE )
		{
		    crc = crc16_calc( crc, q->buf[i] );
		}

		/* verify the caclulated crc against the "good" crc value;
		 * if we fail, discard the bad packet and return an error.
		 */
		if( crc != (unsigned short)GOOD_CRC ) {
		    result = BRL1_CRC;
		    cq_discard_tent( q );
		    STATE_SET( sc, BRL1_FLAG );
		    done = 1;
		    continue;
		}
		
		/* so the crc check was ok.  Now we discard the CRC
		 * from the end of the received bytes.
		 */
		q->tent_next += (BRL1_QSIZE - 2);
		q->tent_next %= BRL1_QSIZE;

		/* get the subchannel and lock it */
		subch = &(sc->subch[SUBCH( LAST_HDR_GET(sc) )]);
		SUBCH_DATA_LOCK( subch, pl );
		
		/* if this isn't a console packet, we need to record
		 * a length byte
		 */
		if( !IS_TTY_PKT(sc) ) {
		    q->buf[q->ipos] = cq_tent_len( q ) - 1;
		}
		
		/* record packet for posterity */
		cq_commit_tent( q );
		result = BRL1_VALID;

		/* notify subchannel owner that there's something
		 * on the queue for them
		 */
		atomic_inc(&(subch->packet_arrived));
		callup = subch->rx_notify;
		SUBCH_DATA_UNLOCK( subch, pl );

		if( callup && (mode == SERIAL_INTERRUPT_MODE) ) {
		    L1SC_RECV_UNLOCK( sc, cpl );
		    L1_collectibles[L1C_RECEIVE_CALLUPS]++;
		    (*callup)( sc->subch[SUBCH(LAST_HDR_GET(sc))].irq_frame.bf_irq,
				sc->subch[SUBCH(LAST_HDR_GET(sc))].irq_frame.bf_dev_id,
				sc->subch[SUBCH(LAST_HDR_GET(sc))].irq_frame.bf_regs,
				sc, SUBCH(LAST_HDR_GET(sc)) );
		    L1SC_RECV_LOCK( sc, cpl );
		}
		continue;	/* go back for more! */
	    }
	    
	    /* none of the special cases applied; we've got a normal
	     * body character
	     */
	    cq_tent_add( q, c );

	    break;

	  case BRL1_ESC:
	    /* saw an escape character.  The next character will need
	     * to be unescaped.
	     */

	    q = sc->subch[ SUBCH( LAST_HDR_GET(sc) ) ].iqp;
	    ASSERT(q);

	    /* if the queue we want to write into is full, don't read from
	     * the uart (this provides backpressure to the L1 side)
	     */
	    if( cq_tent_full( q ) ) {
		result = BRL1_FULL_Q;
		done = 1;
		continue;
	    }
	    
	    if( !read_uart( sc, &c, &result ) ) {

		/* error reading uart */
		if( c != UART_NO_CHAR ) {
		    cq_discard_tent( q );
		    STATE_SET( sc, BRL1_IDLE );
		}
		done = 1;
		continue;
	    }
	    
	    if( c == BRL1_FLAG_CH ) {
		/* flag after escape is an error */
		STATE_SET( sc, BRL1_FLAG );
		cq_discard_tent( q );
		result = BRL1_PROTOCOL;
		done = 1;
		continue;
	    }

	    if( c == BRL1_ESC_CH ) {
		/* two consecutive escapes is an error */
		STATE_SET( sc, BRL1_IDLE );
		cq_discard_tent( q );
		result = BRL1_PROTOCOL;
		done = 1;
		continue;
	    }
	    
	    /* otherwise, we've got a character that needs
	     * to be unescaped
	     */
	    cq_tent_add( q, (c ^ BRL1_XOR_CH) );
	    STATE_SET( sc, BRL1_BODY );

	    break;

	} /* end of switch( STATE_GET(sc) ) */
    } /* end of while(!done) */

    L1SC_RECV_UNLOCK( sc, cpl );

    return result;
}	    


/* brl1_init initializes the Bedrock/L1 protocol layer.  This includes
 * zeroing out the send and receive state information.
 */

void
brl1_init( l1sc_t *sc, nasid_t nasid, net_vec_t uart )
{
    int i;
    brl1_sch_t *subch;

    bzero( sc, sizeof( *sc ) );
    sc->nasid = nasid;
    sc->uart = uart;
    sc->getc_f = (uart == BRL1_LOCALHUB_UART ? uart_getc : rtr_uart_getc);
    sc->putc_f = (uart == BRL1_LOCALHUB_UART ? uart_putc : rtr_uart_putc);
    sc->sol = 1;
    subch = sc->subch;

    /* initialize L1 subchannels
     */

    /* assign processor TTY channels */
    for( i = 0; i < CPUS_PER_NODE; i++, subch++ ) {
	subch->use = BRL1_SUBCH_RSVD;
	subch->packet_arrived = ATOMIC_INIT(0);
	spin_lock_init( &(subch->data_lock) );
	sv_init( &(subch->arrive_sv), &(subch->data_lock), SV_MON_SPIN | SV_ORDER_FIFO /* | SV_INTS */ );
	subch->tx_notify = NULL;
	/* (for now, drop elscuart packets in the kernel) */
	subch->rx_notify = brl1_discard_packet;
	subch->iqp = &sc->garbage_q;
    }

    /* assign system TTY channel (first free subchannel after each
     * processor's individual TTY channel has been assigned)
     */
    subch->use = BRL1_SUBCH_RSVD;
    subch->packet_arrived = ATOMIC_INIT(0);
    spin_lock_init( &(subch->data_lock) );
    sv_init( &(subch->arrive_sv), &subch->data_lock, SV_MON_SPIN | SV_ORDER_FIFO /* | SV_INTS */ );
    subch->tx_notify = NULL;
    if( sc->uart == BRL1_LOCALHUB_UART ) {
	subch->iqp = snia_kmem_zalloc_node( sizeof(sc_cq_t), KM_NOSLEEP, NASID_TO_COMPACT_NODEID(nasid) );
	ASSERT( subch->iqp );
	cq_init( subch->iqp );
	subch->rx_notify = NULL;
    }
    else {
	/* we shouldn't be getting console input from remote UARTs */
	subch->iqp = &sc->garbage_q;
	subch->rx_notify = brl1_discard_packet;
    }
    subch++; i++;

    /* "reserved" subchannels (0x05-0x0F); for now, throw away
     * incoming packets
     */
    for( ; i < 0x10; i++, subch++ ) {
	subch->use = BRL1_SUBCH_FREE;
	subch->packet_arrived = ATOMIC_INIT(0);
	subch->tx_notify = NULL;
	subch->rx_notify = brl1_discard_packet;
	subch->iqp = &sc->garbage_q;
    }

    /* remaining subchannels are free */
    for( ; i < BRL1_NUM_SUBCHANS; i++, subch++ ) {
	subch->use = BRL1_SUBCH_FREE;
	subch->packet_arrived = ATOMIC_INIT(0);
	subch->tx_notify = NULL;
	subch->rx_notify = brl1_discard_packet;
	subch->iqp = &sc->garbage_q;
    }

    /* initialize synchronization structures
     */
    spin_lock_init( &(sc->subch_lock) );
    spin_lock_init( &(sc->send_lock) );
    spin_lock_init( &(sc->recv_lock) );

    if( sc->uart == BRL1_LOCALHUB_UART ) {
	uart_init( sc, UART_BAUD_RATE );
    }
    else {
	rtr_uart_init( sc, UART_BAUD_RATE );
    }

    /* Set up remaining fields using L1 command functions-- elsc_module_get
     * to read the module id, elsc_debug_get to see whether or not we're
     * in verbose mode.
     */
    {
	extern int elsc_module_get(l1sc_t *);

	sc->modid = elsc_module_get( sc );
	sc->modid = (sc->modid < 0 ? INVALID_MODULE : sc->modid);
	sc->verbose = 1;
    }
}

/*********************************************************************
 * These are interrupt-related functions used in the kernel to service
 * the L1.
 */

/*
 * brl1_intrd is the function which is called on a console interrupt.
 */

#if defined(CONFIG_IA64_SGI_SN1)

static void
brl1_intrd(int irq, void *dev_id, struct pt_regs *stuff)
{
    u_char isr_reg;
    l1sc_t *sc = get_elsc();
    int ret;

    L1_collectibles[L1C_INTERRUPTS]++;
    isr_reg = READ_L1_UART_REG(sc->nasid, REG_ISR);

    /* Save for callup args in console */
    sc->subch[SC_CONS_SYSTEM].irq_frame.bf_irq = irq;
    sc->subch[SC_CONS_SYSTEM].irq_frame.bf_dev_id = dev_id;
    sc->subch[SC_CONS_SYSTEM].irq_frame.bf_regs = stuff;

#if	defined(SYNC_CONSOLE_WRITE)
    while( isr_reg & ISR_RxRDY )
#else
    while( isr_reg & (ISR_RxRDY | ISR_TxRDY) )
#endif
    {
	if( isr_reg & ISR_RxRDY ) {
	    L1_collectibles[L1C_OUR_R_INTERRUPTS]++;
	    ret = brl1_receive(sc, SERIAL_INTERRUPT_MODE);
	    if ( (ret != BRL1_VALID) && (ret != BRL1_NO_MESSAGE) && (ret != BRL1_PROTOCOL) && (ret != BRL1_CRC) )
		L1_collectibles[L1C_REC_STALLS] = ret;
	}
#if	!defined(SYNC_CONSOLE_WRITE)
	if( (isr_reg & ISR_TxRDY) || (sc->send_in_use && UART_PUTC_READY(sc->nasid)) ) {
	    L1_collectibles[L1C_OUR_X_INTERRUPTS]++;
	    brl1_send_cont(sc);
	}
#endif	/* SYNC_CONSOLE_WRITE */
	isr_reg = READ_L1_UART_REG(sc->nasid, REG_ISR);
    }
}
#endif	/* CONFIG_IA64_SGI_SN1 */


/*
 * Install a callback function for the system console subchannel 
 * to allow an upper layer to be notified when the send buffer 
 * has been emptied.
 */
static inline void
l1_tx_notif( brl1_notif_t func )
{
	subch_set_tx_notify( &NODEPDA(NASID_TO_COMPACT_NODEID(get_master_nasid()))->module->elsc,
			SC_CONS_SYSTEM, func );
}


/*
 * Install a callback function for the system console subchannel
 * to allow an upper layer to be notified when a packet has been
 * received.
 */
static inline void
l1_rx_notif( brl1_notif_t func )
{
	subch_set_rx_notify( &NODEPDA(NASID_TO_COMPACT_NODEID(get_master_nasid()))->module->elsc,
				SC_CONS_SYSTEM, func );
}


/* brl1_intr is called directly from the uart interrupt; after it runs, the
 * interrupt "daemon" xthread is signalled to continue.
 */
void
brl1_intr( void )
{
}

#define BRL1_INTERRUPT_LEVEL	65	/* linux request_irq() value */

/* Return the current interrupt level */

//#define CONSOLE_POLLING_ALSO

int
l1_get_intr_value( void )
{
#ifdef	CONSOLE_POLLING_ALSO
	return(0);
#else
	return(BRL1_INTERRUPT_LEVEL);
#endif
}

/* Disconnect the callup functions - throw away interrupts */

void
l1_unconnect_intr(void)
{
	/* UnRegister the upper-level callup functions */
	l1_rx_notif((brl1_notif_t)NULL);
	l1_tx_notif((brl1_notif_t)NULL);
	/* We do NOT unregister the interrupts */
}

/* Set up uart interrupt handling for this node's uart */

void
l1_connect_intr(void *rx_notify, void *tx_notify)
{
	l1sc_t *sc;
	nasid_t nasid;
#if defined(CONFIG_IA64_SGI_SN1)
	int tmp;
#endif
	nodepda_t *console_nodepda;
	int intr_connect_level(cpuid_t, int, ilvl_t, intr_func_t);

	if ( L1_interrupts_connected ) {
		/* Interrupts are connected, so just register the callups */
		l1_rx_notif((brl1_notif_t)rx_notify);
		l1_tx_notif((brl1_notif_t)tx_notify);

		L1_collectibles[L1C_CONNECT_CALLS]++;
		return;
	}
	else
		L1_interrupts_connected = 1;

	nasid = get_master_nasid();
	console_nodepda = NODEPDA(NASID_TO_COMPACT_NODEID(nasid));
	sc = &console_nodepda->module->elsc;
	sc->intr_cpu = console_nodepda->node_first_cpu;

#if defined(CONFIG_IA64_SGI_SN1)
	if ( intr_connect_level(sc->intr_cpu, UART_INTR, INTPEND0_MAXMASK, (intr_func_t)brl1_intr) ) {
		L1_interrupts_connected = 0; /* FAILS !! */
	}
	else {
		void synergy_intr_connect(int, int);

		synergy_intr_connect(UART_INTR, sc->intr_cpu);
		L1_collectibles[L1C_R_IRQ]++;
		tmp = request_irq(BRL1_INTERRUPT_LEVEL, brl1_intrd, SA_INTERRUPT | SA_SHIRQ, "l1_protocol_driver", (void *)sc);
		L1_collectibles[L1C_R_IRQ_RET] = (uint64_t)tmp;
		if ( tmp ) {
			L1_interrupts_connected = 0; /* FAILS !! */
		}
		else {
			/* Register the upper-level callup functions */
			l1_rx_notif((brl1_notif_t)rx_notify);
			l1_tx_notif((brl1_notif_t)tx_notify);

			/* Set the uarts the way we like it */
			uart_enable_recv_intr( sc );
			uart_disable_xmit_intr( sc );
		}
	}
#endif	/* CONFIG_IA64_SGI_SN1 */
}


/* Set the line speed */

void
l1_set_baud(int baud)
{
#if 0
	nasid_t nasid;
	static void uart_init(l1sc_t *, int);
#endif

	L1_collectibles[L1C_SET_BAUD]++;

#if 0
	if ( L1_cons_is_inited ) {
		nasid = get_master_nasid();
		if ( NODEPDA(NASID_TO_COMPACT_NODEID(nasid))->module != (module_t *)0 )
			uart_init(&NODEPDA(NASID_TO_COMPACT_NODEID(nasid))->module->elsc, baud);
	}
#endif
	return;
}


/* These are functions to use from serial_in/out when in protocol
 * mode to send and receive uart control regs. These are external
 * interfaces into the protocol driver.
 */

void
l1_control_out(int offset, int value)
{
	nasid_t nasid = get_master_nasid();
	WRITE_L1_UART_REG(nasid, offset, value); 
}

/* Console input exported interface. Return a register value.  */

int
l1_control_in_polled(int offset)
{
	static int l1_control_in_local(int, int);

	return(l1_control_in_local(offset, SERIAL_POLLED_MODE));
}

int
l1_control_in(int offset)
{
	static int l1_control_in_local(int, int);

	return(l1_control_in_local(offset, SERIAL_INTERRUPT_MODE));
}

static int
l1_control_in_local(int offset, int mode)
{
	nasid_t nasid;
	int ret, input;
	static int l1_poll(l1sc_t *, int);

	nasid = get_master_nasid();
	ret = READ_L1_UART_REG(nasid, offset); 

	if ( offset == REG_LSR ) {
		ret |= (LSR_XHRE | LSR_XSRE);	/* can send anytime */
		if ( L1_cons_is_inited ) {
			if ( NODEPDA(NASID_TO_COMPACT_NODEID(nasid))->module != (module_t *)0 ) {
				input = l1_poll(&NODEPDA(NASID_TO_COMPACT_NODEID(nasid))->module->elsc, mode);
				if ( input ) {
					ret |= LSR_RCA;
				}
			}
		}
	}
	return(ret);
}

/*
 * Console input exported interface. Return a character (if one is available)
 */

int
l1_serial_in_polled(void)
{
	static int l1_serial_in_local(int mode);

	return(l1_serial_in_local(SERIAL_POLLED_MODE));
}

int
l1_serial_in(void)
{
	static int l1_serial_in_local(int mode);

	return(l1_serial_in_local(SERIAL_INTERRUPT_MODE));
}

static int
l1_serial_in_local(int mode)
{
	nasid_t nasid;
	l1sc_t *sc;
	int value;
	static int l1_getc( l1sc_t *, int );
	static inline l1sc_t *early_sc_init(nasid_t);

	nasid = get_master_nasid();
	sc = early_sc_init(nasid);
	if ( L1_cons_is_inited ) {
		if ( NODEPDA(NASID_TO_COMPACT_NODEID(nasid))->module != (module_t *)0 ) {
			sc = &NODEPDA(NASID_TO_COMPACT_NODEID(nasid))->module->elsc;
		}
	}
	value = l1_getc(sc, mode);
	return(value);
}

/* Console output exported interface. Write message to the console.  */

int
l1_serial_out( char *str, int len )
{
	nasid_t nasid = get_master_nasid();
	int l1_write(l1sc_t *, char *, int, int);

	if ( L1_cons_is_inited ) {
		if ( NODEPDA(NASID_TO_COMPACT_NODEID(nasid))->module != (module_t *)0 )
			return(l1_write(&NODEPDA(NASID_TO_COMPACT_NODEID(nasid))->module->elsc, str, len,
#if	defined(SYNC_CONSOLE_WRITE)
					1
#else
					!L1_interrupts_connected
#endif
							));
	}
	return(early_l1_serial_out(nasid, str, len, NOT_LOCKED));
}


/*
 * These are the 'early' functions - when we need to do things before we have
 * all the structs setup.
 */

static l1sc_t Early_console;		/* fake l1sc_t */
static int Early_console_inited = 0;

static void
early_brl1_init( l1sc_t *sc, nasid_t nasid, net_vec_t uart )
{
    int i;
    brl1_sch_t *subch;

    bzero( sc, sizeof( *sc ) );
    sc->nasid = nasid;
    sc->uart = uart;
    sc->getc_f = (uart == BRL1_LOCALHUB_UART ? uart_getc : rtr_uart_getc);
    sc->putc_f = (uart == BRL1_LOCALHUB_UART ? uart_putc : rtr_uart_putc);
    sc->sol = 1;
    subch = sc->subch;

    /* initialize L1 subchannels
     */

    /* assign processor TTY channels */
    for( i = 0; i < CPUS_PER_NODE; i++, subch++ ) {
	subch->use = BRL1_SUBCH_RSVD;
	subch->packet_arrived = ATOMIC_INIT(0);
	subch->tx_notify = NULL;
	subch->rx_notify = NULL;
	subch->iqp = &sc->garbage_q;
    }

    /* assign system TTY channel (first free subchannel after each
     * processor's individual TTY channel has been assigned)
     */
    subch->use = BRL1_SUBCH_RSVD;
    subch->packet_arrived = ATOMIC_INIT(0);
    subch->tx_notify = NULL;
    subch->rx_notify = NULL;
    if( sc->uart == BRL1_LOCALHUB_UART ) {
	static sc_cq_t x_iqp;

	subch->iqp = &x_iqp;
	ASSERT( subch->iqp );
	cq_init( subch->iqp );
    }
    else {
	/* we shouldn't be getting console input from remote UARTs */
	subch->iqp = &sc->garbage_q;
    }
    subch++; i++;

    /* "reserved" subchannels (0x05-0x0F); for now, throw away
     * incoming packets
     */
    for( ; i < 0x10; i++, subch++ ) {
	subch->use = BRL1_SUBCH_FREE;
	subch->packet_arrived = ATOMIC_INIT(0);
	subch->tx_notify = NULL;
	subch->rx_notify = NULL;
	subch->iqp = &sc->garbage_q;
    }

    /* remaining subchannels are free */
    for( ; i < BRL1_NUM_SUBCHANS; i++, subch++ ) {
	subch->use = BRL1_SUBCH_FREE;
	subch->packet_arrived = ATOMIC_INIT(0);
	subch->tx_notify = NULL;
	subch->rx_notify = NULL;
	subch->iqp = &sc->garbage_q;
    }
}

static inline l1sc_t *
early_sc_init(nasid_t nasid)
{
	/* This is for early I/O */
	if ( Early_console_inited == 0 ) {
    		early_brl1_init(&Early_console, nasid,  BRL1_LOCALHUB_UART);
		Early_console_inited = 1;
	}
	return(&Early_console);
}

#define PUTCHAR(ch) \
    { \
        while( (!(READ_L1_UART_REG( nasid, REG_LSR ) & LSR_XHRE)) || \
                (!(READ_L1_UART_REG( nasid, REG_MSR ) & MSR_CTS)) ); \
        WRITE_L1_UART_REG( nasid, REG_DAT, (ch) ); \
    }

static int
early_l1_serial_out( nasid_t nasid, char *str, int len, int lock_state )
{
	int ret, sent = 0;
	char *msg = str;
	static int early_l1_send( nasid_t nasid, char *str, int len, int lock_state );

	while ( sent < len ) {
		ret = early_l1_send(nasid, msg, len - sent, lock_state);
		sent += ret;
		msg += ret;
	}
	return(len);
}

static inline int
early_l1_send( nasid_t nasid, char *str, int len, int lock_state )
{
    int sent;
    char crc_char;
    unsigned short crc = INIT_CRC;

    if( len > (BRL1_QSIZE - 1) )
	len = (BRL1_QSIZE - 1);

    sent = len;
    if ( lock_state == NOT_LOCKED )
    	lock_console(nasid);

    PUTCHAR( BRL1_FLAG_CH );
    PUTCHAR( BRL1_EVENT | SC_CONS_SYSTEM );
    crc = crc16_calc( crc, (BRL1_EVENT | SC_CONS_SYSTEM) );

    while( len ) {

	if( (*str == BRL1_FLAG_CH) || (*str == BRL1_ESC_CH) ) {
	    PUTCHAR( BRL1_ESC_CH );
	    PUTCHAR( (*str) ^ BRL1_XOR_CH );
	}
	else {
	    PUTCHAR( *str );
	}
	
	crc = crc16_calc( crc, *str );

	str++; len--;
    }
    
    crc ^= 0xffff;
    crc_char = crc & 0xff;
    if( (crc_char == BRL1_ESC_CH) || (crc_char == BRL1_FLAG_CH) ) {
	crc_char ^= BRL1_XOR_CH;
	PUTCHAR( BRL1_ESC_CH );
    }
    PUTCHAR( crc_char );
    crc_char = (crc >> 8) & 0xff;
    if( (crc_char == BRL1_ESC_CH) || (crc_char == BRL1_FLAG_CH) ) {
	crc_char ^= BRL1_XOR_CH;
	PUTCHAR( BRL1_ESC_CH );
    }
    PUTCHAR( crc_char );
    PUTCHAR( BRL1_FLAG_CH );

    if ( lock_state == NOT_LOCKED )
    	unlock_console(nasid);
    return sent;
}


/*********************************************************************
 * l1_cons functions
 *
 * These allow the L1 to act as the system console.  They're intended
 * to abstract away most of the br/l1 internal details from the
 * _L1_cons_* functions (in the prom-- see "l1_console.c") and
 * l1_* functions (in the kernel-- see "sio_l1.c") that they support.
 *
 */

static int
l1_poll( l1sc_t *sc, int mode )
{
    int ret;

    /* in case this gets called before the l1sc_t structure for the module_t
     * struct for this node is initialized (i.e., if we're called with a
     * zero l1sc_t pointer)...
     */


    if( !sc ) {
	return 0;
    }

    if( atomic_read(&sc->subch[SC_CONS_SYSTEM].packet_arrived) ) {
	return 1;
    }

    ret = brl1_receive( sc, mode );
    if ( (ret != BRL1_VALID) && (ret != BRL1_NO_MESSAGE) && (ret != BRL1_PROTOCOL) && (ret != BRL1_CRC) )
	L1_collectibles[L1C_REC_STALLS] = ret;

    if( atomic_read(&sc->subch[SC_CONS_SYSTEM].packet_arrived) ) {
	return 1;
    }
    return 0;
}


/* pull a character off of the system console queue (if one is available)
 */
static int
l1_getc( l1sc_t *sc, int mode )
{
    unsigned long pl = 0;
    int c;

    brl1_sch_t *subch = &(sc->subch[SC_CONS_SYSTEM]);
    sc_cq_t *q = subch->iqp;

    if( !l1_poll( sc, mode ) ) {
	return 0;
    }

    SUBCH_DATA_LOCK( subch, pl );
    if( cq_empty( q ) ) {
	atomic_set(&subch->packet_arrived, 0);
	SUBCH_DATA_UNLOCK( subch, pl );
	return 0;
    }
    cq_rem( q, c );
    if( cq_empty( q ) )
	atomic_set(&subch->packet_arrived, 0);
    SUBCH_DATA_UNLOCK( subch, pl );

    return c;
}

/*
 * Write a message to the L1 on the system console subchannel.
 *
 * Danger: don't use a non-zero value for the wait parameter unless you're
 * someone important (like a kernel error message).
 */

int
l1_write( l1sc_t *sc, char *msg, int len, int wait )
{
	int sent = 0, ret = 0;

	if ( wait ) {
		while ( sent < len ) {
			ret = brl1_send( sc, msg, len - sent, (SC_CONS_SYSTEM | BRL1_EVENT), wait );
			sent += ret;
			msg += ret;
		}
		ret = len;
	}
	else {
		ret = brl1_send( sc, msg, len, (SC_CONS_SYSTEM | BRL1_EVENT), wait );
	}
	return(ret);
}

/* initialize the system console subchannel
 */
void
l1_init(void)
{
	/* All we do now is remember that we have been called */
	L1_cons_is_inited = 1;
}


/*********************************************************************
 * The following functions and definitions implement the "message"-
 * style interface to the L1 system controller.
 *
 * Note that throughout this file, "sc" generally stands for "system
 * controller", while "subchannels" tend to be represented by
 * variables with names like subch or ch.
 *
 */

#ifdef L1_DEBUG
#define L1_DBG_PRF(x) printf x
#else
#define L1_DBG_PRF(x)
#endif

/*
 * sc_data_ready is called to signal threads that are blocked on l1 input.
 */
void
sc_data_ready( int dummy0, void *dummy1, struct pt_regs *dummy2, l1sc_t *sc, int ch )
{
    unsigned long pl = 0;

    brl1_sch_t *subch = &(sc->subch[ch]);
    SUBCH_DATA_LOCK( subch, pl );
    sv_signal( &(subch->arrive_sv) );
    SUBCH_DATA_UNLOCK( subch, pl );
}

/* sc_open reserves a subchannel to send a request to the L1 (the
 * L1's response will arrive on the same channel).  The number
 * returned by sc_open is the system controller subchannel
 * acquired.
 */
int
sc_open( l1sc_t *sc, uint target )
{
    /* The kernel version implements a locking scheme to arbitrate
     * subchannel assignment.
     */
    int ch;
    unsigned long pl = 0;
    brl1_sch_t *subch;

    SUBCH_LOCK( sc, pl );

    /* Look for a free subchannel. Subchannels 0-15 are reserved
     * for other purposes.
     */
    for( subch = &(sc->subch[BRL1_CMD_SUBCH]), ch = BRL1_CMD_SUBCH; 
			ch < BRL1_NUM_SUBCHANS; subch++, ch++ ) {
        if( subch->use == BRL1_SUBCH_FREE )
            break;
    }

    if( ch == BRL1_NUM_SUBCHANS ) {
        /* there were no subchannels available! */
        SUBCH_UNLOCK( sc, pl );
        return SC_NSUBCH;
    }

    subch->use = BRL1_SUBCH_RSVD;
    SUBCH_UNLOCK( sc, pl );

    atomic_set(&subch->packet_arrived, 0);
    subch->target = target;
    spin_lock_init( &(subch->data_lock) );
    sv_init( &(subch->arrive_sv), &(subch->data_lock), SV_MON_SPIN | SV_ORDER_FIFO /* | SV_INTS */);
    subch->tx_notify = NULL;
    subch->rx_notify = sc_data_ready;
    subch->iqp = snia_kmem_zalloc_node( sizeof(sc_cq_t), KM_NOSLEEP,
				   NASID_TO_COMPACT_NODEID(sc->nasid) );
    ASSERT( subch->iqp );
    cq_init( subch->iqp );

    return ch;
}


/* sc_close frees a Bedrock<->L1 subchannel.
 */
int
sc_close( l1sc_t *sc, int ch )
{
    unsigned long pl = 0;
    brl1_sch_t *subch;

    SUBCH_LOCK( sc, pl );
    subch = &(sc->subch[ch]);
    if( subch->use != BRL1_SUBCH_RSVD ) {
        /* we're trying to close a subchannel that's not open */
	SUBCH_UNLOCK( sc, pl );
        return SC_NOPEN;
    }

    atomic_set(&subch->packet_arrived, 0);
    subch->use = BRL1_SUBCH_FREE;

    sv_broadcast( &(subch->arrive_sv) );
    sv_destroy( &(subch->arrive_sv) );
    spin_lock_destroy( &(subch->data_lock) );

    ASSERT( subch->iqp && (subch->iqp != &sc->garbage_q) );
    snia_kmem_free( subch->iqp, sizeof(sc_cq_t) );
    subch->iqp = &sc->garbage_q;
    subch->tx_notify = NULL;
    subch->rx_notify = brl1_discard_packet;

    SUBCH_UNLOCK( sc, pl );

    return SC_SUCCESS;
}


/* sc_construct_msg builds a bedrock-to-L1 request in the supplied
 * buffer.  Returns the length of the message.  The
 * safest course when passing a buffer to be filled in is to use
 * BRL1_QSIZE as the buffer size.
 *
 * Command arguments are passed as type/argument pairs, i.e., to
 * pass the number 5 as an argument to an L1 command, call
 * sc_construct_msg as follows:
 *
 *    char msg[BRL1_QSIZE];
 *    msg_len = sc_construct_msg( msg,
 *				  BRL1_QSIZE,
 *				  target_component,
 *                                L1_ADDR_TASK_BOGUSTASK,
 *                                L1_BOGUSTASK_REQ_BOGUSREQ,
 *                                2,
 *                                L1_ARG_INT, 5 );
 *
 * To pass an additional ASCII argument, you'd do the following:
 *
 *    char *str;
 *    ... str points to a null-terminated ascii string ...
 *    msg_len = sc_construct_msg( msg,
 *                                BRL1_QSIZE,
 *				  target_component,
 *                                L1_ADDR_TASK_BOGUSTASK,
 *                                L1_BOGUSTASK_REQ_BOGUSREQ,
 *                                4,
 *                                L1_ARG_INT, 5,
 *                                L1_ARG_ASCII, str );
 *
 * Finally, arbitrary data of unknown type is passed using the argtype
 * code L1_ARG_UNKNOWN, a data length, and a buffer pointer, e.g.
 *
 *    msg_len = sc_construct_msg( msg,
 *                                BRL1_QSIZE,
 *				  target_component,
 *                                L1_ADDR_TASK_BOGUSTASK,
 *                                L1_BOGUSTASK_REQ_BOGUSREQ,
 *                                3,
 *                                L1_ARG_UNKNOWN, 32, bufptr );
 *
 * ...passes 32 bytes of data starting at bufptr.  Note that no string or
 * "unknown"-type argument should be long enough to overflow the message
 * buffer.
 *
 * To construct a message for an L1 command that requires no arguments,
 * you'd use the following:
 *
 *    msg_len = sc_construct_msg( msg,
 *                                BRL1_QSIZE,
 *				  target_component,
 *                                L1_ADDR_TASK_BOGUSTASK,
 *                                L1_BOGUSTASK_REQ_BOGUSREQ,
 *                                0 );
 *
 * The final 0 means "no varargs".  Notice that this parameter is used to hold
 * the number of additional arguments to sc_construct_msg, _not_ the actual
 * number of arguments used by the L1 command (so 2 per L1_ARG_[INT,ASCII]
 * type argument, and 3 per L1_ARG_UNKOWN type argument).  A call to construct
 * an L1 command which required three integer arguments and two arguments of
 * some arbitrary (unknown) type would pass 12 as the value for this parameter.
 *
 * ENDIANNESS WARNING: The following code does a lot of copying back-and-forth
 * between byte arrays and four-byte big-endian integers.  Depending on the
 * system controller connection and endianness of future architectures, some
 * rewriting might be necessary.
 */
int
sc_construct_msg( l1sc_t  *sc,		/* system controller struct */
		  int	   ch,           /* subchannel for this message */
		  char    *msg,          /* message buffer */
		  int      msg_len,      /* size of message buffer */
                  l1addr_t addr_task,    /* target system controller task */
                  short    req_code,     /* 16-bit request code */
                  int      req_nargs,    /* # of arguments (varargs) passed */
                  ... )                 /* any additional parameters */
{
    uint32_t buf32;   /* 32-bit buffer used to bounce things around */
    void *bufptr;       /* used to hold command argument addresses */
    va_list al;         /* variable argument list */
    int index;          /* current index into msg buffer */
    int argno;          /* current position in varargs list */
    int l1_argno;       /* running total of arguments to l1 */
    int l1_arg_t;       /* argument type/length */
    int l1_argno_byte;  /* offset of argument count byte */

    index = argno = 0;

    /* set up destination address */
    if( (msg_len -= sizeof( buf32 )) < 0 )
	return -1;
    L1_ADDRESS_TO_TASK( &buf32, sc->subch[ch].target, addr_task );
    COPY_INT_TO_BUFFER(msg, index, buf32);

    /* copy request code */
    if( (msg_len -= 2) < 0 )
	return( -1 );
    msg[index++] = ((req_code >> 8) & 0xff);
    msg[index++] = (req_code & 0xff);

    if( !req_nargs ) {
        return index;
    }

    /* reserve a byte for the argument count */
    if( (msg_len -= 1) < 0 )
	return( -1 );
    l1_argno_byte = index++;
    l1_argno = 0;

    /* copy additional arguments */
    va_start( al, req_nargs );
    while( argno < req_nargs ) {
        l1_argno++;
        l1_arg_t = va_arg( al, int ); argno++;
        switch( l1_arg_t )
        {
          case L1_ARG_INT:
	    if( (msg_len -= (sizeof( buf32 ) + 1)) < 0 )
		return( -1 );
            msg[index++] = L1_ARG_INT;
            buf32 = (unsigned)va_arg( al, int ); argno++;
	    COPY_INT_TO_BUFFER(msg, index, buf32);
            break;

          case L1_ARG_ASCII:
            bufptr = va_arg( al, char* ); argno++;
	    if( (msg_len -= (strlen( bufptr ) + 2)) < 0 )
		return( -1 );
            msg[index++] = L1_ARG_ASCII;
            strcpy( (char *)&(msg[index]), (char *)bufptr );
            index += (strlen( bufptr ) + 1); /* include terminating null */
            break;

	  case L1_ARG_UNKNOWN:
              {
                  int arglen;
		  
                  arglen = va_arg( al, int ); argno++;
                  bufptr = va_arg( al, void* ); argno++;
		  if( (msg_len -= (arglen + 1)) < 0 )
		      return( -1 );
                  msg[index++] = L1_ARG_UNKNOWN | arglen;
                  BCOPY( bufptr, &(msg[index]), arglen  );
                  index += arglen;
		  break;
              }
	  
	  default: /* unhandled argument type */
	    return -1;
        }
    }

    va_end( al );
    msg[l1_argno_byte] = l1_argno;

    return index;
}



/* sc_interpret_resp verifies an L1 response to a bedrock request, and
 * breaks the response data up into the constituent parts.  If the
 * response message indicates error, or if a mismatch is found in the
 * expected number and type of arguments, an error is returned.  The
 * arguments to this function work very much like the arguments to
 * sc_construct_msg, above, except that L1_ARG_INTs must be followed
 * by a _pointer_ to an integer that can be filled in by this function.
 */
int
sc_interpret_resp( char *resp,          /* buffer received from L1 */
                   int   resp_nargs,    /* number of _varargs_ passed in */
                   ... )
{
    uint32_t buf32;   /* 32-bit buffer used to bounce things around */
    void *bufptr;       /* used to hold response field addresses */
    va_list al;         /* variable argument list */
    int index;          /* current index into response buffer */
    int argno;          /* current position in varargs list */
    int l1_fldno;       /* number of resp fields received from l1 */
    int l1_fld_t;       /* field type/length */

    index = argno = 0;

#if defined(L1_DEBUG)
#define DUMP_RESP							  \
    {									  \
	int ix;								  \
        char outbuf[512];						  \
        sprintf( outbuf, "sc_interpret_resp error line %d: ", __LINE__ ); \
	for( ix = 0; ix < 16; ix++ ) {					  \
	    sprintf( &outbuf[strlen(outbuf)], "%x ", resp[ix] );	  \
	}								  \
	printk( "%s\n", outbuf );					  \
    }
#else
#define DUMP_RESP
#endif /* L1_DEBUG */

    /* check response code */
    COPY_BUFFER_TO_INT(resp, index, buf32);
    if( buf32 != L1_RESP_OK ) {
	DUMP_RESP;
        return buf32;
    }

    /* get number of response fields */
    l1_fldno = resp[index++];

    va_start( al, resp_nargs );

    /* copy out response fields */
    while( argno < resp_nargs ) {
        l1_fldno--;
        l1_fld_t = va_arg( al, int ); argno++;
        switch( l1_fld_t )
        {
          case L1_ARG_INT:
            if( resp[index++] != L1_ARG_INT ) {
                /* type mismatch */
		va_end( al );
		DUMP_RESP;
		return -1;
            }
            bufptr = va_arg( al, int* ); argno++;
	    COPY_BUFFER_TO_BUFFER(resp, index, bufptr);
            break;

          case L1_ARG_ASCII:
            if( resp[index++] != L1_ARG_ASCII ) {
                /* type mismatch */
		va_end( al );
		DUMP_RESP;
                return -1;
            }
            bufptr = va_arg( al, char* ); argno++;
            strcpy( (char *)bufptr, (char *)&(resp[index]) );
            /* include terminating null */
            index += (strlen( &(resp[index]) ) + 1);
            break;

          default:
	    if( (l1_fld_t & L1_ARG_UNKNOWN) == L1_ARG_UNKNOWN )
	    {
		int *arglen;
		
		arglen = va_arg( al, int* ); argno++;
		bufptr = va_arg( al, void* ); argno++;
		*arglen = ((resp[index++] & ~L1_ARG_UNKNOWN) & 0xff);
		BCOPY( &(resp[index]), bufptr, *arglen  );
		index += (*arglen);
	    }
	    
	    else {
		/* unhandled type */
		va_end( al );
		DUMP_RESP;
		return -1;
	    }
        }
    }
    va_end( al );
  
    if( (l1_fldno != 0) || (argno != resp_nargs) ) {
        /* wrong number of arguments */
	DUMP_RESP;
        return -1;
    }
    return 0;
}




/* sc_send takes as arguments a system controller struct, a
 * buffer which contains a Bedrock<->L1 "request" message,
 * the message length, and the subchannel (presumably obtained
 * from an earlier invocation of sc_open) over which the
 * message is to be sent.  The final argument ("wait") indicates
 * whether the send is to be performed synchronously or not.
 *
 * sc_send returns either zero or an error value.  Synchronous sends 
 * (wait != 0) will not return until the data has actually been sent
 * to the UART.  Synchronous sends generally receive privileged
 * treatment.  The intent is that they be used sparingly, for such
 * purposes as kernel printf's (the "ducons" routines).  Run-of-the-mill
 * console output and L1 requests should NOT use a non-zero value
 * for wait.
 */
int
sc_send( l1sc_t *sc, int ch, char *msg, int len, int wait )
{
    char type_and_subch;
    int result;

    if( (ch < 0) || ( ch >= BRL1_NUM_SUBCHANS) ) {
        return SC_BADSUBCH;
    }

    /* Verify that this is an open subchannel
     */
    if( sc->subch[ch].use == BRL1_SUBCH_FREE ) {
        return SC_NOPEN;
    }

    type_and_subch = (BRL1_REQUEST | ((u_char)ch));
    result = brl1_send( sc, msg, len, type_and_subch, wait );

    /* If we sent as much as we asked to, return "ok". */
    if( result == len )
	return( SC_SUCCESS );

    /* Or, if we sent less, than either the UART is busy or
     * we're trying to send too large a packet anyway.
     */
    else if( result >= 0 && result < len )
	return( SC_BUSY );

    /* Or, if something else went wrong (result < 0), then
     * return that error value.
     */
    else
	return( result );
}



/* subch_pull_msg pulls a message off the receive queue for subch
 * and places it the buffer pointed to by msg.  This routine should only
 * be called when the caller already knows a message is available on the
 * receive queue (and, in the kernel, only when the subchannel data lock
 * is held by the caller).
 */
static void
subch_pull_msg( brl1_sch_t *subch, char *msg, int *len )
{
    sc_cq_t *q;         /* receive queue */
    int before_wrap,    /* packet may be split into two different       */
        after_wrap;     /*   pieces to accommodate queue wraparound      */

    /* pull message off the receive queue */
    q = subch->iqp;

    cq_rem( q, *len );   /* remove length byte and store */
    cq_discard( q );     /* remove type/subch byte and discard */

    if ( *len > 0 )
	(*len)--;        /* don't count type/subch byte in length returned */

    if( (q->opos + (*len)) > BRL1_QSIZE ) {
        before_wrap = BRL1_QSIZE - q->opos;
        after_wrap = (*len) - before_wrap;
    }
    else {
        before_wrap = (*len);
        after_wrap = 0;
    }

    BCOPY( q->buf + q->opos, msg, before_wrap  );
    if( after_wrap ) {
        BCOPY( q->buf, msg + before_wrap, after_wrap  );
	q->opos = after_wrap;
    }
    else {
	q->opos = ((q->opos + before_wrap) & (BRL1_QSIZE - 1));
    }
    atomic_dec(&(subch->packet_arrived));
}


/* sc_recv_poll can be called as a blocking or non-blocking function;
 * it attempts to pull a message off of the subchannel specified
 * in the argument list (ch).
 *
 * The "block" argument, if non-zero, is interpreted as a timeout
 * delay (to avoid permanent waiting).
 */

int
sc_recv_poll( l1sc_t *sc, int ch, char *msg, int *len, uint64_t block )
{
    int is_msg = 0;
    unsigned long pl = 0;
    brl1_sch_t *subch = &(sc->subch[ch]);

    rtc_time_t exp_time = rtc_time() + block;

    /* sanity check-- make sure this is an open subchannel */
    if( subch->use == BRL1_SUBCH_FREE )
	return( SC_NOPEN );

    do {

        /* kick the next lower layer and see if it pulls anything in
         */
	brl1_receive( sc, SERIAL_POLLED_MODE );
	is_msg = atomic_read(&subch->packet_arrived);

    } while( block && !is_msg && (rtc_time() < exp_time) );

    if( !is_msg ) {
	/* no message and we didn't care to wait for one */
	return( SC_NMSG );
    }

    SUBCH_DATA_LOCK( subch, pl );
    subch_pull_msg( subch, msg, len );
    SUBCH_DATA_UNLOCK( subch, pl );

    return( SC_SUCCESS );
}
    

/* Like sc_recv_poll, sc_recv_intr can be called in either a blocking
 * or non-blocking mode.  Rather than polling until an appointed timeout,
 * however, sc_recv_intr sleeps on a syncrhonization variable until a
 * signal from the lower layer tells us that a packet has arrived.
 *
 * sc_recv_intr can't be used with remote (router) L1s.
 */
int
sc_recv_intr( l1sc_t *sc, int ch, char *msg, int *len, uint64_t block )
{
    int is_msg = 0;
    unsigned long pl = 0;
    brl1_sch_t *subch = &(sc->subch[ch]);

    do {
	SUBCH_DATA_LOCK(subch, pl);
	is_msg = atomic_read(&subch->packet_arrived);
	if( !is_msg && block ) {
	    /* wake me when you've got something */
	    subch->rx_notify = sc_data_ready;
	    sv_wait( &(subch->arrive_sv), 0, 0);
	    if( subch->use == BRL1_SUBCH_FREE ) {
		/* oops-- somebody closed our subchannel while we were
		 * sleeping!
		 */

		/* no need to unlock since the channel's closed anyhow */
		return( SC_NOPEN );
	    }
	}
    } while( !is_msg && block );

    if( !is_msg ) {
	/* no message and we didn't care to wait for one */
	SUBCH_DATA_UNLOCK( subch, pl );
	return( SC_NMSG );
    }

    subch_pull_msg( subch, msg, len );
    SUBCH_DATA_UNLOCK( subch, pl );

    return( SC_SUCCESS );
}

/* sc_command implements a (blocking) combination of sc_send and sc_recv.
 * It is intended to be the SN1 equivalent of SN0's "elsc_command", which
 * issued a system controller command and then waited for a response from
 * the system controller before returning.
 *
 * cmd points to the outgoing command; resp points to the buffer in
 * which the response is to be stored.  Both buffers are assumed to
 * be the same length; if there is any doubt as to whether the
 * response buffer is long enough to hold the L1's response, then
 * make it BRL1_QSIZE bytes-- no Bedrock<->L1 message can be any
 * bigger.
 *
 * Be careful using the same buffer for both cmd and resp; it could get
 * hairy if there were ever an L1 command request that spanned multiple
 * packets.  (On the other hand, that would require some additional
 * rewriting of the L1 command interface anyway.)
 */
#define __RETRIES	50
#define __WAIT_SEND	1	// ( sc->uart != BRL1_LOCALHUB_UART )
#define __WAIT_RECV	10000000


int
sc_command( l1sc_t *sc, int ch, char *cmd, char *resp, int *len )
{
#ifndef CONFIG_SERIAL_SGI_L1_PROTOCOL
    return SC_NMSG;
#else
    int result;
    int retries;

    if ( IS_RUNNING_ON_SIMULATOR() )
    	return SC_NMSG;

    retries = __RETRIES;

    while( (result = sc_send( sc, ch, cmd, *len, __WAIT_SEND )) < 0 ) {
	if( result == SC_BUSY ) {
	    retries--;
	    if( retries <= 0 )
		return result;
	    uart_delay(500);
	}
	else {
	    return result;
	}
    }
    
    /* block on sc_recv_* */
    if( (sc->uart == BRL1_LOCALHUB_UART) && L1_interrupts_connected ) {
	return( sc_recv_intr( sc, ch, resp, len, __WAIT_RECV ) );
    }
    else {
	return( sc_recv_poll( sc, ch, resp, len, __WAIT_RECV ) );
    }
#endif /* CONFIG_SERIAL_SGI_L1_PROTOCOL */
}

/* sc_command_kern is a knuckle-dragging, no-patience version of sc_command
 * used in situations where the kernel has a command that shouldn't be
 * delayed until the send buffer clears.  sc_command should be used instead
 * under most circumstances.
 */

int
sc_command_kern( l1sc_t *sc, int ch, char *cmd, char *resp, int *len )
{
#ifndef CONFIG_SERIAL_SGI_L1_PROTOCOL
    return SC_NMSG;
#else
    int result;

    if ( IS_RUNNING_ON_SIMULATOR() )
    	return SC_NMSG;

    if( (result = sc_send( sc, ch, cmd, *len, 1 )) < 0 ) {
	return result;
    }

    return( sc_recv_poll( sc, ch, resp, len, __WAIT_RECV ) );
#endif /* CONFIG_SERIAL_SGI_L1_PROTOCOL */
}



/* sc_poll checks the queue corresponding to the given
 * subchannel to see if there's anything available.  If
 * not, it kicks the brl1 layer and then checks again.
 *
 * Returns 1 if input is available on the given queue,
 * 0 otherwise.
 */

int
sc_poll( l1sc_t *sc, int ch )
{
    brl1_sch_t *subch = &(sc->subch[ch]);

    if( atomic_read(&subch->packet_arrived) )
	return 1;

    brl1_receive( sc, SERIAL_POLLED_MODE );

    if( atomic_read(&subch->packet_arrived) )
	return 1;

    return 0;
}

/* for now, sc_init just calls brl1_init */

void
sc_init( l1sc_t *sc, nasid_t nasid, net_vec_t uart )
{
    if ( !IS_RUNNING_ON_SIMULATOR() )
    	brl1_init( sc, nasid, uart );
}

/* sc_dispatch_env_event handles events sent from the system control
 * network's environmental monitor tasks.
 */

#if	defined(LINUX_KERNEL_THREADS)

static void
sc_dispatch_env_event( uint code, int argc, char *args, int maxlen )
{
    int j, i = 0;
    uint32_t ESPcode;

    switch( code ) {
	/* for now, all codes do the same thing: grab two arguments
	 * and print a cmn_err_tag message */
      default:
	/* check number of arguments */
	if( argc != 2 ) {
	    L1_DBG_PRF(( "sc_dispatch_env_event: "
			 "expected 2 arguments, got %d\n", argc ));
	    return;
	}
	
	/* get ESP code (integer argument) */
	if( args[i++] != L1_ARG_INT ) {
	    L1_DBG_PRF(( "sc_dispatch_env_event: "
			 "expected integer argument\n" ));
	    return;
	}
	/* WARNING: highly endian */
	COPY_BUFFER_TO_INT(args, i, ESPcode);

	/* verify string argument */
	if( args[i++] != L1_ARG_ASCII ) {
	    L1_DBG_PRF(( "sc_dispatch_env_event: "
			 "expected an ASCII string\n" ));
	    return;
	}
	for( j = i; j < maxlen; j++ ) {
	    if( args[j] == '\0' ) break; /* found string termination */
	}
	if( j == maxlen ) {
	    j--;
	    L1_DBG_PRF(( "sc_dispatch_env_event: "
			 "message too long-- truncating\n" ));
	}

	/* strip out trailing cr/lf */
	for( ; 
	     j > 1 && ((args[j-1] == 0xd) || (args[j-1] == 0xa)); 
	     j-- );
	args[j] = '\0';
	
	/* strip out leading cr/lf */
	for( ;
	     i < j && ((args[i] == 0xd) || (args[i] == 0xa));
	     i++ );
    }
}


/* sc_event waits for events to arrive from the system controller, and
 * prints appropriate messages to the syslog.
 */

static void
sc_event( l1sc_t *sc, int ch )
{
    char event[BRL1_QSIZE];
    int i;
    int result;
    int event_len;
    uint32_t ev_src;
    uint32_t ev_code;
    int ev_argc;

    while(1) {
	
	bzero( event, BRL1_QSIZE );

	/*
	 * wait for an event 
	 */
	result = sc_recv_intr( sc, ch, event, &event_len, 1 );
	if( result != SC_SUCCESS ) {
	    printk(KERN_WARNING  "Error receiving sysctl event on nasid %d\n",
		     sc->nasid );
	}
	else {
	    /*
	     * an event arrived; break it down into useful pieces
	     */
#if defined(L1_DEBUG) && 0
	    int ix;
	    printf( "Event packet received:\n" );
	    for (ix = 0; ix < 64; ix++) {
		printf( "%x%x ", ((event[ix] >> 4) & ((uint64_t)0xf)),
			(event[ix] & ((uint64_t)0xf)) );
		if( (ix % 16) == 0xf ) printf( "\n" );
	    }
#endif /* L1_DEBUG */

	    i = 0;

	    /* get event source */
	    COPY_BUFFER_TO_INT(event, i, ev_src);
	    COPY_BUFFER_TO_INT(event, i, ev_code);

	    /* get arg count */
	    ev_argc = (event[i++] & 0xffUL);
	    
	    /* dispatch events by task */
	    switch( (ev_src & L1_ADDR_TASK_MASK) >> L1_ADDR_TASK_SHFT )
	    {
	      case L1_ADDR_TASK_ENV: /* environmental monitor event */
		sc_dispatch_env_event( ev_code, ev_argc, &(event[i]), 
				       BRL1_QSIZE - i );
		break;

	      default: /* unhandled task type */
		L1_DBG_PRF(( "Unhandled event type received from system "
			     "controllers: source task %x\n",
			     (ev_src & L1_ADDR_TASK_MASK) >> L1_ADDR_TASK_SHFT
			   ));
	    }
	}
	
    }			
}

/* sc_listen sets up a service thread to listen for incoming events.
 */

void
sc_listen( l1sc_t *sc )
{
    int result;
    unsigned long pl = 0;
    brl1_sch_t *subch;

    char        msg[BRL1_QSIZE];
    int         len;    /* length of message being sent */
    int         ch;     /* system controller subchannel used */

    extern int msc_shutdown_pri;

    /* grab the designated "event subchannel" */
    SUBCH_LOCK( sc, pl );
    subch = &(sc->subch[BRL1_EVENT_SUBCH]);
    if( subch->use != BRL1_SUBCH_FREE ) {
	SUBCH_UNLOCK( sc, pl );
	printk(KERN_WARNING  "sysctl event subchannel in use! "
		 "Not monitoring sysctl events.\n" );
	return;
    }
    subch->use = BRL1_SUBCH_RSVD;
    SUBCH_UNLOCK( sc, pl );

    atomic_set(&subch->packet_arrived, 0);
    subch->target = BRL1_LOCALHUB_UART;
    spin_lock_init( &(subch->data_lock) );
    sv_init( &(subch->arrive_sv), &(subch->data_lock), SV_MON_SPIN | SV_ORDER_FIFO /* | SV_INTS */);
    subch->tx_notify = NULL;
    subch->rx_notify = sc_data_ready;
    subch->iqp = snia_kmem_zalloc_node( sizeof(sc_cq_t), KM_NOSLEEP,
				   NASID_TO_COMPACT_NODEID(sc->nasid) );
    ASSERT( subch->iqp );
    cq_init( subch->iqp );

    /* set up a thread to listen for events */
    sthread_create( "sysctl event handler", 0, 0, 0, msc_shutdown_pri,
		    KT_PS, (st_func_t *) sc_event,
		    (void *)sc, (void *)(uint64_t)BRL1_EVENT_SUBCH, 0, 0 );

    /* signal the L1 to begin sending events */
    bzero( msg, BRL1_QSIZE );
    ch = sc_open( sc, L1_ADDR_LOCAL );

    if( (len = sc_construct_msg( sc, ch, msg, BRL1_QSIZE,
				 L1_ADDR_TASK_GENERAL,
				 L1_REQ_EVENT_SUBCH, 2,
				 L1_ARG_INT, BRL1_EVENT_SUBCH )) < 0 )
    {
	sc_close( sc, ch );
	L1_DBG_PRF(( "Failure in sc_construct_msg (%d)\n", len ));
	goto err_return;
    }

    result = sc_command_kern( sc, ch, msg, msg, &len );
    if( result < 0 )
    {
	sc_close( sc, ch );
	L1_DBG_PRF(( "Failure in sc_command_kern (%d)\n", result ));
	goto err_return;
    }

    sc_close( sc, ch );

    result = sc_interpret_resp( msg, 0 );
    if( result < 0 )
    {
	L1_DBG_PRF(( "Failure in sc_interpret_resp (%d)\n", result ));
	goto err_return;
    }

    /* everything went fine; just return */
    return;
	
err_return:
    /* there was a problem; complain */
    printk(KERN_WARNING  "failed to set sysctl event-monitoring subchannel.  "
	     "Sysctl events will not be monitored.\n" );
}

#endif	/* LINUX_KERNEL_THREADS */