summaryrefslogtreecommitdiff
path: root/drivers/dahdi/xpp/card_pri.c
blob: 6780621fac1330f9cf3ec0d5bc9e600a32e622a0 (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
/*
 * Written by Oron Peled <oron@actcom.co.il>
 * Copyright (C) 2004-2006, Xorcom
 *
 * Parts derived from Cologne demo driver for the chip.
 *
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/delay.h>
#include "xpd.h"
#include "xproto.h"
#include "xpp_dahdi.h"
#include "card_pri.h"
#include "dahdi_debug.h"
#include "xbus-core.h"

static const char rcsid[] = "$Id$";

static DEF_PARM(int, debug, 0, 0644, "Print DBG statements");	/* must be before dahdi_debug.h */
static DEF_PARM(uint, poll_interval, 500, 0644, "Poll channel state interval in milliseconds (0 - disable)");

#define	PRI_LINES_BITMASK	BITMASK(31)
#define	PRI_SIGCAP	(		\
			DAHDI_SIG_EM		| \
			DAHDI_SIG_CLEAR		| \
			DAHDI_SIG_FXSLS		| \
			DAHDI_SIG_FXSGS		| \
			DAHDI_SIG_FXSKS		| \
			DAHDI_SIG_HARDHDLC	| \
			DAHDI_SIG_MTP2		| \
			DAHDI_SIG_FXOLS		| \
			DAHDI_SIG_FXOGS		| \
			DAHDI_SIG_FXOKS		| \
			DAHDI_SIG_CAS		| \
			DAHDI_SIG_EM_E1		| \
			DAHDI_SIG_DACS_RBS	\
			)

static bool is_sigtype_dchan(int sigtype)
{
	if((sigtype & DAHDI_SIG_HDLCRAW) == DAHDI_SIG_HDLCRAW)
		return 1;
	if((sigtype & DAHDI_SIG_HDLCFCS) == DAHDI_SIG_HDLCFCS)
		return 1;
	if((sigtype & DAHDI_SIG_HARDHDLC) == DAHDI_SIG_HARDHDLC)
		return 1;
	return 0;
}

#define	MAX_SLAVES		4		/* we have MUX of 4 clocks */

#define	PRI_PORT(xpd)	((xpd)->addr.subunit)
#define	CHAN_PER_REGS(p)	(((p)->is_esf) ? 2 : 4)

/*---------------- PRI Protocol Commands ----------------------------------*/

static bool pri_packet_is_valid(xpacket_t *pack);
static void pri_packet_dump(const char *msg, xpacket_t *pack);
#ifdef	OLD_PROC
static int proc_pri_info_read(char *page, char **start, off_t off, int count, int *eof, void *data);
static int proc_pri_info_write(struct file *file, const char __user *buffer, unsigned long count, void *data);
#endif
static int pri_startup(struct dahdi_span *span);
static int pri_shutdown(struct dahdi_span *span);
static int pri_rbsbits(struct dahdi_chan *chan, int bits);
static int pri_lineconfig(xpd_t *xpd, int lineconfig);
static void send_idlebits(xpd_t *xpd, bool saveold);

#define	PROC_REGISTER_FNAME	"slics"
#ifdef	OLD_PROC
#define	PROC_PRI_INFO_FNAME	"pri_info"
#endif

enum pri_protocol {
	PRI_PROTO_0  	= 0,
	PRI_PROTO_E1	= 1,
	PRI_PROTO_T1 	= 2,
	PRI_PROTO_J1 	= 3
};

static const char *pri_protocol_name(enum pri_protocol pri_protocol)
{
	static const char *protocol_names[] = {
		[PRI_PROTO_0] = "??",	/* unknown */
		[PRI_PROTO_E1] = "E1",
		[PRI_PROTO_T1] = "T1",
		[PRI_PROTO_J1] = "J1"
		};
	return protocol_names[pri_protocol];
}

static int pri_num_channels(enum pri_protocol pri_protocol)
{
	static int num_channels[] = {
		[PRI_PROTO_0] = 0,
		[PRI_PROTO_E1] = 31,
		[PRI_PROTO_T1] = 24,
		[PRI_PROTO_J1] = 0
		};
	return num_channels[pri_protocol];
}

static const char *type_name(enum pri_protocol pri_protocol)
{
	static const char	*names[4] = {
		[PRI_PROTO_0] = "PRI-Unknown",
		[PRI_PROTO_E1] = "E1",
		[PRI_PROTO_T1] = "T1",
		[PRI_PROTO_J1] = "J1"
	};

	return names[pri_protocol];
}

static int pri_linecompat(enum pri_protocol pri_protocol)
{
	static const int linecompat[] = {
		[PRI_PROTO_0] = 0,
		[PRI_PROTO_E1] =
			/* coding */
			DAHDI_CONFIG_CCS |
			DAHDI_CONFIG_CRC4 |
			/* framing */
			DAHDI_CONFIG_AMI | DAHDI_CONFIG_HDB3,
		[PRI_PROTO_T1] =
			/* coding */
			DAHDI_CONFIG_D4 |
			DAHDI_CONFIG_ESF |
			/* framing */
			DAHDI_CONFIG_AMI | DAHDI_CONFIG_B8ZS,
		[PRI_PROTO_J1] = 0
	};

	DBG(GENERAL, "pri_linecompat: pri_protocol=%d\n", pri_protocol);
	return linecompat[pri_protocol];
}

#define	PRI_DCHAN_IDX(priv)	((priv)->dchan_num - 1)

enum pri_led_state {
	PRI_LED_OFF		= 0x0,
	PRI_LED_ON		= 0x1,
	/*
	 * We blink by software from driver, so that
	 * if the driver malfunction that blink would stop.
	 */
	// PRI_LED_BLINK_SLOW	= 0x2,	/* 1/2 a second blink cycle */
	// PRI_LED_BLINK_FAST	= 0x3	/* 1/4 a second blink cycle */
};

enum pri_led_selectors {
	BOTTOM_RED_LED		= 0,
	BOTTOM_GREEN_LED	= 1,
	TOP_RED_LED		= 2,
	TOP_GREEN_LED		= 3,
};

#define	NUM_LEDS	4

struct pri_leds {
	byte	state:2;	/* enum pri_led_state */
	byte	led_sel:2;	/* enum pri_led_selectors */
	byte	reserved:4;
};

#define	REG_CCB1_T	0x2F	/* Clear Channel Register 1 */

#define	REG_FRS0	0x4C	/* Framer Receive Status Register 0 */
#define	REG_FRS0_T1_FSR	BIT(0)	/* T1 - Frame Search Restart Flag */
#define	REG_FRS0_LMFA	BIT(1)	/* Loss of Multiframe Alignment */
#define	REG_FRS0_E1_NMF	BIT(2)	/* E1 - No Multiframe Alignment Found */
#define	REG_FRS0_RRA	BIT(4)	/* Receive Remote Alarm: T1-YELLOW-Alarm */
#define	REG_FRS0_LFA	BIT(5)	/* Loss of Frame Alignment */
#define	REG_FRS0_AIS	BIT(6)	/* Alarm Indication Signal: T1-BLUE-Alarm */
#define	REG_FRS0_LOS	BIT(7)	/* Los Of Signal: T1-RED-Alarm */

#define	REG_FRS1	0x4D	/* Framer Receive Status Register 1 */

#define	REG_LIM0	0x36
#define	REG_LIM0_MAS	BIT(0)	/* Master Mode, DCO-R circuitry is frequency synchronized to the clock supplied by SYNC */
#define	REG_LIM0_RTRS	BIT(5)	/*
				 * Receive Termination Resistance Selection:
				 * integrated resistor to create 75 Ohm termination (100 || 300 = 75)
				 * 0 = 100 Ohm
				 * 1 = 75 Ohm
				 */
#define	REG_LIM0_LL	BIT(1)	/* LL (Local Loopback) */

#define	REG_FMR0	0x1C
#define	REG_FMR0_E_RC0	BIT(4)	/* Receive Code - LSB */
#define	REG_FMR0_E_RC1	BIT(5)	/* Receive Code - MSB */
#define	REG_FMR0_E_XC0	BIT(6)	/* Transmit Code - LSB */
#define	REG_FMR0_E_XC1	BIT(7)	/* Transmit Code - MSB */

#define	REG_FMR1	0x1D
#define	REG_FMR1_XAIS	BIT(0)	/* Transmit AIS toward transmit end */
#define	REG_FMR1_SSD0	BIT(1)
#define	REG_FMR1_ECM	BIT(2)
#define	REG_FMR1_T_CRC	BIT(3)	/* Enable CRC6 */
#define	REG_FMR1_E_XFS	BIT(3)	/* Transmit Framing Select */
#define	REG_FMR1_PMOD	BIT(4)	/* E1 = 0, T1/J1 = 1 */
#define	REG_FMR1_EDL	BIT(5)
#define	REG_FMR1_AFR	BIT(6)

#define	REG_FMR2	0x1E
#define	REG_FMR2_E_ALMF	BIT(0)	/* Automatic Loss of Multiframe */
#define	REG_FMR2_T_EXZE	BIT(0)	/* Excessive Zeros Detection Enable */
#define	REG_FMR2_E_AXRA	BIT(1)	/* Automatic Transmit Remote Alarm */
#define	REG_FMR2_T_AXRA	BIT(1)	/* Automatic Transmit Remote Alarm */
#define	REG_FMR2_E_PLB	BIT(2)	/* Payload Loop-Back */
#define	REG_FMR2_E_RFS0	BIT(6)	/* Receive Framing Select - LSB */
#define	REG_FMR2_E_RFS1	BIT(7)	/* Receive Framing Select - MSB */
#define	REG_FMR2_T_SSP	BIT(5)	/* Select Synchronization/Resynchronization Procedure */
#define	REG_FMR2_T_MCSP	BIT(6)	/* Multiple Candidates Synchronization Procedure */
#define	REG_FMR2_T_AFRS	BIT(7)	/* Automatic Force Resynchronization */

#define	REG_FMR3	0x31
#define	REG_FMR3_EXTIW	BIT(0)	/* Extended CRC4 to Non-CRC4 Interworking */

#define	REG_FMR4	0x20
#define	REG_FMR4_FM0	BIT(0)
#define	REG_FMR4_FM1	BIT(1)
#define	REG_FMR4_AUTO	BIT(2)
#define	REG_FMR4_SSC0	BIT(3)
#define	REG_FMR4_SSC1	BIT(4)
#define	REG_FMR4_XRA	BIT(5)	/* Transmit Remote Alarm (Yellow Alarm) */
#define	REG_FMR4_TM	BIT(6)
#define	REG_FMR4_AIS3	BIT(7)

#define	REG_XSW_E	0x20
#define	REG_XSW_E_XY4	BIT(0)
#define	REG_XSW_E_XY3	BIT(1)
#define	REG_XSW_E_XY2	BIT(2)
#define	REG_XSW_E_XY1	BIT(3)
#define	REG_XSW_E_XY0	BIT(4)
#define	REG_XSW_E_XRA	BIT(5)	/* Transmit Remote Alarm (Yellow Alarm) */
#define	REG_XSW_E_XTM	BIT(6)
#define	REG_XSW_E_XSIS	BIT(7)

#define REG_XSP_E	0x21
#define REG_FMR5_T	0x21
#define	REG_XSP_E_XSIF	BIT(2)	/* Transmit Spare Bit For International Use (FAS Word)  */
#define	REG_FMR5_T_XTM	BIT(2)	/* Transmit Transparent Mode  */
#define	REG_XSP_E_AXS	BIT(3)	/* Automatic Transmission of Submultiframe Status  */
#define	REG_XSP_E_EBP	BIT(4)	/* E-Bit Polarity, Si-bit position of every outgoing CRC multiframe  */
#define	REG_XSP_E_CASEN	BIT(6)	/* CAS: Channel Associated Signaling Enable  */
#define	REG_FMR5_T_EIBR	BIT(6)	/* CAS: Enable Internal Bit Robbing Access   */

#define REG_XC0_T	0x22	/* Transmit Control 0 */
#define REG_XC0_BRIF	BIT(5)	/* Bit Robbing Idle Function */

#define REG_CMDR_E	0x02	/* Command Register */
#define REG_CMDR_RRES	BIT(6)	/* Receiver    reset */
#define REG_CMDR_XRES	BIT(4)	/* Transmitter reset */

#define	REG_RC0		0x24
#define	REG_RC0_SJR	BIT(7)	/* T1 = 0, J1 = 1 */

#define	REG_CMR1	0x44
#define	REG_CMR1_DRSS	(BIT(7) | BIT(6))
#define	REG_CMR1_RS	(BIT(5) | BIT(4))
#define	REG_CMR1_STF	BIT(2)

#define	REG_RS1_E	0x70	/* Receive CAS Register 1	*/
#define	REG_RS2_E	0x71	/* Receive CAS Register 2	*/
#define	REG_RS3_E	0x72	/* Receive CAS Register 3	*/
#define	REG_RS4_E	0x73	/* Receive CAS Register 4	*/
#define	REG_RS5_E	0x74	/* Receive CAS Register 5	*/
#define	REG_RS6_E	0x75	/* Receive CAS Register 6	*/
#define	REG_RS7_E	0x76	/* Receive CAS Register 7	*/
#define	REG_RS8_E	0x77	/* Receive CAS Register 8	*/
#define	REG_RS9_E	0x78	/* Receive CAS Register 9	*/
#define	REG_RS10_E	0x79	/* Receive CAS Register 10	*/
#define	REG_RS11_E	0x7A	/* Receive CAS Register 11	*/
#define	REG_RS12_E	0x7B	/* Receive CAS Register 12	*/
#define	REG_RS13_E	0x7C	/* Receive CAS Register 13	*/
#define	REG_RS14_E	0x7D	/* Receive CAS Register 14	*/
#define	REG_RS15_E	0x7E	/* Receive CAS Register 15	*/
#define	REG_RS16_E	0x7F	/* Receive CAS Register 16	*/

#define	REG_PC2		0x81	/* Port Configuration 2	*/
#define	REG_PC3		0x82	/* Port Configuration 3	*/
#define	REG_PC4		0x83	/* Port Configuration 4	*/

#define	REG_XPM2	0x28	/* Transmit Pulse Mask 2 */

#define	VAL_PC_SYPR	0x00	/* Synchronous Pulse Receive (Input, low active) */
#define	VAL_PC_GPI	0x90	/* General purpose input */
#define	VAL_PC_GPOH	0x0A	/* General Purpose Output, high level */
#define	VAL_PC_GPOL	0x0B	/* General Purpose Output, low level */

#define	NUM_CAS_RS_E	(REG_RS16_E - REG_RS2_E + 1)
/* and of those, the ones used in T1: */
#define	NUM_CAS_RS_T	(REG_RS12_E - REG_RS1_E + 1)

struct PRI_priv_data {
	bool				clock_source;
#ifdef	OLD_PROC
	struct proc_dir_entry		*pri_info;
#endif
	enum pri_protocol		pri_protocol;
	xpp_line_t			rbslines;
	int				deflaw;
	unsigned int			dchan_num;
	bool				initialized;
	int				is_cas;

	unsigned int			chanconfig_dchan;
#define	NO_DCHAN	(0)
#define	DCHAN(p)	((p)->chanconfig_dchan)
#define	VALID_DCHAN(p)	(DCHAN(p) != NO_DCHAN)
#define	SET_DCHAN(p,d)	do { DCHAN(p) = (d); } while(0);

	byte				cas_rs_e[NUM_CAS_RS_E];
	byte				cas_ts_e[NUM_CAS_RS_E];
	uint				cas_replies;
	bool				is_esf;
	bool				local_loopback;
	uint				poll_noreplies;
	uint				layer1_replies;
	byte				reg_frs0;
	byte				reg_frs1;
	bool				layer1_up;
	int				alarms;
	byte				dchan_tx_sample;
	byte				dchan_rx_sample;
	uint				dchan_tx_counter;
	uint				dchan_rx_counter;
	bool				dchan_alive;
	uint				dchan_alive_ticks;
	enum pri_led_state		ledstate[NUM_LEDS];
};

static xproto_table_t	PROTO_TABLE(PRI);

DEF_RPACKET_DATA(PRI, SET_LED,	/* Set one of the LED's */
	struct pri_leds		pri_leds;
	);


static /* 0x33 */ DECLARE_CMD(PRI, SET_LED, enum pri_led_selectors led_sel, enum pri_led_state to_led_state);

#define	DO_LED(xpd, which, tostate)	\
		CALL_PROTO(PRI, SET_LED, (xpd)->xbus, (xpd), (which), (tostate))

/*---------------- PRI: Methods -------------------------------------------*/

static int query_subunit(xpd_t *xpd, byte regnum)
{
	XPD_DBG(REGS, xpd, "(%d%d): REG=0x%02X\n",
		xpd->addr.unit, xpd->addr.subunit,
		regnum);
	return xpp_register_request(
			xpd->xbus, xpd,
			PRI_PORT(xpd),		/* portno	*/
			0,			/* writing	*/
			regnum,
			0,			/* do_subreg	*/
			0,			/* subreg	*/
			0,			/* data_L	*/
			0,			/* do_datah	*/
			0,			/* data_H	*/
			0			/* should_reply	*/
			);
}


static int write_subunit(xpd_t *xpd, byte regnum, byte val)
{
	XPD_DBG(REGS, xpd, "(%d%d): REG=0x%02X dataL=0x%02X\n",
		xpd->addr.unit, xpd->addr.subunit,
		regnum, val);
	return xpp_register_request(
			xpd->xbus, xpd,
			PRI_PORT(xpd),		/* portno	*/
			1,			/* writing	*/
			regnum,
			0,			/* do_subreg	*/
			0,			/* subreg	*/
			val,			/* data_L	*/
			0,			/* do_datah	*/
			0,			/* data_H	*/
			0			/* should_reply	*/
			);
}

static int pri_write_reg(xpd_t *xpd, int regnum, byte val)
{
	XPD_DBG(REGS, xpd, "(%d%d): REG=0x%02X dataL=0x%02X\n",
		xpd->addr.unit, xpd->addr.subunit,
		regnum, val);
	return xpp_register_request(
			xpd->xbus, xpd,
			0,			/* portno=0	*/
			1,			/* writing	*/
			regnum,
			0,			/* do_subreg	*/
			0,			/* subreg	*/
			val,			/* data_L	*/
			0,			/* do_datah	*/
			0,			/* data_H	*/
			0			/* should_reply	*/
			);
}

static int cas_regbase(xpd_t *xpd)
{
	struct PRI_priv_data	*priv;

	priv = xpd->priv;
	switch (priv->pri_protocol) {
	case PRI_PROTO_E1:
		return REG_RS2_E;
	case PRI_PROTO_T1:
		/* fall-through */
	case PRI_PROTO_J1:
		return REG_RS1_E;
	case PRI_PROTO_0:
		/* fall-through */
		;
	}
	BUG();
	return 0;
}

static int cas_numregs(xpd_t *xpd)
{
	struct PRI_priv_data	*priv;

	priv = xpd->priv;
	switch (priv->pri_protocol) {
	case PRI_PROTO_E1:
		return NUM_CAS_RS_E;
	case PRI_PROTO_T1:
		/* fall-through */
	case PRI_PROTO_J1:
		return NUM_CAS_RS_T;
	case PRI_PROTO_0:
		/* fall-through */
		;
	}
	BUG();
	return 0;
}

static int write_cas_reg(xpd_t *xpd, int rsnum, byte val)
{
	struct PRI_priv_data	*priv;
	int			regbase = cas_regbase(xpd);
	int			num_cas_rs = cas_numregs(xpd);
	int			regnum;
	bool			is_d4 = 0;

	BUG_ON(!xpd);
	priv = xpd->priv;
	if ((priv->pri_protocol == PRI_PROTO_T1) && !priv->is_esf) {
		/* same data should be copied to RS7..12 in D4 only */
		is_d4 = 1;
	}
	if (rsnum < 0 || rsnum >= num_cas_rs) {
		XPD_ERR(xpd, "RBS(TX): rsnum=%d\n", rsnum);
		BUG();
	}
	regnum = regbase + rsnum;
	priv->cas_ts_e[rsnum] = val;
	XPD_DBG(SIGNAL, xpd, "RBS(TX): reg=0x%X val=0x%02X\n", regnum, val);
	write_subunit(xpd, regbase + rsnum, val);
	if (is_d4) {
		/* same data should be copied to RS7..12 in D4 only */
		regnum = REG_RS7_E + rsnum;
		XPD_DBG(SIGNAL, xpd, "RBS(TX): reg=0x%X val=0x%02X\n",
				regnum, val);
		write_subunit(xpd, regnum, val);
	}
	return 0;
}

#ifdef	OLD_PROC
static void pri_proc_remove(xbus_t *xbus, xpd_t *xpd)
{
	struct PRI_priv_data	*priv;

	BUG_ON(!xpd);
	priv = xpd->priv;
	XPD_DBG(PROC, xpd, "\n");
#ifdef	CONFIG_PROC_FS
	if(priv->pri_info) {
		XPD_DBG(PROC, xpd, "Removing xpd PRI_INFO file\n");
		remove_proc_entry(PROC_PRI_INFO_FNAME, xpd->proc_xpd_dir);
	}
#endif
}
#endif

#ifdef	OLD_PROC
static int pri_proc_create(xbus_t *xbus, xpd_t *xpd)
{
	struct PRI_priv_data	*priv;

	BUG_ON(!xpd);
	priv = xpd->priv;
	XPD_DBG(PROC, xpd, "\n");
#ifdef	CONFIG_PROC_FS
	XPD_DBG(PROC, xpd, "Creating PRI_INFO file\n");
	priv->pri_info = create_proc_entry(PROC_PRI_INFO_FNAME, 0644, xpd->proc_xpd_dir);
	if(!priv->pri_info) {
		XPD_ERR(xpd, "Failed to create proc '%s'\n", PROC_PRI_INFO_FNAME);
		goto err;
	}
	SET_PROC_DIRENTRY_OWNER(priv->pri_info);
	priv->pri_info->write_proc = proc_pri_info_write;
	priv->pri_info->read_proc = proc_pri_info_read;
	priv->pri_info->data = xpd;
#endif
	return 0;
err:
	pri_proc_remove(xbus, xpd);
	return -EINVAL;
}
#endif

static bool valid_pri_modes(const xpd_t *xpd)
{
	struct PRI_priv_data	*priv;

	BUG_ON(!xpd);
	priv = xpd->priv;
	if(
		priv->pri_protocol != PRI_PROTO_E1 &&
		priv->pri_protocol != PRI_PROTO_T1 &&
		priv->pri_protocol != PRI_PROTO_J1)
		return 0;
	return 1;
}

static void PRI_card_pcm_recompute(xpd_t *xpd,
		xpp_line_t pcm_mask)
{
	struct PRI_priv_data	*priv;
	int			i;
	int			line_count = 0;
	unsigned long		flags;
	uint			pcm_len;

	BUG_ON(!xpd);
	priv = xpd->priv;
	spin_lock_irqsave(&PHONEDEV(xpd).lock_recompute_pcm, flags);
	//XPD_DBG(SIGNAL, xpd, "pcm_mask=0x%X\n", pcm_mask);
	/* Add/remove all the trivial cases */
	pcm_mask |= PHONEDEV(xpd).offhook_state;
	for_each_line(xpd, i)
		if (IS_SET(pcm_mask, i))
			line_count++;
	if(priv->is_cas) {
		if(priv->pri_protocol == PRI_PROTO_E1) {
			/* CAS: Don't send PCM to D-Channel */
			line_count--;
			pcm_mask &= ~BIT(PRI_DCHAN_IDX(priv));
		}
	}
	/*
	 * FIXME: Workaround a bug in sync code of the Astribank.
	 *        Send dummy PCM for sync.
	 */
	if (xpd->addr.unit == 0 && pcm_mask == 0) {
		pcm_mask = BIT(0);
		line_count = 1;
	}
	pcm_len = (line_count)
		? RPACKET_HEADERSIZE + sizeof(xpp_line_t) +
			line_count * DAHDI_CHUNKSIZE
		: 0L;
	update_wanted_pcm_mask(xpd, pcm_mask, pcm_len);
	spin_unlock_irqrestore(&PHONEDEV(xpd).lock_recompute_pcm, flags);
}

/*
 * Set E1/T1/J1
 * May only be called on unregistered xpd's
 * (the span and channel description are set according to this)
 */
static int set_pri_proto(xpd_t *xpd, enum pri_protocol set_proto)
{
	struct PRI_priv_data	*priv;
	int			deflaw;
	unsigned int		dchan_num;
	int			default_lineconfig = 0;
	int			ret;

	BUG_ON(!xpd);
	priv = xpd->priv;
	if(SPAN_REGISTERED(xpd)) {
		XPD_NOTICE(xpd, "Registered as span %d. Cannot do setup pri protocol (%s)\n",
			PHONEDEV(xpd).span.spanno, __FUNCTION__);
		return -EBUSY;
	}
	if(priv->pri_protocol != PRI_PROTO_0) {
		if(priv->pri_protocol == set_proto) {
			XPD_NOTICE(xpd, "Already in protocol %s. Ignored\n", pri_protocol_name(set_proto));
			return 0;
		} else {
			XPD_INFO(xpd, "Switching from %s to %s\n",
				pri_protocol_name(priv->pri_protocol),
				pri_protocol_name(set_proto));
		}
	}
	switch(set_proto) {
		case PRI_PROTO_E1:
			deflaw = DAHDI_LAW_ALAW;
			dchan_num = 16;
			default_lineconfig = DAHDI_CONFIG_CCS | DAHDI_CONFIG_CRC4 | DAHDI_CONFIG_HDB3;
			break;
		case PRI_PROTO_T1:
			deflaw = DAHDI_LAW_MULAW;
			dchan_num = 24;
			default_lineconfig = DAHDI_CONFIG_ESF | DAHDI_CONFIG_B8ZS;
			break;
		case PRI_PROTO_J1:
			/*
			 * Check all assumptions
			 */
			deflaw = DAHDI_LAW_MULAW;
			dchan_num = 24;
			default_lineconfig = 0;	/* FIXME: J1??? */
			XPD_NOTICE(xpd, "J1 is not supported yet\n");
			return -ENOSYS;
		default:
			XPD_ERR(xpd, "%s: Unknown pri protocol = %d\n",
				__FUNCTION__, set_proto);
			return -EINVAL;
	}
	priv->pri_protocol = set_proto;
	priv->is_cas = -1;
	PHONEDEV(xpd).channels = pri_num_channels(set_proto);
	PHONEDEV(xpd).offhook_state = BITMASK(PHONEDEV(xpd).channels);
	CALL_PHONE_METHOD(card_pcm_recompute, xpd, 0);
	priv->deflaw = deflaw;
	priv->dchan_num = dchan_num;
	priv->local_loopback = 0;
	xpd->type_name = type_name(priv->pri_protocol);
	XPD_DBG(GENERAL, xpd, "%s, channels=%d, dchan_num=%d, deflaw=%d\n",
			pri_protocol_name(set_proto),
			PHONEDEV(xpd).channels,
			priv->dchan_num,
			priv->deflaw
			);
	/*
	 * Must set default now, so layer1 polling (Register REG_FRS0) would
	 * give reliable results.
	 */
	ret = pri_lineconfig(xpd, default_lineconfig);
	if(ret) {
		XPD_NOTICE(xpd, "Failed setting PRI default line config\n");
		return ret;
	}
	return 0;
}

static void dahdi_update_syncsrc(xpd_t *xpd)
{
	struct PRI_priv_data	*priv;
	xpd_t			*subxpd;
	int			best_spanno = 0;
	int			i;

	if(!SPAN_REGISTERED(xpd))
		return;
	for(i = 0; i < MAX_SLAVES; i++) {
		subxpd = xpd_byaddr(xpd->xbus, xpd->addr.unit, i);
		if(!subxpd)
			continue;
		priv = subxpd->priv;
		if(priv->clock_source && priv->alarms == 0) {
			if(best_spanno)
				XPD_ERR(xpd, "Duplicate XPD's with clock_source=1\n");
			best_spanno = PHONEDEV(subxpd).span.spanno;
		}
	}
	for(i = 0; i < MAX_SLAVES; i++) {
		subxpd = xpd_byaddr(xpd->xbus, xpd->addr.unit, i);
		if(!subxpd)
			continue;
		if(PHONEDEV(subxpd).span.syncsrc == best_spanno)
			XPD_DBG(SYNC, xpd, "Setting SyncSource to span %d\n", best_spanno);
		else
			XPD_DBG(SYNC, xpd, "Slaving to span %d\n", best_spanno);
		PHONEDEV(subxpd).span.syncsrc = best_spanno;
	}
}

/*
 * Called from:
 *   - set_master_mode() --
 *       As a result of dahdi_cfg
 *   - layer1_state() --
 *       As a result of an alarm.
 */
static void set_clocking(xpd_t *xpd)
{
	xbus_t			*xbus;
	xpd_t			*best_xpd = NULL;
	int			best_subunit = -1;	/* invalid */
	unsigned int		best_subunit_prio = INT_MAX;
	int			i;

	xbus = xpd->xbus;
	/* Find subunit with best timing priority */
	for(i = 0; i < MAX_SLAVES; i++) {
		struct PRI_priv_data	*priv;
		xpd_t			*subxpd;
		
		subxpd = xpd_byaddr(xbus, xpd->addr.unit, i);
		if(!subxpd)
			continue;
		priv = subxpd->priv;
		if(priv->alarms != 0)
			continue;
		if(PHONEDEV(subxpd).timing_priority > 0 && PHONEDEV(subxpd).timing_priority < best_subunit_prio) {
			best_xpd = subxpd;
			best_subunit = i;
			best_subunit_prio = PHONEDEV(subxpd).timing_priority;
		}
	}
	/* Now set it */
	if(best_xpd && ((struct PRI_priv_data *)(best_xpd->priv))->clock_source == 0) {
		byte	reg_pc_init[] = { VAL_PC_GPI, VAL_PC_GPI, VAL_PC_GPI };

		for(i = 0; i < ARRAY_SIZE(reg_pc_init); i++) {
			byte	reg_pc = reg_pc_init[i];

			reg_pc |= (best_subunit & (1 << i)) ? VAL_PC_GPOH : VAL_PC_GPOL;
			XPD_DBG(SYNC, best_xpd,
					"ClockSource Set: PC%d=0x%02X\n", 2+i, reg_pc);
			pri_write_reg(xpd, REG_PC2 + i, reg_pc);
		}
		((struct PRI_priv_data *)(best_xpd->priv))->clock_source = 1;
	}
	/* clear old clock sources */
	for(i = 0; i < MAX_SLAVES; i++) {
		struct PRI_priv_data	*priv;
		xpd_t			*subxpd;

		subxpd = xpd_byaddr(xbus, xpd->addr.unit, i);
		if(subxpd && subxpd != best_xpd) {
			XPD_DBG(SYNC, subxpd, "Clearing clock source\n");
			priv = subxpd->priv;
			priv->clock_source = 0;
		}
	}
	dahdi_update_syncsrc(xpd);
}

static void set_reg_lim0(const char *msg, xpd_t *xpd)
{
	struct PRI_priv_data	*priv;
	bool			is_master_mode;
	bool			localloop;
	byte			lim0 = 0;

	BUG_ON(!xpd);
	priv = xpd->priv;
	BUG_ON(!priv);
	is_master_mode = PHONEDEV(xpd).timing_priority == 0;
	localloop = priv->local_loopback;
	lim0 |= (localloop) ? REG_LIM0_LL : 0;
	if(is_master_mode)
		lim0 |=  REG_LIM0_MAS;
	else
		lim0 &= ~REG_LIM0_MAS;
	XPD_DBG(SIGNAL, xpd, "%s(%s): %s, %s\n", __FUNCTION__, msg,
		(is_master_mode) ? "MASTER" : "SLAVE",
		(localloop) ? "LOCALLOOP" : "NO_LOCALLOOP");
	write_subunit(xpd, REG_LIM0 , lim0);
}

/*
 * Normally set by the timing parameter in /etc/dahdi/system.conf
 * If this is called by dahdi_cfg, than it's too late to change
 * dahdi sync priority (we are already registered)
 *
 * Also called from set_localloop()
 */
static int set_master_mode(const char *msg, xpd_t *xpd)
{
	struct PRI_priv_data	*priv;

	BUG_ON(!xpd);
	XPD_DBG(SIGNAL, xpd, "\n");
	priv = xpd->priv;
	set_reg_lim0(__FUNCTION__, xpd);
	set_clocking(xpd);
	return 0;
}

static int set_localloop(xpd_t *xpd, bool localloop)
{
	struct PRI_priv_data	*priv;

	BUG_ON(!xpd);
	priv = xpd->priv;
	if(SPAN_REGISTERED(xpd)) {
		XPD_NOTICE(xpd, "Registered as span %d. Cannot do %s\n",
			PHONEDEV(xpd).span.spanno, __FUNCTION__);
		return -EBUSY;
	}
	priv->local_loopback = localloop;
	XPD_DBG(SIGNAL, xpd, "%s: %s\n", __FUNCTION__, (localloop) ? "LOCALLOOP" : "NO");
	set_master_mode(__FUNCTION__, xpd);
	return 0;
}

#define	VALID_CONFIG(bit,flg,str)	[bit] = { .flags = flg, .name = str }

static const struct {
	const char	*name;
	const int	flags;
} valid_spanconfigs[sizeof(unsigned int)*8] = {
	/* These apply to T1 */
	VALID_CONFIG(4, DAHDI_CONFIG_D4, "D4"),
	VALID_CONFIG(5, DAHDI_CONFIG_ESF, "ESF"),
	VALID_CONFIG(6, DAHDI_CONFIG_AMI, "AMI"),
	VALID_CONFIG(7, DAHDI_CONFIG_B8ZS, "B8ZS"),
	/* These apply to E1 */
	VALID_CONFIG(8, DAHDI_CONFIG_CCS, "CCS"),
	VALID_CONFIG(9, DAHDI_CONFIG_HDB3, "HDB3"),
	VALID_CONFIG(10, DAHDI_CONFIG_CRC4, "CRC4"),
};

/*
 * Mark the lines as CLEAR or RBS signalling.
 * With T1, we need to mark the CLEAR lines on the REG_CCB1_T registers
 * Should be called only when we are registered to DAHDI
 * The channo parameter:
 *	channo == 0: set lines for the whole span
 *	channo != 0: only set modified lines
 */
static void set_rbslines(xpd_t *xpd, int channo)
{
	struct PRI_priv_data	*priv;
	xpp_line_t		new_rbslines = 0;
	xpp_line_t		modified_lines;
	int			i;

	priv = xpd->priv;
	for_each_line(xpd, i) {
		struct dahdi_chan	*chan = XPD_CHAN(xpd, i);

		if(chan->flags & DAHDI_FLAG_CLEAR)
			BIT_CLR(new_rbslines, i);
		else
			BIT_SET(new_rbslines, i);
	}
	new_rbslines &= BITMASK(PHONEDEV(xpd).channels);
	modified_lines = priv->rbslines ^ new_rbslines;
	XPD_DBG(DEVICES, xpd, "RBSLINES-%d(%s): 0x%X\n",
		channo, pri_protocol_name(priv->pri_protocol), new_rbslines);
	if((priv->pri_protocol == PRI_PROTO_T1) || (priv->pri_protocol == PRI_PROTO_J1)) {
		byte	clear_lines = 0;	/* Mark clear lines */
		bool	reg_changed = 0;

		for_each_line(xpd, i) {
			int	bytenum = i / 8;
			int	bitnum = i % 8;

			if(!IS_SET(new_rbslines, i)) {
				BIT_SET(clear_lines, (7 - bitnum));
			}
			if(IS_SET(modified_lines, i))
				reg_changed = 1;
			if(bitnum == 7) {
				if(channo == 0 || reg_changed) {
					bytenum += REG_CCB1_T;
					XPD_DBG(DEVICES, xpd, "RBS(%s): modified=0x%X rbslines=0x%X reg=0x%X clear_lines=0x%X\n",
							pri_protocol_name(priv->pri_protocol),
							modified_lines, new_rbslines, bytenum, clear_lines);
					write_subunit(xpd, bytenum, clear_lines);
				}
				clear_lines = 0;
				reg_changed = 0;
			}
		}
	}
	priv->rbslines = new_rbslines;
}

static int set_mode_cas(xpd_t *xpd, bool want_cas)
{
	struct PRI_priv_data	*priv;

	priv = xpd->priv;
	XPD_INFO(xpd, "Setting TDM to %s\n", (want_cas) ? "CAS" : "PRI");
	if(want_cas) {
		priv->is_cas = 1;
		priv->dchan_alive = 0;
	} else {
		priv->is_cas = 0;
	}
	return 0;
}

static int pri_lineconfig(xpd_t *xpd, int lineconfig)
{
	struct PRI_priv_data	*priv;
	const char		*framingstr = "";
	const char		*codingstr = "";
	const char		*crcstr = "";
#ifdef JAPANEZE_SUPPORT
	byte			rc0 = 0;	/* FIXME: PCM offsets */
#endif
	byte			fmr0 = 0;
	byte			fmr1 = REG_FMR1_ECM;
	byte			fmr2 = 0;
	byte			fmr3 = 0;	/* write only for CRC4 */
	byte			fmr4 = 0;
	byte                    cmdr = REG_CMDR_RRES | REG_CMDR_XRES;
	byte			xsp  = 0;
	unsigned int		bad_bits;
	bool			force_cas = 0;
	int			i;

	BUG_ON(!xpd);
	priv = xpd->priv;
	/*
	 * validate
	 */
	bad_bits = lineconfig & pri_linecompat(priv->pri_protocol);
	bad_bits = bad_bits ^ lineconfig;
	for(i = 0; i < ARRAY_SIZE(valid_spanconfigs); i++) {
		unsigned int	flags = valid_spanconfigs[i].flags;

		if(bad_bits & BIT(i)) {
			if(flags) {
				XPD_ERR(xpd,
					"Bad config item '%s' for %s. Ignore\n",
					valid_spanconfigs[i].name,
					pri_protocol_name(priv->pri_protocol));
			} else {
				/* we got real garbage */
				XPD_ERR(xpd,
					"Unknown config item 0x%lX for %s. Ignore\n",
					BIT(i),
					pri_protocol_name(priv->pri_protocol));
			}
		}
		if(flags && flags != BIT(i)) {
			ERR("%s: BUG: i=%d flags=0x%X\n",
				__FUNCTION__, i, flags);
			// BUG();
		}
	}
	if(bad_bits)
		goto bad_lineconfig;
	if(priv->pri_protocol == PRI_PROTO_E1) {
		fmr1 |= REG_FMR1_AFR;
		fmr2 = REG_FMR2_E_AXRA | REG_FMR2_E_ALMF;	/* 0x03 */
		fmr4 = 0x9F;								/*  E1.XSW:  All spare bits = 1*/
		xsp |= REG_XSP_E_EBP | REG_XSP_E_AXS | REG_XSP_E_XSIF;
	} else if(priv->pri_protocol == PRI_PROTO_T1) {
		fmr1 |= REG_FMR1_PMOD | REG_FMR1_T_CRC;
		fmr2 = REG_FMR2_T_SSP | REG_FMR2_T_AXRA;	/* 0x22 */
		fmr4 = 0x0C;
		xsp &= ~REG_FMR5_T_XTM;
		force_cas = 1;					/* T1 - Chip always in CAS mode */
	} else if(priv->pri_protocol == PRI_PROTO_J1) {
		fmr1 |= REG_FMR1_PMOD;
		fmr4 = 0x1C;
		xsp &= ~REG_FMR5_T_XTM;
		force_cas = 1;					/* T1 - Chip always in CAS mode */
		XPD_ERR(xpd, "J1 unsupported yet\n");
		return -ENOSYS;
	}
	if(priv->local_loopback)
		fmr2 |= REG_FMR2_E_PLB;
	/* framing first */
	if (lineconfig & DAHDI_CONFIG_B8ZS) {
		framingstr = "B8ZS";
		fmr0 = REG_FMR0_E_XC1 | REG_FMR0_E_XC0 | REG_FMR0_E_RC1 | REG_FMR0_E_RC0;
	} else if (lineconfig & DAHDI_CONFIG_AMI) {
		framingstr = "AMI";
		fmr0 = REG_FMR0_E_XC1 | REG_FMR0_E_RC1;
		/*
		 * From Infineon Errata Sheet: PEF 22554, Version 3.1
		 * Problem: Incorrect CAS Receiption when
		 *          using AMI receive line code
		 * Workaround: For E1,
		 *               "...The receive line coding HDB3 is
		 *                recommended instead."
		 *             For T1,
		 *               "...in T1 mode it is recommended to
		 *                configure the Rx side to B8ZS coding"
		 * For both cases this is the same bit in FMR0
		 */
		if(priv->pri_protocol == PRI_PROTO_J1)
			XPD_NOTICE(xpd, "J1 is not supported yet\n");
		else
			fmr0 |= REG_FMR0_E_RC0;
	} else if (lineconfig & DAHDI_CONFIG_HDB3) {
		framingstr = "HDB3";
		fmr0 = REG_FMR0_E_XC1 | REG_FMR0_E_XC0 | REG_FMR0_E_RC1 | REG_FMR0_E_RC0;
	} else {
		XPD_NOTICE(xpd, "Bad lineconfig. Not (B8ZS|AMI|HDB3). Ignored.\n");
		return -EINVAL;
	}
	/* then coding */
	priv->is_esf = 0;
	if (lineconfig & DAHDI_CONFIG_ESF) {
		codingstr = "ESF";
		fmr4 |= REG_FMR4_FM1;
		fmr2 |= REG_FMR2_T_AXRA | REG_FMR2_T_MCSP | REG_FMR2_T_SSP;
		priv->is_esf = 1;
	} else if (lineconfig & DAHDI_CONFIG_D4) {
		codingstr = "D4";
	} else if (lineconfig & DAHDI_CONFIG_CCS) {
		codingstr = "CCS";
		set_mode_cas(xpd, 0);	/* In E1 we know right from the span statement. */
	} else {
		codingstr = "CAS";	/* In E1 we know right from the span statement. */
		force_cas = 1;
		set_mode_cas(xpd, 1);
	}
	CALL_PHONE_METHOD(card_pcm_recompute, xpd, 0);
	/*
	 * E1's can enable CRC checking
	 * CRC4 is legal only for E1, and it is checked by pri_linecompat()
	 * in the beginning of the function.
	 */
	if (lineconfig & DAHDI_CONFIG_CRC4) {
		crcstr = "CRC4";
		fmr1 |= REG_FMR1_E_XFS;
		fmr2 |= REG_FMR2_E_RFS1;
		fmr3 |= REG_FMR3_EXTIW;
	}
	XPD_DBG(GENERAL, xpd, "[%s] lineconfig=%s/%s/%s %s (0x%X)\n",
		(priv->clock_source)?"MASTER":"SLAVE",
		framingstr, codingstr, crcstr,
		(lineconfig & DAHDI_CONFIG_NOTOPEN)?"YELLOW":"",
		lineconfig);
	set_reg_lim0(__FUNCTION__, xpd);
	XPD_DBG(GENERAL, xpd, "%s: fmr1(0x%02X) = 0x%02X\n", __FUNCTION__, REG_FMR1, fmr1);
	write_subunit(xpd, REG_FMR1, fmr1);
	XPD_DBG(GENERAL, xpd, "%s: fmr2(0x%02X) = 0x%02X\n", __FUNCTION__, REG_FMR2, fmr2);
	write_subunit(xpd, REG_FMR2, fmr2);
	XPD_DBG(GENERAL, xpd, "%s: fmr0(0x%02X) = 0x%02X\n", __FUNCTION__, REG_FMR0, fmr0);
	write_subunit(xpd, REG_FMR0, fmr0);
	XPD_DBG(GENERAL, xpd, "%s: fmr4(0x%02X) = 0x%02X\n", __FUNCTION__, REG_FMR4, fmr4);
	write_subunit(xpd, REG_FMR4, fmr4);
	if(fmr3) {
		XPD_DBG(GENERAL, xpd, "%s: fmr3(0x%02X) = 0x%02X\n", __FUNCTION__, REG_FMR3, fmr3);
		write_subunit(xpd, REG_FMR3, fmr3);
	}
	XPD_DBG(GENERAL, xpd, "%s: cmdr(0x%02X) = 0x%02X\n", __FUNCTION__, REG_CMDR_E, cmdr);
	write_subunit(xpd, REG_CMDR_E, cmdr);
#ifdef JAPANEZE_SUPPORT
	if(rc0) {
		XPD_DBG(GENERAL, xpd, "%s: rc0(0x%02X) = 0x%02X\n", __FUNCTION__, REG_RC0, rc0);
		write_subunit(xpd, REG_RC0, rc0);
	}
#endif
	if(force_cas) {
		xsp |= REG_XSP_E_CASEN;	/* Same as REG_FMR5_T_EIBR for T1 */
	}
	XPD_DBG(GENERAL, xpd, "%s: xsp(0x%02X) = 0x%02X\n", __FUNCTION__, REG_XSP_E, xsp);
	write_subunit(xpd, REG_XSP_E, xsp);
	return 0;
bad_lineconfig:
	XPD_ERR(xpd, "Bad lineconfig. Abort\n");
	return -EINVAL;
}

/*
 * Called only for 'span' keyword in /etc/dahdi/system.conf
 */

static int pri_spanconfig(struct dahdi_span *span, struct dahdi_lineconfig *lc)
{
	struct phonedev	*phonedev = container_of(span, struct phonedev, span);
	xpd_t		*xpd = container_of(phonedev, struct xpd, phonedev);
	struct PRI_priv_data	*priv;
	int			ret;

	BUG_ON(!xpd);
	priv = xpd->priv;
	if(lc->span != PHONEDEV(xpd).span.spanno) {
		XPD_ERR(xpd, "I am span %d but got spanconfig for span %d\n",
			PHONEDEV(xpd).span.spanno, lc->span);
		return -EINVAL;
	}
	/*
	 * FIXME: lc->name is unused by dahdi_cfg and dahdi...
	 *        We currently ignore it also.
	 */
	XPD_DBG(GENERAL, xpd, "[%s] lbo=%d lineconfig=0x%X sync=%d\n",
		(priv->clock_source)?"MASTER":"SLAVE", lc->lbo, lc->lineconfig, lc->sync);
	ret = pri_lineconfig(xpd, lc->lineconfig);
	if(!ret) {
		span->lineconfig = lc->lineconfig;
		PHONEDEV(xpd).timing_priority = lc->sync;
		set_master_mode("spanconfig", xpd);
		elect_syncer("PRI-master_mode");
	}
	return ret;
}

/*
 * Set signalling type (if appropriate)
 * Called from dahdi with spinlock held on chan. Must not call back
 * dahdi functions.
 */
static int pri_chanconfig(struct dahdi_chan *chan, int sigtype)
{
	struct phonedev	*phonedev = container_of(chan->span, struct phonedev, span);
	xpd_t		*xpd = container_of(phonedev, struct xpd, phonedev);
	struct PRI_priv_data	*priv;

	BUG_ON(!xpd);
	priv = xpd->priv;
	DBG(GENERAL, "channel %d (%s) -> %s\n", chan->channo, chan->name, sig2str(sigtype));
	/*
	 * Some bookkeeping to check if we have DChan defined or not
	 * FIXME: actually use this to prevent duplicate DChan definitions
	 *        and prevent DChan definitions with CAS.
	 */
	if(is_sigtype_dchan(sigtype)) {
		if (VALID_DCHAN(priv) && DCHAN(priv) != chan->channo) {
			ERR("channel %d (%s) marked DChan but also channel %d.\n",
				chan->channo, chan->name, DCHAN(priv));
			return -EINVAL;
		}
		XPD_DBG(GENERAL, xpd, "channel %d (%s) marked as DChan\n", chan->channo, chan->name);
		SET_DCHAN(priv, chan->channo);
		/* In T1, we don't know before-hand */
		if(priv->pri_protocol != PRI_PROTO_E1 && priv->is_cas != 0) {
			set_mode_cas(xpd, 0);
		}
	} else {
		if(chan->channo == 1) {
			XPD_DBG(GENERAL, xpd, "channel %d (%s) marked a not DChan\n", chan->channo, chan->name);
			SET_DCHAN(priv, NO_DCHAN);
		}
		/* In T1, we don't know before-hand */
		if(priv->pri_protocol != PRI_PROTO_E1 && priv->is_cas != 1)
			set_mode_cas(xpd, 1);
	}
	if(PHONEDEV(xpd).span.flags & DAHDI_FLAG_RUNNING) {
		XPD_DBG(DEVICES, xpd, "Span is RUNNING. Updating rbslines.\n");
		set_rbslines(xpd, chan->channo);
	}
	// FIXME: sanity checks:
	// - should be supported (within the sigcap)
	// - should not replace fxs <->fxo ??? (covered by previous?)
	return 0;
}

static xpd_t *PRI_card_new(xbus_t *xbus, int unit, int subunit, const xproto_table_t *proto_table,
	byte subtype, int subunits, int subunit_ports, bool to_phone)
{
	xpd_t			*xpd = NULL;
	struct PRI_priv_data	*priv;
	int			channels = min(31, CHANNELS_PERXPD);	/* worst case */

	if(subunit_ports != 1) {
		XBUS_ERR(xbus, "Bad subunit_ports=%d\n", subunit_ports);
		return NULL;
	}
	XBUS_DBG(GENERAL, xbus, "\n");
	xpd = xpd_alloc(xbus, unit, subunit, subtype, subunits, sizeof(struct PRI_priv_data), proto_table, channels);
	if(!xpd)
		return NULL;
	priv = xpd->priv;
	priv->pri_protocol = PRI_PROTO_0;		/* Default, changes in set_pri_proto() */
	priv->deflaw = DAHDI_LAW_DEFAULT;		/* Default, changes in set_pri_proto() */
	xpd->type_name = type_name(priv->pri_protocol);
#ifdef	OLD_PROC
	if(pri_proc_create(xbus, xpd) < 0) {
		xpd_free(xpd);
		return NULL;
	}
#endif
	xbus->sync_mode_default = SYNC_MODE_AB;
	return xpd;
}

static int PRI_card_init(xbus_t *xbus, xpd_t *xpd)
{
	struct PRI_priv_data	*priv;
	int			ret = 0;
	xproto_table_t		*proto_table;

	BUG_ON(!xpd);
	XPD_DBG(GENERAL, xpd, "\n");
	xpd->type = XPD_TYPE_PRI;
	proto_table = &PROTO_TABLE(PRI);
	priv = xpd->priv;
	if(priv->pri_protocol == PRI_PROTO_0) {
		/*
		 * init_card_* script didn't set pri protocol
		 * Let's have a default E1
		 */
		ret = set_pri_proto(xpd, PRI_PROTO_E1);
		if(ret < 0)
			goto err;
	}
	SET_DCHAN(priv, NO_DCHAN);
	/*
	 * initialization script should have set correct
	 * operating modes.
	 */
	if(!valid_pri_modes(xpd)) {
		XPD_NOTICE(xpd, "PRI protocol not set\n");
		goto err;
	}
	xpd->type_name = type_name(priv->pri_protocol);
	PHONEDEV(xpd).direction = TO_PSTN;
	XPD_DBG(DEVICES, xpd, "%s\n", xpd->type_name);
	PHONEDEV(xpd).timing_priority = 1;		/* High priority SLAVE */
	set_master_mode(__FUNCTION__, xpd);
	for(ret = 0; ret < NUM_LEDS; ret++) {
		DO_LED(xpd, ret, PRI_LED_ON);
		msleep(20);
		DO_LED(xpd, ret, PRI_LED_OFF);
	}
	priv->initialized = 1;
	return 0;
err:
#ifdef	OLD_PROC
	pri_proc_remove(xbus, xpd);
#endif
	XPD_ERR(xpd, "Failed initializing registers (%d)\n", ret);
	return ret;
}

static int PRI_card_remove(xbus_t *xbus, xpd_t *xpd)
{
	struct PRI_priv_data	*priv;

	BUG_ON(!xpd);
	priv = xpd->priv;
	XPD_DBG(GENERAL, xpd, "\n");
#ifdef	OLD_PROC
	pri_proc_remove(xbus, xpd);
#endif
	return 0;
}

#ifdef	DAHDI_AUDIO_NOTIFY
static int pri_audio_notify(struct dahdi_chan *chan, int on)
{
	xpd_t		*xpd = chan->pvt;
	int		pos = chan->chanpos - 1;

	BUG_ON(!xpd);
	LINE_DBG(SIGNAL, xpd, pos, "PRI-AUDIO: %s\n", (on) ? "on" : "off");
	mark_offhook(xpd, pos, on);
	return 0;
}
#endif

static const struct dahdi_span_ops PRI_span_ops = {
	.owner = THIS_MODULE,
	.spanconfig = pri_spanconfig,
	.chanconfig = pri_chanconfig,
	.startup = pri_startup,
	.shutdown = pri_shutdown,
	.rbsbits = pri_rbsbits,
	.open = xpp_open,
	.close = xpp_close,
	.ioctl = xpp_ioctl,
	.maint = xpp_maint,
#ifdef	DAHDI_SYNC_TICK
	.sync_tick = dahdi_sync_tick,
#endif
#ifdef	CONFIG_DAHDI_WATCHDOG
	.watchdog = xpp_watchdog,
#endif

#ifdef	DAHDI_AUDIO_NOTIFY
	.audio_notify = pri_audio_notify,
#endif
};

static int PRI_card_dahdi_preregistration(xpd_t *xpd, bool on)
{
	xbus_t			*xbus;
	struct PRI_priv_data	*priv;
	int			i;
	
	BUG_ON(!xpd);
	xbus = xpd->xbus;
	priv = xpd->priv;
	BUG_ON(!xbus);
	XPD_DBG(GENERAL, xpd, "%s (proto=%s, channels=%d, deflaw=%d)\n",
		(on)?"on":"off",
		pri_protocol_name(priv->pri_protocol),
		PHONEDEV(xpd).channels,
		priv->deflaw);
	if(!on) {
		/* Nothing to do yet */
		return 0;
	}
	PHONEDEV(xpd).span.spantype = pri_protocol_name(priv->pri_protocol);
	PHONEDEV(xpd).span.linecompat = pri_linecompat(priv->pri_protocol);
	PHONEDEV(xpd).span.deflaw = priv->deflaw;
	PHONEDEV(xpd).span.alarms = DAHDI_ALARM_NONE;
	for_each_line(xpd, i) {
		struct dahdi_chan	*cur_chan = XPD_CHAN(xpd, i);
		bool		is_dchan = i == PRI_DCHAN_IDX(priv);

		XPD_DBG(GENERAL, xpd, "setting PRI channel %d (%s)\n", i,
			(is_dchan)?"DCHAN":"CLEAR");
		snprintf(cur_chan->name, MAX_CHANNAME, "XPP_%s/%02d/%1d%1d/%d",
				xpd->type_name, xbus->num, xpd->addr.unit, xpd->addr.subunit, i);
		cur_chan->chanpos = i + 1;
		cur_chan->pvt = xpd;
		cur_chan->sigcap = PRI_SIGCAP;
		if(is_dchan && !priv->is_cas) {	/* D-CHAN */
			//FIXME: cur_chan->flags |= DAHDI_FLAG_PRIDCHAN;
			cur_chan->flags &= ~DAHDI_FLAG_HDLC;
		}
	}
	PHONEDEV(xpd).offhook_state = PHONEDEV(xpd).wanted_pcm_mask;
	PHONEDEV(xpd).span.ops = &PRI_span_ops;
	return 0;
}

static int PRI_card_dahdi_postregistration(xpd_t *xpd, bool on)
{
	xbus_t			*xbus;
	struct PRI_priv_data	*priv;
	
	BUG_ON(!xpd);
	xbus = xpd->xbus;
	priv = xpd->priv;
	BUG_ON(!xbus);
	XPD_DBG(GENERAL, xpd, "%s\n", (on)?"on":"off");
	dahdi_update_syncsrc(xpd);
	return(0);
}

static void dchan_state(xpd_t *xpd, bool up)
{
	struct PRI_priv_data	*priv;

	BUG_ON(!xpd);
	priv = xpd->priv;
	BUG_ON(!priv);
	if(priv->is_cas) {
		return;
	}
	if(priv->dchan_alive == up)
		return;
	if(!priv->layer1_up)	/* No layer1, kill dchan */
		up = 0;
	if(up) {
		XPD_DBG(SIGNAL, xpd, "STATE CHANGE: D-Channel RUNNING\n");
		priv->dchan_alive = 1;
	} else {
		int	d = PRI_DCHAN_IDX(priv);

		if(SPAN_REGISTERED(xpd) && d >= 0 && d < PHONEDEV(xpd).channels) {
			byte	*pcm;

			pcm = (byte *)XPD_CHAN(xpd, d)->readchunk;
			pcm[0] = 0x00;
			pcm = (byte *)XPD_CHAN(xpd, d)->writechunk;
			pcm[0] = 0x00;
		}
		XPD_DBG(SIGNAL, xpd, "STATE CHANGE: D-Channel STOPPED\n");
		priv->dchan_rx_counter = priv->dchan_tx_counter = 0;
		priv->dchan_alive = 0;
		priv->dchan_alive_ticks = 0;
		priv->dchan_rx_sample = priv->dchan_tx_sample = 0x00;
	}
}

/*
 * LED managment is done by the driver now:
 *   - Turn constant ON RED/GREEN led to indicate MASTER/SLAVE port
 *   - Very fast "Double Blink" to indicate Layer1 alive (without D-Channel)
 *   - Constant blink (1/2 sec cycle) to indicate D-Channel alive.
 */
static void handle_leds(xbus_t *xbus, xpd_t *xpd)
{
	struct PRI_priv_data	*priv;
	unsigned int		timer_count;
	int			which_led;
	int			other_led;
	enum pri_led_state	ledstate;
	int			mod;

	BUG_ON(!xpd);
	priv = xpd->priv;
	BUG_ON(!priv);
	if(PHONEDEV(xpd).timing_priority == 0) {
		which_led = TOP_RED_LED;
		other_led = BOTTOM_GREEN_LED;
	} else {
		which_led = BOTTOM_GREEN_LED;
		other_led = TOP_RED_LED;
	}
	ledstate = priv->ledstate[which_led];
	timer_count = xpd->timer_count;
	if(xpd->blink_mode) {
		if((timer_count % DEFAULT_LED_PERIOD) == 0) {
			// led state is toggled
			if(ledstate == PRI_LED_OFF) {
				DO_LED(xpd, which_led, PRI_LED_ON);
				DO_LED(xpd, other_led, PRI_LED_ON);
			} else {
				DO_LED(xpd, which_led, PRI_LED_OFF);
				DO_LED(xpd, other_led, PRI_LED_OFF);
			}
		}
		return;
	}
	if(priv->ledstate[other_led] != PRI_LED_OFF)
		DO_LED(xpd, other_led, PRI_LED_OFF);
	if(priv->dchan_alive) {
		mod = timer_count % 1000;
		switch(mod) {
			case 0:
				DO_LED(xpd, which_led, PRI_LED_ON);
				break;
			case 500:
				DO_LED(xpd, which_led, PRI_LED_OFF);
				break;
		}
	} else if(priv->layer1_up) {
		mod = timer_count % 1000;
		switch(mod) {
			case 0:
			case 100:
				DO_LED(xpd, which_led, PRI_LED_ON);
				break;
			case 50:
			case 150:
				DO_LED(xpd, which_led, PRI_LED_OFF);
				break;
		}
	} else {
		if(priv->ledstate[which_led] != PRI_LED_ON)
			DO_LED(xpd, which_led, PRI_LED_ON);
	}
}

static int PRI_card_tick(xbus_t *xbus, xpd_t *xpd)
{
	struct PRI_priv_data	*priv;

	BUG_ON(!xpd);
	priv = xpd->priv;
	BUG_ON(!priv);
	if(!priv->initialized || !xbus->self_ticking)
		return 0;
	/*
	 * Poll layer1 status (cascade subunits)
	 */
	if(poll_interval != 0 &&
		((xpd->timer_count % poll_interval) == 0)) {
		priv->poll_noreplies++;
		query_subunit(xpd, REG_FRS0);
		//query_subunit(xpd, REG_FRS1);
	}
	if(priv->dchan_tx_counter >= 1 && priv->dchan_rx_counter > 1) {
		dchan_state(xpd, 1);
		priv->dchan_alive_ticks++;
	}
	handle_leds(xbus, xpd);
	return 0;
}

static int PRI_card_ioctl(xpd_t *xpd, int pos, unsigned int cmd, unsigned long arg)
{
	struct dahdi_chan	*chan;

	BUG_ON(!xpd);
	if(!XBUS_IS(xpd->xbus, READY))
		return -ENODEV;
	chan = XPD_CHAN(xpd, pos);
	switch (cmd) {
		case DAHDI_TONEDETECT:
			/*
			 * Asterisk call all span types with this (FXS specific)
			 * call. Silently ignore it.
			 */
			LINE_DBG(SIGNAL, xpd, pos, "PRI: TONEDETECT (%s)\n",
				(chan->flags & DAHDI_FLAG_AUDIO) ?
					"AUDIO" : "SILENCE");
			return -ENOTTY;
		case DAHDI_ONHOOKTRANSFER:
			LINE_DBG(SIGNAL, xpd, pos, "PRI: ONHOOKTRANSFER\n");
			return -ENOTTY;
		case DAHDI_VMWI:
			LINE_DBG(SIGNAL, xpd, pos, "PRI: VMWI\n");
			return -ENOTTY;
		case DAHDI_VMWI_CONFIG:
			LINE_DBG(SIGNAL, xpd, pos, "PRI: VMWI_CONFIG\n");
			return -ENOTTY;
		default:
			report_bad_ioctl(THIS_MODULE->name, xpd, pos, cmd);
			return -ENOTTY;
	}
	return 0;
}

static int PRI_card_close(xpd_t *xpd, lineno_t pos)
{
	//struct dahdi_chan	*chan = XPD_CHAN(xpd, pos);
	dchan_state(xpd, 0);
	return 0;
}

/*
 * Called only for 'span' keyword in /etc/dahdi/system.conf
 */
static int pri_startup(struct dahdi_span *span)
{
	struct phonedev	*phonedev = container_of(span, struct phonedev, span);
	xpd_t		*xpd = container_of(phonedev, struct xpd, phonedev);
	struct PRI_priv_data	*priv;

	BUG_ON(!xpd);
	priv = xpd->priv;
	BUG_ON(!priv);
	if(!XBUS_IS(xpd->xbus, READY)) {
		XPD_DBG(GENERAL, xpd, "Startup called by dahdi. No Hardware. Ignored\n");
		return -ENODEV;
	}
	XPD_DBG(GENERAL, xpd, "STARTUP\n");
	// Turn on all channels
	CALL_PHONE_METHOD(card_state, xpd, 1);
	set_rbslines(xpd, 0);
	write_subunit(xpd, REG_XPM2, 0x00);
	return 0;
}

/*
 * Called only for 'span' keyword in /etc/dahdi/system.conf
 */
static int pri_shutdown(struct dahdi_span *span)
{
	struct phonedev	*phonedev = container_of(span, struct phonedev, span);
	xpd_t		*xpd = container_of(phonedev, struct xpd, phonedev);
	struct PRI_priv_data	*priv;

	BUG_ON(!xpd);
	priv = xpd->priv;
	BUG_ON(!priv);
	if(!XBUS_IS(xpd->xbus, READY)) {
		XPD_DBG(GENERAL, xpd, "Shutdown called by dahdi. No Hardware. Ignored\n");
		return -ENODEV;
	}
	XPD_DBG(GENERAL, xpd, "SHUTDOWN\n");
	// Turn off all channels
	CALL_PHONE_METHOD(card_state, xpd, 0);
	return 0;
}

static int encode_rbsbits_e1(xpd_t *xpd, int pos, int bits)
{
	struct PRI_priv_data	*priv;
	byte			val;
	int			rsnum;

	BUG_ON(!xpd);
	priv = xpd->priv;
	BUG_ON(!priv);
	BUG_ON(priv->pri_protocol != PRI_PROTO_E1);
	if(pos == 15)
		return 0;	/* Don't write dchan in CAS */
	if(pos < 0 || pos > 31) {
		XPD_NOTICE(xpd, "%s: pos=%d out of range. Ignore\n", __FUNCTION__, pos);
		return 0;
	}
	if(pos >= 16) {
		/* Low nibble */
		rsnum = pos - 16;
		val = (priv->cas_ts_e[rsnum] & 0xF0) | (bits & 0x0F);
	} else {
		/* High nibble */
		rsnum = pos;
		val = (priv->cas_ts_e[rsnum] & 0x0F) | ((bits << 4) & 0xF0);
	}
	LINE_DBG(SIGNAL, xpd, pos, "RBS: TX: bits=0x%X\n", bits);
	write_cas_reg(xpd, rsnum, val);
	return 0;
}

static int encode_rbsbits_t1(xpd_t *xpd, int pos, int bits)
{
	struct PRI_priv_data	*priv;
	int			rsnum;
	int			chan_per_reg;
	int			offset;
	int			width;
	uint			tx_bits = bits;
	uint			mask;
	byte			val;

	BUG_ON(!xpd);
	priv = xpd->priv;
	BUG_ON(!priv);
	BUG_ON(priv->pri_protocol != PRI_PROTO_T1);
	if(pos < 0 || pos >= PHONEDEV(xpd).channels) {
		XPD_ERR(xpd, "%s: Bad pos=%d\n", __FUNCTION__, pos);
		return 0;
	}
	chan_per_reg = CHAN_PER_REGS(priv);
	width = 8 / chan_per_reg;
	rsnum = pos / chan_per_reg;
	offset = pos % chan_per_reg;
	mask = BITMASK(width) << (chan_per_reg - offset - 1) * width;
	if (!priv->is_esf)
		tx_bits >>= 2;
	tx_bits &= BITMASK(width);
	tx_bits <<= (chan_per_reg - offset - 1) * width;
	val = priv->cas_ts_e[rsnum];
	val &= ~mask;
	val |= tx_bits;
	LINE_DBG(SIGNAL, xpd, pos,
		"bits=0x%02X RS%02d(%s) offset=%d tx_bits=0x%02X\n",
		bits, rsnum+1,
		(priv->is_esf) ? "esf" : "d4",
		offset, tx_bits);
	write_cas_reg(xpd, rsnum , val);
	priv->dchan_tx_counter++;
	return 0;
}

static void send_idlebits(xpd_t *xpd, bool saveold)
{
	struct PRI_priv_data	*priv;
	byte			save_rs[NUM_CAS_RS_E];
	int			i;

	if (!SPAN_REGISTERED(xpd))
		return;
	priv = xpd->priv;
	BUG_ON(!priv);
	XPD_DBG(SIGNAL, xpd, "saveold=%d\n", saveold);
	if (saveold)
		memcpy(save_rs, priv->cas_ts_e, sizeof(save_rs));
	for_each_line(xpd, i) {
		struct dahdi_chan	*chan = XPD_CHAN(xpd, i);

		pri_rbsbits(chan, chan->idlebits);
	}
	if (saveold)
		memcpy(priv->cas_ts_e, save_rs, sizeof(save_rs));
}

static void send_oldbits(xpd_t *xpd)
{
	struct PRI_priv_data	*priv;
	int			i;

	BUG_ON(!xpd);
	priv = xpd->priv;
	BUG_ON(!priv);
	XPD_DBG(SIGNAL, xpd, "\n");
	for (i = 0; i < cas_numregs(xpd); i++)
		write_cas_reg(xpd, i , priv->cas_ts_e[i]);
}

static int pri_rbsbits(struct dahdi_chan *chan, int bits)
{
	xpd_t			*xpd;
	struct PRI_priv_data	*priv;
	int			pos;

	xpd = chan->pvt;
	BUG_ON(!xpd);
	pos = chan->chanpos - 1;
	priv = xpd->priv;
	BUG_ON(!priv);
	if(!priv->is_cas) {
		XPD_DBG(SIGNAL, xpd, "RBS: TX: not in CAS mode. Ignore.\n");
		return 0;
	}
	if (chan->sig == DAHDI_SIG_NONE) {
		LINE_DBG(SIGNAL, xpd, pos,
				"RBS: TX: sigtyp=%s. , bits=0x%X. Ignore.\n", 
				sig2str(chan->sig), bits);
		return 0;
	}
	if(!priv->layer1_up) {
		XPD_DBG(SIGNAL, xpd, "RBS: TX: No layer1 yet. Keep going.\n");
	}
	if(priv->pri_protocol == PRI_PROTO_E1) {
		if(encode_rbsbits_e1(xpd, pos, bits) < 0)
			return -EINVAL;
	} else if(priv->pri_protocol == PRI_PROTO_T1) {
		if(encode_rbsbits_t1(xpd, pos, bits) < 0)
			return -EINVAL;
	} else {
		XPD_NOTICE(xpd, "%s: protocol %s is not supported yet with CAS\n",
			__FUNCTION__, pri_protocol_name(priv->pri_protocol));
		return -EINVAL;
	}
	return 0;
}

/*! Copy PCM chunks from the buffers of the xpd to a new packet
 * \param xbus	xbus of source xpd.
 * \param xpd	source xpd.
 * \param lines	a bitmask of the active channels that need to be copied. 
 * \param pack	packet to be filled.
 *
 * On PRI this function is should also shift the lines mask one bit, as
 * channel 0 on the wire is an internal chip control channel. We only
 * send 31 channels to the device, but they should be called 1-31 rather
 * than 0-30 .
 */
static void PRI_card_pcm_fromspan(xpd_t *xpd, xpacket_t *pack)
{
	struct PRI_priv_data	*priv;
	byte			*pcm;
	unsigned long		flags;
	int			i;
	xpp_line_t		wanted_lines;
	int			physical_chan;
	int			physical_mask = 0;

	BUG_ON(!xpd);
	BUG_ON(!pack);
	priv = xpd->priv;
	BUG_ON(!priv);
	pcm = RPACKET_FIELD(pack, GLOBAL, PCM_WRITE, pcm);
	spin_lock_irqsave(&xpd->lock, flags);
	wanted_lines = PHONEDEV(xpd).wanted_pcm_mask;
	physical_chan = 0;
	for_each_line(xpd, i) {
		struct dahdi_chan	*chan = XPD_CHAN(xpd, i);

		if(priv->pri_protocol == PRI_PROTO_E1) {
			/* In E1 - Only 0'th channel is unused */
			if(i == 0) {
				physical_chan++;
			}
		} else if(priv->pri_protocol == PRI_PROTO_T1) {
			/* In T1 - Every 4'th channel is unused */
			if((i % 3) == 0) {
				physical_chan++;
			}
		}
		if(IS_SET(wanted_lines, i)) {
			physical_mask |= BIT(physical_chan);
			if(SPAN_REGISTERED(xpd)) {
#ifdef	DEBUG_PCMTX
				int	channo = XPD_CHAN(xpd, i)->channo;

				if(pcmtx >= 0 && pcmtx_chan == channo)
					memset((u_char *)pcm, pcmtx, DAHDI_CHUNKSIZE);
				else
#endif
					memcpy((u_char *)pcm, chan->writechunk, DAHDI_CHUNKSIZE);
				if(i == PRI_DCHAN_IDX(priv)) {
					if(priv->dchan_tx_sample != chan->writechunk[0]) {
						priv->dchan_tx_sample = chan->writechunk[0];
						priv->dchan_tx_counter++;
					} else if(chan->writechunk[0] == 0xFF)
						dchan_state(xpd, 0);
					else
						chan->writechunk[0] = 0xFF;	/* Clobber for next tick */
				}
			} else
				memset((u_char *)pcm, DAHDI_XLAW(0, chan), DAHDI_CHUNKSIZE);
			pcm += DAHDI_CHUNKSIZE;
		}
		physical_chan++;
	}
	RPACKET_FIELD(pack, GLOBAL, PCM_WRITE, lines) = physical_mask;
	XPD_COUNTER(xpd, PCM_WRITE)++;
	spin_unlock_irqrestore(&xpd->lock, flags);
}

/*! Copy PCM chunks from the packet we received to the xpd struct.
 * \param xbus	xbus of target xpd.
 * \param xpd	target xpd.
 * \param pack	Source packet.
 *
 * On PRI this function is should also shift the lines back mask one bit, as
 * channel 0 on the wire is an internal chip control channel. 
 *
 * \see PRI_card_pcm_fromspan
 */
static void PRI_card_pcm_tospan(xpd_t *xpd, xpacket_t *pack)
{
	struct PRI_priv_data	*priv;
	byte			*pcm;
	xpp_line_t		physical_mask;
	unsigned long		flags;
	int			i;
	int			logical_chan;

	if(!SPAN_REGISTERED(xpd))
		return;
	priv = xpd->priv;
	BUG_ON(!priv);
	pcm = RPACKET_FIELD(pack, GLOBAL, PCM_READ, pcm);
	physical_mask = RPACKET_FIELD(pack, GLOBAL, PCM_WRITE, lines);
	spin_lock_irqsave(&xpd->lock, flags);
	logical_chan = 0;
	for (i = 0; i < CHANNELS_PERXPD; i++) {
		volatile u_char	*r;

		if(priv->pri_protocol == PRI_PROTO_E1) {
			/* In E1 - Only 0'th channel is unused */
			if(i == 0)
				continue;
		} else if(priv->pri_protocol == PRI_PROTO_T1) {
			/* In T1 - Every 4'th channel is unused */
			if((i % 4) == 0)
				continue;
		}
		if(logical_chan == PRI_DCHAN_IDX(priv) && !priv->is_cas) {
			if(priv->dchan_rx_sample != pcm[0]) {
				if(debug & DBG_PCM) {
					XPD_INFO(xpd, "RX-D-Chan: prev=0x%X now=0x%X\n",
							priv->dchan_rx_sample, pcm[0]);
					dump_packet("RX-D-Chan", pack, 1);
				}
				priv->dchan_rx_sample = pcm[0];
				priv->dchan_rx_counter++;
			} else if(pcm[0] == 0xFF)
				dchan_state(xpd, 0);
		}
		if(IS_SET(physical_mask, i)) {
			r = XPD_CHAN(xpd, logical_chan)->readchunk;
			// memset((u_char *)r, 0x5A, DAHDI_CHUNKSIZE);	// DEBUG
			memcpy((u_char *)r, pcm, DAHDI_CHUNKSIZE);
			pcm += DAHDI_CHUNKSIZE;
		}
		logical_chan++;
	}
	XPD_COUNTER(xpd, PCM_READ)++;
	spin_unlock_irqrestore(&xpd->lock, flags);
}

static int PRI_timing_priority(xpd_t *xpd)
{
	struct PRI_priv_data	*priv;

	priv = xpd->priv;
	BUG_ON(!priv);
	if (priv->layer1_up)
		return PHONEDEV(xpd).timing_priority;
	XPD_DBG(SYNC, xpd, "No timing priority (no layer1)\n");
	return -ENOENT;
}



/*---------------- PRI: HOST COMMANDS -------------------------------------*/

static /* 0x33 */ HOSTCMD(PRI, SET_LED, enum pri_led_selectors led_sel, enum pri_led_state to_led_state)
{
	int			ret = 0;
	xframe_t		*xframe;
	xpacket_t		*pack;
	struct pri_leds		*pri_leds;
	struct PRI_priv_data	*priv;

	BUG_ON(!xbus);
	BUG_ON(!xpd);
	priv = xpd->priv;
	BUG_ON(!priv);
	XPD_DBG(LEDS, xpd, "led_sel=%d to_state=%d\n", led_sel, to_led_state);
	XFRAME_NEW_CMD(xframe, pack, xbus, PRI, SET_LED, xpd->xbus_idx);
	pri_leds = &RPACKET_FIELD(pack, PRI, SET_LED, pri_leds);
	pri_leds->state = to_led_state;
	pri_leds->led_sel = led_sel;
	pri_leds->reserved = 0;
	XPACKET_LEN(pack) = RPACKET_SIZE(PRI, SET_LED);
	ret = send_cmd_frame(xbus, xframe);
	priv->ledstate[led_sel] = to_led_state;
	return ret;
}

/*---------------- PRI: Astribank Reply Handlers --------------------------*/
static void layer1_state(xpd_t *xpd, byte data_low)
{
	struct PRI_priv_data	*priv;
	int			alarms = DAHDI_ALARM_NONE;
	int			layer1_up_prev;

	BUG_ON(!xpd);
	priv = xpd->priv;
	BUG_ON(!priv);
	priv->poll_noreplies = 0;
	if(data_low & REG_FRS0_LOS)
		alarms |=  DAHDI_ALARM_RED;
	if(data_low & REG_FRS0_AIS)
		alarms |= DAHDI_ALARM_BLUE;
	if(data_low & REG_FRS0_RRA)
		alarms |= DAHDI_ALARM_YELLOW;
	layer1_up_prev  = priv->layer1_up;
	priv->layer1_up = alarms == DAHDI_ALARM_NONE;
#if 0
	/*
	 * Some bad bits (e.g: LMFA and NMF have no alarm "colors"
	 * associated. However, layer1 is still not working if they are set.
	 * FIXME: These behave differently in E1/T1, so ignore them for while.
	 */
	if(data_low & (REG_FRS0_LMFA | REG_FRS0_E1_NMF))
		priv->layer1_up = 0;
#endif
	priv->alarms = alarms;
	if(!priv->layer1_up) {
		dchan_state(xpd, 0);
	} else if (priv->is_cas && !layer1_up_prev) {
		int	regbase = cas_regbase(xpd);
		int	i;

		XPD_DBG(SIGNAL , xpd,
			"Returning From Alarm Refreshing Rx register data \n");
		for (i = 0; i < cas_numregs(xpd); i++)
			query_subunit(xpd, regbase + i);
	}

	if(SPAN_REGISTERED(xpd) && PHONEDEV(xpd).span.alarms != alarms) {
		char	str1[MAX_PROC_WRITE];
		char	str2[MAX_PROC_WRITE];

		alarm2str(PHONEDEV(xpd).span.alarms, str1, sizeof(str1));
		alarm2str(alarms, str2, sizeof(str2));
		XPD_NOTICE(xpd, "Alarms: 0x%X (%s) => 0x%X (%s)\n",
				PHONEDEV(xpd).span.alarms, str1,
				alarms, str2);
		if (priv->is_cas) {
			if (alarms == DAHDI_ALARM_NONE)
				send_oldbits(xpd);
			else if (PHONEDEV(xpd).span.alarms == DAHDI_ALARM_NONE)
				send_idlebits(xpd, 1);
		}
		PHONEDEV(xpd).span.alarms = alarms;
		elect_syncer("LAYER1");
		dahdi_alarm_notify(&PHONEDEV(xpd).span);
		set_clocking(xpd);
	}
	priv->reg_frs0 = data_low;
	priv->layer1_replies++;
	XPD_DBG(REGS, xpd, "subunit=%d data_low=0x%02X\n", xpd->addr.subunit, data_low);
}

static int decode_cas_e1(xpd_t *xpd, byte regnum, byte data_low)
{
	struct PRI_priv_data	*priv;
	uint			pos = regnum - REG_RS2_E;
	int			rsnum = pos + 2;
	int			chan1 = pos;
	int			chan2 = pos + 16;
	int			val1 = (data_low >> 4) & 0xF;
	int			val2 = data_low & 0xF;

	priv = xpd->priv;
	BUG_ON(!priv->is_cas);
	BUG_ON(priv->pri_protocol != PRI_PROTO_E1);
	XPD_DBG(SIGNAL, xpd, "RBS: RX: data_low=0x%02X\n", data_low);
	if(pos < 0 || pos >= NUM_CAS_RS_E) {
		XPD_ERR(xpd, "%s: got bad pos=%d [0-%d]\n", __FUNCTION__, pos, NUM_CAS_RS_E);
		return -EINVAL;
	}
	if(chan1 < 0 || chan1 > PHONEDEV(xpd).channels) {
		XPD_NOTICE(xpd, "%s: %s CAS: Bad chan1 number (%d)\n",
			__FUNCTION__,
			pri_protocol_name(priv->pri_protocol),
			chan1);
		return -EINVAL;
	}
	if(chan2 < 0 || chan2 > PHONEDEV(xpd).channels) {
		XPD_NOTICE(xpd, "%s: %s CAS: Bad chan2 number (%d)\n",
			__FUNCTION__,
			pri_protocol_name(priv->pri_protocol),
			chan2);
		return -EINVAL;
	}
	XPD_DBG(SIGNAL, xpd, "RBS: RX: RS%02d (channel %2d, channel %2d): 0x%02X -> 0x%02X\n",
		rsnum, chan1+1, chan2+1, priv->cas_rs_e[pos], data_low);
	if(SPAN_REGISTERED(xpd)) {
		dahdi_rbsbits(XPD_CHAN(xpd, chan1), val1);
		dahdi_rbsbits(XPD_CHAN(xpd, chan2), val2);
	}
	priv->dchan_rx_counter++;
	priv->cas_rs_e[pos] = data_low;
	return 0;
}

static int decode_cas_t1(xpd_t *xpd, byte regnum, byte data_low)
{
	struct PRI_priv_data	*priv;
	uint			rsnum;
	uint			chan_per_reg;
	uint			width;
	int			i;

	priv = xpd->priv;
	BUG_ON(!priv->is_cas);
	BUG_ON(priv->pri_protocol != PRI_PROTO_T1);
	rsnum = regnum - REG_RS1_E;
	if(rsnum < 0 || rsnum >= 12) {
		XPD_ERR(xpd, "Bad rsnum=%d\n", rsnum);
		return 0;
	}
	if(!priv->is_esf)
		rsnum = rsnum % 6;	/* 2 identical banks of 6 registers */
	chan_per_reg = CHAN_PER_REGS(priv);
	width = 8 / chan_per_reg;
	XPD_DBG(SIGNAL, xpd,
		"RBS: RX(%s,%d): RS%02d data_low=0x%02X\n",
		(priv->is_esf) ? "esf" : "d4",
		chan_per_reg,
		rsnum+1, data_low);
	for(i = 0; i < chan_per_reg; i++) {
		uint			rxsig = (data_low >> (i * width)) & BITMASK(width);
		int			pos;
		struct dahdi_chan	*chan;

		if (!priv->is_esf)
			rxsig <<= 2;
		pos = rsnum * chan_per_reg + chan_per_reg - i - 1;
		if(pos < 0 || pos >= PHONEDEV(xpd).channels) {
			XPD_ERR(xpd, "%s: Bad pos=%d\n", __FUNCTION__, pos);
			continue;
		}
		chan = XPD_CHAN(xpd, pos);
		if(!chan) {
			XPD_ERR(xpd, "%s: Null channel in pos=%d\n", __FUNCTION__, pos);
			continue;
		}
		if(chan->rxsig != rxsig) {
			LINE_DBG(SIGNAL, xpd, pos, "i=%d rxsig=0x%02X\n", i, rxsig);
			dahdi_rbsbits(chan, rxsig);
		}
	}
	priv->cas_rs_e[rsnum] = data_low;
	return 0;
}

static void process_cas_dchan(xpd_t *xpd, byte regnum, byte data_low)
{
	struct PRI_priv_data	*priv;

	priv = xpd->priv;
	if(!priv->is_cas) {
		static int	rate_limit;

		if((rate_limit++ % 10003) == 0)
			XPD_NOTICE(xpd, "RBS: RX: not in CAS mode. Ignore.\n");
		return;
	}
	if(!priv->layer1_up) {
		static int	rate_limit;

		if((rate_limit++ % 10003) == 0)
			XPD_DBG(SIGNAL, xpd, "RBS: RX: No layer1.\n");
	}
	if(!SPAN_REGISTERED(xpd)) {
		static int	rate_limit;

		if((rate_limit++ % 10003) == 0)
			XPD_DBG(SIGNAL, xpd, "RBS: RX: Span not registered. Ignore.\n");
		return;
	}
	if(priv->pri_protocol == PRI_PROTO_E1) {
		if(regnum == REG_RS1_E)
			return; /* Time slot 0: Ignored for E1 */
		if(regnum < REG_RS2_E) {
			/* Should not happen, but harmless. Ignore */
			if (regnum == REG_RS1_E)
				return;

			XPD_NOTICE(xpd,
				"%s: received register 0x%X in protocol %s. Ignore\n",
				__FUNCTION__, regnum, pri_protocol_name(priv->pri_protocol));
			return;
		}
		if(decode_cas_e1(xpd, regnum, data_low) < 0)
			return;
	} else if(priv->pri_protocol == PRI_PROTO_T1) {
		if(regnum > REG_RS12_E) {
			XPD_NOTICE(xpd,
				"%s: received register 0x%X in protocol %s. Ignore\n",
				__FUNCTION__, regnum, pri_protocol_name(priv->pri_protocol));
			return;
		}
		if(decode_cas_t1(xpd, regnum, data_low) < 0)
			return;
	} else {
		XPD_NOTICE(xpd, "%s: protocol %s is not supported yet with CAS\n",
			__FUNCTION__, pri_protocol_name(priv->pri_protocol));
	}
	priv->cas_replies++;
}

static int PRI_card_register_reply(xbus_t *xbus, xpd_t *xpd, reg_cmd_t *info)
{
	unsigned long		flags;
	struct PRI_priv_data	*priv;
	struct xpd_addr		addr;
	xpd_t			*orig_xpd;
	byte			regnum;
	byte			data_low;

	/* Map UNIT + PORTNUM to XPD */
	orig_xpd = xpd;
	addr.unit = orig_xpd->addr.unit;
	addr.subunit = info->portnum;
	regnum = REG_FIELD(info, regnum);
	data_low = REG_FIELD(info, data_low);
	xpd = xpd_byaddr(xbus, addr.unit, addr.subunit);
	if(!xpd) {
		static int	rate_limit;

		if((rate_limit++ % 1003) < 5)
			notify_bad_xpd(__FUNCTION__, xbus, addr , orig_xpd->xpdname);
		return -EPROTO;
	}
	spin_lock_irqsave(&xpd->lock, flags);
	priv = xpd->priv;
	BUG_ON(!priv);
	if(info->is_multibyte) {
		XPD_NOTICE(xpd, "Got Multibyte: %d bytes, eoframe: %d\n",
				info->bytes, info->eoframe);
		goto end;
	}
	if(regnum == REG_FRS0 && !REG_FIELD(info, do_subreg))
		layer1_state(xpd, data_low);
	else if(regnum == REG_FRS1 && !REG_FIELD(info, do_subreg))
		priv->reg_frs1 = data_low;
	if(priv->is_cas && !REG_FIELD(info, do_subreg)) {
		if(regnum >= REG_RS1_E && regnum <= REG_RS16_E) {
			process_cas_dchan(xpd, regnum, data_low);
		}
	}
	/* Update /proc info only if reply relate to the last slic read request */
	if(
			REG_FIELD(&xpd->requested_reply, regnum) == REG_FIELD(info, regnum) &&
			REG_FIELD(&xpd->requested_reply, do_subreg) == REG_FIELD(info, do_subreg) &&
			REG_FIELD(&xpd->requested_reply, subreg) == REG_FIELD(info, subreg)) {
		xpd->last_reply = *info;
	}
	
end:
	spin_unlock_irqrestore(&xpd->lock, flags);
	return 0;
}

static int PRI_card_state(xpd_t *xpd, bool on)
{
	BUG_ON(!xpd);
	XPD_DBG(GENERAL, xpd, "%s\n", (on)?"on":"off");
	return 0;
}

static const struct xops	pri_xops = {
	.card_new	= PRI_card_new,
	.card_init	= PRI_card_init,
	.card_remove	= PRI_card_remove,
	.card_tick	= PRI_card_tick,
	.card_register_reply	= PRI_card_register_reply,
};

static const struct phoneops	pri_phoneops = {
	.card_dahdi_preregistration	= PRI_card_dahdi_preregistration,
	.card_dahdi_postregistration	= PRI_card_dahdi_postregistration,
	.card_pcm_recompute	= PRI_card_pcm_recompute,
	.card_pcm_fromspan	= PRI_card_pcm_fromspan,
	.card_pcm_tospan	= PRI_card_pcm_tospan,
	.card_timing_priority	= PRI_timing_priority,
	.card_ioctl	= PRI_card_ioctl,
	.card_close	= PRI_card_close,
	.card_state	= PRI_card_state,
};

static xproto_table_t PROTO_TABLE(PRI) = {
	.owner = THIS_MODULE,
	.entries = {
		/*	Table	Card	Opcode		*/
	},
	.name = "PRI",	/* protocol name */
	.ports_per_subunit = 1,
	.type = XPD_TYPE_PRI,
	.xops = &pri_xops,
	.phoneops = &pri_phoneops,
	.packet_is_valid = pri_packet_is_valid,
	.packet_dump = pri_packet_dump,
};

static bool pri_packet_is_valid(xpacket_t *pack)
{
	const xproto_entry_t	*xe = NULL;
	// DBG(GENERAL, "\n");
	xe = xproto_card_entry(&PROTO_TABLE(PRI), XPACKET_OP(pack));
	return xe != NULL;
}

static void pri_packet_dump(const char *msg, xpacket_t *pack)
{
	DBG(GENERAL, "%s\n", msg);
}
/*------------------------- REGISTER Handling --------------------------*/
#ifdef	OLD_PROC
static int proc_pri_info_write(struct file *file, const char __user *buffer, unsigned long count, void *data)
{
	xpd_t			*xpd = data;
	struct PRI_priv_data	*priv;
	char			buf[MAX_PROC_WRITE];
	char			*p;
	char			*tok;
	int			ret = 0;
	bool			got_localloop = 0;
	bool			got_nolocalloop = 0;
	bool			got_e1 = 0;
	bool			got_t1 = 0;
	bool			got_j1 = 0;

	if(!xpd)
		return -ENODEV;
	XPD_NOTICE(xpd, "%s: DEPRECATED: %s[%d] write to /proc interface instead of /sys\n",
		__FUNCTION__, current->comm, current->tgid);
	priv = xpd->priv;
	if(count >= MAX_PROC_WRITE) {	/* leave room for null */
		XPD_ERR(xpd, "write too long (%ld)\n", count);
		return -E2BIG;
	}
	if(copy_from_user(buf, buffer, count)) {
		XPD_ERR(xpd, "Failed reading user data\n");
		return -EFAULT;
	}
	buf[count] = '\0';
	XPD_DBG(PROC, xpd, "PRI-SETUP: got %s\n", buf);
	/*
	 * First parse. Act only of *everything* is good.
	 */
	p = buf;
	while((tok = strsep(&p, " \t\v\n")) != NULL) {
		if(*tok == '\0')
			continue;
		XPD_DBG(PROC, xpd, "Got token='%s'\n", tok);
		if(strnicmp(tok, "LOCALLOOP", 8) == 0)
			got_localloop = 1;
		else if(strnicmp(tok, "NOLOCALLOOP", 8) == 0)
			got_nolocalloop = 1;
		else if(strnicmp(tok, "E1", 2) == 0)
			got_e1 = 1;
		else if(strnicmp(tok, "T1", 2) == 0)
			got_t1 = 1;
		else if(strnicmp(tok, "J1", 2) == 0) {
			got_j1 = 1;
		} else {
			XPD_NOTICE(xpd, "PRI-SETUP: unknown keyword: '%s'\n", tok);
			return -EINVAL;
		}
	}
	if(got_e1)
		ret = set_pri_proto(xpd, PRI_PROTO_E1);
	else if(got_t1)
		ret = set_pri_proto(xpd, PRI_PROTO_T1);
	else if(got_j1)
		ret = set_pri_proto(xpd, PRI_PROTO_J1);
	if(priv->pri_protocol == PRI_PROTO_0) {
		XPD_ERR(xpd,
			"Must set PRI protocol (E1/T1/J1) before setting other parameters\n");
		return -EINVAL;
	}
	if(got_localloop)
		ret = set_localloop(xpd, 1);
	if(got_nolocalloop)
		ret = set_localloop(xpd, 0);
	return (ret) ? ret : count;
}


static int proc_pri_info_read(char *page, char **start, off_t off, int count, int *eof, void *data)
{
	int			len = 0;
	unsigned long		flags;
	xpd_t			*xpd = data;
	struct PRI_priv_data	*priv;
	int			i;

	DBG(PROC, "\n");
	if(!xpd)
		return -ENODEV;
	XPD_NOTICE(xpd, "%s: DEPRECATED: %s[%d] read from /proc interface instead of /sys\n",
		__FUNCTION__, current->comm, current->tgid);
	spin_lock_irqsave(&xpd->lock, flags);
	priv = xpd->priv;
	BUG_ON(!priv);
	len += sprintf(page + len, "PRI: %s %s%s (deflaw=%d, dchan=%d)\n",
		(priv->clock_source) ? "MASTER" : "SLAVE",
		pri_protocol_name(priv->pri_protocol),
		(priv->local_loopback) ? " LOCALLOOP" : "",
		priv->deflaw, priv->dchan_num);
	len += sprintf(page + len, "%05d Layer1: ", priv->layer1_replies);
	if(priv->poll_noreplies > 1)
		len += sprintf(page + len, "No Replies [%d]\n",
			priv->poll_noreplies);
	else {
		len += sprintf(page + len, "%s\n",
				((priv->layer1_up) ?  "UP" : "DOWN"));
		len += sprintf(page + len,
				"Framer Status: FRS0=0x%02X, FRS1=0x%02X ALARMS:",
				priv->reg_frs0, priv->reg_frs1);
		if(priv->reg_frs0 & REG_FRS0_LOS)
			len += sprintf(page + len, " RED");
		if(priv->reg_frs0 & REG_FRS0_AIS)
			len += sprintf(page + len, " BLUE");
		if(priv->reg_frs0 & REG_FRS0_RRA)
			len += sprintf(page + len, " YELLOW");
		len += sprintf(page + len, "\n");
	}
	if(priv->is_cas) {
		len += sprintf(page + len,
			"CAS: replies=%d\n", priv->cas_replies);
		len += sprintf(page + len, "   CAS-TS: ");
		for(i = 0; i < NUM_CAS_RS_E; i++) {
			len += sprintf(page + len, " %02X", priv->cas_ts_e[i]);
		}
		len += sprintf(page + len, "\n");
		len += sprintf(page + len, "   CAS-RS: ");
		for(i = 0; i < NUM_CAS_RS_E; i++) {
			len += sprintf(page + len, " %02X", priv->cas_rs_e[i]);
		}
		len += sprintf(page + len, "\n");
	}
	len += sprintf(page + len, "D-Channel: TX=[%5d] (0x%02X)   RX=[%5d] (0x%02X) ",
			priv->dchan_tx_counter, priv->dchan_tx_sample,
			priv->dchan_rx_counter, priv->dchan_rx_sample);
	if(priv->dchan_alive) {
		len += sprintf(page + len, "(alive %d K-ticks)\n",
			priv->dchan_alive_ticks/1000);
	} else {
		len += sprintf(page + len, "(dead)\n");
	}
	for(i = 0; i < NUM_LEDS; i++)
		len += sprintf(page + len, "LED #%d: %d\n", i, priv->ledstate[i]);
	spin_unlock_irqrestore(&xpd->lock, flags);
	if (len <= off+count)
		*eof = 1;
	*start = page + off;
	len -= off;
	if (len > count)
		len = count;
	if (len < 0)
		len = 0;
	return len;
}
#endif

/*------------------------- sysfs stuff --------------------------------*/
static DEVICE_ATTR_READER(pri_protocol_show, dev, buf)
{
	xpd_t			*xpd;
	struct PRI_priv_data	*priv;
	unsigned long		flags;
	int			len = 0;

	BUG_ON(!dev);
	xpd = dev_to_xpd(dev);
	if(!xpd)
		return -ENODEV;
	priv = xpd->priv;
	BUG_ON(!priv);
	spin_lock_irqsave(&xpd->lock, flags);
	len += sprintf(buf, "%s\n", pri_protocol_name(priv->pri_protocol));
	spin_unlock_irqrestore(&xpd->lock, flags);
	return len;
}

static DEVICE_ATTR_WRITER(pri_protocol_store, dev, buf, count)
{
	xpd_t			*xpd;
	enum pri_protocol	new_protocol = PRI_PROTO_0;
	int			i;
	int			ret;

	BUG_ON(!dev);
	xpd = dev_to_xpd(dev);
	XPD_DBG(GENERAL, xpd, "%s\n", buf);
	if(!xpd)
		return -ENODEV;
	if((i = strcspn(buf, " \r\n")) != 2) {
		XPD_NOTICE(xpd,
			"Protocol name '%s' has %d characters (should be 2). Ignored.\n",
			buf, i);
		return -EINVAL;
	}
	if(strnicmp(buf, "E1", 2) == 0)
		new_protocol = PRI_PROTO_E1;
	else if(strnicmp(buf, "T1", 2) == 0)
		new_protocol = PRI_PROTO_T1;
	else if(strnicmp(buf, "J1", 2) == 0)
		new_protocol = PRI_PROTO_J1;
	else {
		XPD_NOTICE(xpd,
			"Unknown PRI protocol '%s' (should be E1|T1|J1). Ignored.\n",
			buf);
		return -EINVAL;
	}
	ret = set_pri_proto(xpd, new_protocol);
	return (ret < 0) ? ret : count;
}

static	DEVICE_ATTR(pri_protocol, S_IRUGO | S_IWUSR, pri_protocol_show, pri_protocol_store);

static DEVICE_ATTR_READER(pri_localloop_show, dev, buf)
{
	xpd_t			*xpd;
	struct PRI_priv_data	*priv;
	unsigned long		flags;
	int			len = 0;

	BUG_ON(!dev);
	xpd = dev_to_xpd(dev);
	if(!xpd)
		return -ENODEV;
	priv = xpd->priv;
	BUG_ON(!priv);
	spin_lock_irqsave(&xpd->lock, flags);
	len += sprintf(buf, "%c\n",
		(priv->local_loopback) ? 'Y' : 'N');
	spin_unlock_irqrestore(&xpd->lock, flags);
	return len;
}

static DEVICE_ATTR_WRITER(pri_localloop_store, dev, buf, count)
{
	xpd_t			*xpd;
	bool			ll = 0;
	int			i;
	int			ret;

	BUG_ON(!dev);
	xpd = dev_to_xpd(dev);
	XPD_DBG(GENERAL, xpd, "%s\n", buf);
	if(!xpd)
		return -ENODEV;
	if((i = strcspn(buf, " \r\n")) != 1) {
		XPD_NOTICE(xpd,
			"Value '%s' has %d characters (should be 1). Ignored.\n",
			buf, i);
		return -EINVAL;
	}
	if(strchr("1Yy", buf[0]) != NULL)
		ll = 1;
	else if(strchr("0Nn", buf[0]) != NULL)
		ll = 0;
	else {
		XPD_NOTICE(xpd,
			"Unknown value '%s' (should be [1Yy]|[0Nn]). Ignored.\n",
			buf);
		return -EINVAL;
	}
	ret = set_localloop(xpd, ll);
	return (ret < 0) ? ret : count;
}

static	DEVICE_ATTR(pri_localloop, S_IRUGO | S_IWUSR, pri_localloop_show, pri_localloop_store);

static DEVICE_ATTR_READER(pri_layer1_show, dev, buf)
{
	xpd_t			*xpd;
	struct PRI_priv_data	*priv;
	unsigned long		flags;
	int			len = 0;

	BUG_ON(!dev);
	xpd = dev_to_xpd(dev);
	if(!xpd)
		return -ENODEV;
	priv = xpd->priv;
	BUG_ON(!priv);
	spin_lock_irqsave(&xpd->lock, flags);
	if(priv->poll_noreplies > 1)
		len += sprintf(buf + len, "Unknown[%d]", priv->poll_noreplies);
	else
		len += sprintf(buf + len, "%-10s", ((priv->layer1_up) ?  "UP" : "DOWN"));
	len += sprintf(buf + len, "%d\n", priv->layer1_replies);
	spin_unlock_irqrestore(&xpd->lock, flags);
	return len;
}

static	DEVICE_ATTR(pri_layer1, S_IRUGO, pri_layer1_show, NULL);

static DEVICE_ATTR_READER(pri_alarms_show, dev, buf)
{
	xpd_t			*xpd;
	struct PRI_priv_data	*priv;
	unsigned long		flags;
	int			len = 0;
	const static struct {
		byte		bits;
		const char	*name;
	} alarm_types[] = {
		{ REG_FRS0_LOS, "RED" },
		{ REG_FRS0_AIS, "BLUE" },
		{ REG_FRS0_RRA, "YELLOW" },
	};

	BUG_ON(!dev);
	xpd = dev_to_xpd(dev);
	if(!xpd)
		return -ENODEV;
	priv = xpd->priv;
	BUG_ON(!priv);
	spin_lock_irqsave(&xpd->lock, flags);
	if(priv->poll_noreplies > 1)
		len += sprintf(buf + len, "Unknown[%d]", priv->poll_noreplies);
	else {
		int	i;

		for(i = 0; i < ARRAY_SIZE(alarm_types); i++) {
			if(priv->reg_frs0 & alarm_types[i].bits)
				len += sprintf(buf + len, "%s ", alarm_types[i].name);
		}
	}
	len += sprintf(buf + len, "\n");
	spin_unlock_irqrestore(&xpd->lock, flags);
	return len;
}

static	DEVICE_ATTR(pri_alarms, S_IRUGO, pri_alarms_show, NULL);

static DEVICE_ATTR_READER(pri_cas_show, dev, buf)
{
	xpd_t			*xpd;
	struct PRI_priv_data	*priv;
	unsigned long		flags;
	int			len = 0;

	BUG_ON(!dev);
	xpd = dev_to_xpd(dev);
	if(!xpd)
		return -ENODEV;
	priv = xpd->priv;
	BUG_ON(!priv);
	spin_lock_irqsave(&xpd->lock, flags);
	if(priv->is_cas) {
		int	i;

		len += sprintf(buf + len,
			"CAS: replies=%d\n", priv->cas_replies);
		len += sprintf(buf + len, "   CAS-TS: ");
		for(i = 0; i < NUM_CAS_RS_E; i++) {
			len += sprintf(buf + len, " %02X", priv->cas_ts_e[i]);
		}
		len += sprintf(buf + len, "\n");
		len += sprintf(buf + len, "   CAS-RS: ");
		for(i = 0; i < NUM_CAS_RS_E; i++) {
			len += sprintf(buf + len, " %02X", priv->cas_rs_e[i]);
		}
		len += sprintf(buf + len, "\n");
	}
	spin_unlock_irqrestore(&xpd->lock, flags);
	return len;
}

static	DEVICE_ATTR(pri_cas, S_IRUGO, pri_cas_show, NULL);

static DEVICE_ATTR_READER(pri_dchan_show, dev, buf)
{
	xpd_t			*xpd;
	struct PRI_priv_data	*priv;
	unsigned long		flags;
	int			len = 0;

	BUG_ON(!dev);
	xpd = dev_to_xpd(dev);
	if(!xpd)
		return -ENODEV;
	priv = xpd->priv;
	BUG_ON(!priv);
	spin_lock_irqsave(&xpd->lock, flags);
	len += sprintf(buf + len, "D-Channel: TX=[%5d] (0x%02X)   RX=[%5d] (0x%02X) ",
			priv->dchan_tx_counter, priv->dchan_tx_sample,
			priv->dchan_rx_counter, priv->dchan_rx_sample);
	if(priv->dchan_alive) {
		len += sprintf(buf + len, "(alive %d K-ticks)\n",
			priv->dchan_alive_ticks/1000);
	} else {
		len += sprintf(buf + len, "(dead)\n");
	}
	spin_unlock_irqrestore(&xpd->lock, flags);
	return len;
}

static	DEVICE_ATTR(pri_dchan, S_IRUGO, pri_dchan_show, NULL);

static DEVICE_ATTR_READER(pri_clocking_show, dev, buf)
{
	xpd_t			*xpd;
	struct PRI_priv_data	*priv;
	unsigned long		flags;
	int			len = 0;

	BUG_ON(!dev);
	xpd = dev_to_xpd(dev);
	if(!xpd)
		return -ENODEV;
	priv = xpd->priv;
	BUG_ON(!priv);
	spin_lock_irqsave(&xpd->lock, flags);
	len += sprintf(buf + len, "%s\n", (priv->clock_source) ? "MASTER" : "SLAVE");
	spin_unlock_irqrestore(&xpd->lock, flags);
	return len;
}

static	DEVICE_ATTR(pri_clocking, S_IRUGO, pri_clocking_show, NULL);

static int pri_xpd_probe(struct device *dev)
{
	xpd_t	*xpd;
	int	ret = 0;

	xpd = dev_to_xpd(dev);
	/* Is it our device? */
	if(xpd->type != XPD_TYPE_PRI) {
		XPD_ERR(xpd, "drop suggestion for %s (%d)\n",
			dev_name(dev), xpd->type);
		return -EINVAL;
	}
	XPD_DBG(DEVICES, xpd, "SYSFS\n");
	ret = device_create_file(dev, &dev_attr_pri_protocol);
	if(ret) {
		XPD_ERR(xpd, "%s: device_create_file(pri_protocol) failed: %d\n", __FUNCTION__, ret);
		goto fail_pri_protocol;
	}
	ret = device_create_file(dev, &dev_attr_pri_localloop);
	if(ret) {
		XPD_ERR(xpd, "%s: device_create_file(pri_localloop) failed: %d\n", __FUNCTION__, ret);
		goto fail_pri_localloop;
	}
	ret = device_create_file(dev, &dev_attr_pri_layer1);
	if(ret) {
		XPD_ERR(xpd, "%s: device_create_file(pri_layer1) failed: %d\n", __FUNCTION__, ret);
		goto fail_pri_layer1;
	}
	ret = device_create_file(dev, &dev_attr_pri_alarms);
	if(ret) {
		XPD_ERR(xpd, "%s: device_create_file(pri_alarms) failed: %d\n", __FUNCTION__, ret);
		goto fail_pri_alarms;
	}
	ret = device_create_file(dev, &dev_attr_pri_cas);
	if(ret) {
		XPD_ERR(xpd, "%s: device_create_file(pri_cas) failed: %d\n", __FUNCTION__, ret);
		goto fail_pri_cas;
	}
	ret = device_create_file(dev, &dev_attr_pri_dchan);
	if(ret) {
		XPD_ERR(xpd, "%s: device_create_file(pri_dchan) failed: %d\n", __FUNCTION__, ret);
		goto fail_pri_dchan;
	}
	ret = device_create_file(dev, &dev_attr_pri_clocking);
	if(ret) {
		XPD_ERR(xpd, "%s: device_create_file(pri_clocking) failed: %d\n", __FUNCTION__, ret);
		goto fail_pri_clocking;
	}
	return 0;
fail_pri_clocking:
	device_remove_file(dev, &dev_attr_pri_dchan);
fail_pri_dchan:
	device_remove_file(dev, &dev_attr_pri_cas);
fail_pri_cas:
	device_remove_file(dev, &dev_attr_pri_alarms);
fail_pri_alarms:
	device_remove_file(dev, &dev_attr_pri_layer1);
fail_pri_layer1:
	device_remove_file(dev, &dev_attr_pri_localloop);
fail_pri_localloop:
	device_remove_file(dev, &dev_attr_pri_protocol);
fail_pri_protocol:
	return ret;
}

static int pri_xpd_remove(struct device *dev)
{
	xpd_t	*xpd;

	xpd = dev_to_xpd(dev);
	XPD_DBG(DEVICES, xpd, "SYSFS\n");
	device_remove_file(dev, &dev_attr_pri_clocking);
	device_remove_file(dev, &dev_attr_pri_dchan);
	device_remove_file(dev, &dev_attr_pri_cas);
	device_remove_file(dev, &dev_attr_pri_alarms);
	device_remove_file(dev, &dev_attr_pri_layer1);
	device_remove_file(dev, &dev_attr_pri_localloop);
	device_remove_file(dev, &dev_attr_pri_protocol);
	return 0;
}

static struct xpd_driver	pri_driver = {
	.type		= XPD_TYPE_PRI,
	.driver		= {
		.name = "pri",
#ifndef OLD_HOTPLUG_SUPPORT
		.owner = THIS_MODULE,
#endif
		.probe = pri_xpd_probe,
		.remove = pri_xpd_remove
	}
};

static int __init card_pri_startup(void)
{
	int	ret;

	if((ret = xpd_driver_register(&pri_driver.driver)) < 0)
		return ret;
	INFO("revision %s\n", XPP_VERSION);
#ifdef	DAHDI_AUDIO_NOTIFY
	INFO("FEATURE: WITH DAHDI_AUDIO_NOTIFY\n");
#else
	INFO("FEATURE: WITHOUT DAHDI_AUDIO_NOTIFY\n");
#endif
	xproto_register(&PROTO_TABLE(PRI));
	return 0;
}

static void __exit card_pri_cleanup(void)
{
	DBG(GENERAL, "\n");
	xproto_unregister(&PROTO_TABLE(PRI));
	xpd_driver_unregister(&pri_driver.driver);
}

MODULE_DESCRIPTION("XPP PRI Card Driver");
MODULE_AUTHOR("Oron Peled <oron@actcom.co.il>");
MODULE_LICENSE("GPL");
MODULE_VERSION(XPP_VERSION);
MODULE_ALIAS_XPD(XPD_TYPE_PRI);

module_init(card_pri_startup);
module_exit(card_pri_cleanup);