summaryrefslogtreecommitdiff
path: root/drivers/dahdi/dahdi-base.c
blob: c4a5e14c763c34a8d03ec1374a4f2bda5cf386fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
/*
 * DAHDI Telephony Interface Driver
 *
 * Written by Mark Spencer <markster@digium.com>
 * Based on previous works, designs, and architectures conceived and
 * written by Jim Dixon <jim@lambdatel.com>.
 *
 * Special thanks to Steve Underwood <steve@coppice.org>
 * for substantial contributions to signal processing functions
 * in DAHDI and the Zapata library.
 *
 * Yury Bokhoncovich <byg@cf1.ru>
 * Adaptation for 2.4.20+ kernels (HDLC API was changed)
 * The work has been performed as a part of our move
 * from Cisco 3620 to IBM x305 here in F1 Group
 *
 * Copyright (C) 2001 Jim Dixon / Zapata Telephony.
 * Copyright (C) 2001 - 2011 Digium, Inc.
 *
 * All rights reserved.
 *
 */

/*
 * See http://www.asterisk.org for more information about
 * the Asterisk project. Please do not directly contact
 * any of the maintainers of this project for assistance;
 * the project provides a web site, mailing lists and IRC
 * channels for your use.
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License Version 2 as published by the
 * Free Software Foundation. See the LICENSE file included with
 * this program for more details.
 */


#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/version.h>
#include <linux/ctype.h>
#include <linux/kmod.h>
#include <linux/moduleparam.h>
#include <linux/sched.h>
#include <linux/list.h>
#include <linux/delay.h>
#include <linux/mutex.h>

#if defined(HAVE_UNLOCKED_IOCTL) && defined(CONFIG_BKL)
#include <linux/smp_lock.h>
#endif

#include <linux/ppp_defs.h>

#include <asm/atomic.h>

#define DAHDI_PRINK_MACROS_USE_debug
#define module_printk(level, fmt, args...) printk(level "%s: " fmt, THIS_MODULE->name, ## args)

/* Grab fasthdlc with tables */
#define FAST_HDLC_NEED_TABLES
#include <dahdi/kernel.h>
#include "ecdis.h"
#include "dahdi.h"

#ifdef CONFIG_DAHDI_PPP
#include <linux/netdevice.h>
#include <linux/if.h>
#include <linux/if_ppp.h>
#endif

#ifdef CONFIG_DAHDI_NET
#include <linux/netdevice.h>
#endif

#include "hpec/hpec_user.h"

#include <stdbool.h>

#if defined(EMPULSE) && defined(EMFLASH)
#error "You cannot define both EMPULSE and EMFLASH"
#endif

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 37)
#ifndef CONFIG_BKL
#warning "No CONFIG_BKL is an experimental configuration."
#endif
#endif

/* Get helper arithmetic */
#include "arith.h"
#if defined(CONFIG_DAHDI_MMX) || defined(ECHO_CAN_FP)
#include <asm/i387.h>
#endif

#define hdlc_to_chan(h) (((struct dahdi_hdlc *)(h))->chan)
#define netdev_to_chan(h) (((struct dahdi_hdlc *)(dev_to_hdlc(h)->priv))->chan)
#define chan_to_netdev(h) ((h)->hdlcnetdev->netdev)

/* macro-oni for determining a unit (channel) number */
#define	UNIT(file) MINOR(file->f_dentry->d_inode->i_rdev)

EXPORT_SYMBOL(dahdi_transcode_fops);
EXPORT_SYMBOL(dahdi_init_tone_state);
EXPORT_SYMBOL(dahdi_mf_tone);
EXPORT_SYMBOL(__dahdi_mulaw);
EXPORT_SYMBOL(__dahdi_alaw);
#ifdef CONFIG_CALC_XLAW
EXPORT_SYMBOL(__dahdi_lineartoulaw);
EXPORT_SYMBOL(__dahdi_lineartoalaw);
#else
EXPORT_SYMBOL(__dahdi_lin2mu);
EXPORT_SYMBOL(__dahdi_lin2a);
#endif
EXPORT_SYMBOL(dahdi_rbsbits);
EXPORT_SYMBOL(dahdi_qevent_nolock);
EXPORT_SYMBOL(dahdi_qevent_lock);
EXPORT_SYMBOL(dahdi_hooksig);
EXPORT_SYMBOL(dahdi_alarm_notify);
EXPORT_SYMBOL(dahdi_set_dynamic_ioctl);
EXPORT_SYMBOL(dahdi_hdlc_abort);
EXPORT_SYMBOL(dahdi_hdlc_finish);
EXPORT_SYMBOL(dahdi_hdlc_getbuf);
EXPORT_SYMBOL(dahdi_hdlc_putbuf);
EXPORT_SYMBOL(dahdi_alarm_channel);

EXPORT_SYMBOL(dahdi_register_echocan_factory);
EXPORT_SYMBOL(dahdi_unregister_echocan_factory);

EXPORT_SYMBOL(dahdi_set_hpec_ioctl);

#ifdef CONFIG_PROC_FS
static struct proc_dir_entry *root_proc_entry;
#endif

static int deftaps = 64;

int debug;
#define DEBUG_MAIN	(1 << 0)
#define DEBUG_RBS	(1 << 5)

/*!
 * \brief states for transmit signalling
 */
enum dahdi_txstate {
	DAHDI_TXSTATE_ONHOOK,
	DAHDI_TXSTATE_OFFHOOK,
	DAHDI_TXSTATE_START,
	DAHDI_TXSTATE_PREWINK,
	DAHDI_TXSTATE_WINK,
	DAHDI_TXSTATE_PREFLASH,
	DAHDI_TXSTATE_FLASH,
	DAHDI_TXSTATE_DEBOUNCE,
	DAHDI_TXSTATE_AFTERSTART,
	DAHDI_TXSTATE_RINGON,
	DAHDI_TXSTATE_RINGOFF,
	DAHDI_TXSTATE_KEWL,
	DAHDI_TXSTATE_AFTERKEWL,
	DAHDI_TXSTATE_PULSEBREAK,
	DAHDI_TXSTATE_PULSEMAKE,
	DAHDI_TXSTATE_PULSEAFTER,
};

typedef short sumtype[DAHDI_MAX_CHUNKSIZE];

static sumtype sums[(DAHDI_MAX_CONF + 1) * 3];

/* Translate conference aliases into actual conferences
   and vice-versa */
static short confalias[DAHDI_MAX_CONF + 1];
static short confrev[DAHDI_MAX_CONF + 1];

static sumtype *conf_sums_next;
static sumtype *conf_sums;
static sumtype *conf_sums_prev;

static struct dahdi_span *master;
struct file_operations *dahdi_transcode_fops = NULL;

#ifdef CONFIG_DAHDI_CORE_TIMER

static struct core_timer {
	struct timer_list timer;
	struct timespec start_interval;
	unsigned long interval;
	atomic_t count;
	atomic_t shutdown;
	atomic_t last_count;
} core_timer;

#endif /* CONFIG_DAHDI_CORE_TIMER */


enum dahdi_digit_mode {
	DIGIT_MODE_DTMF,
	DIGIT_MODE_MFR1,
	DIGIT_MODE_PULSE,
	DIGIT_MODE_MFR2_FWD,
	DIGIT_MODE_MFR2_REV,
};

/* At the end of silence, the tone stops */
static struct dahdi_tone dtmf_silence = {
	.tonesamples = DAHDI_MS_TO_SAMPLES(DAHDI_CONFIG_DEFAULT_DTMF_LENGTH),
};

/* At the end of silence, the tone stops */
static struct dahdi_tone mfr1_silence = {
	.tonesamples = DAHDI_MS_TO_SAMPLES(DAHDI_CONFIG_DEFAULT_MFR1_LENGTH),
};

/* At the end of silence, the tone stops */
static struct dahdi_tone mfr2_silence = {
	.tonesamples = DAHDI_MS_TO_SAMPLES(DAHDI_CONFIG_DEFAULT_MFR2_LENGTH),
};

/* A pause in the dialing */
static struct dahdi_tone tone_pause = {
	.tonesamples = DAHDI_MS_TO_SAMPLES(DAHDI_CONFIG_PAUSE_LENGTH),
};

static struct dahdi_dialparams global_dialparams = {
	.dtmf_tonelen = DAHDI_MS_TO_SAMPLES(DAHDI_CONFIG_DEFAULT_DTMF_LENGTH),
	.mfv1_tonelen = DAHDI_MS_TO_SAMPLES(DAHDI_CONFIG_DEFAULT_MFR1_LENGTH),
	.mfr2_tonelen = DAHDI_MS_TO_SAMPLES(DAHDI_CONFIG_DEFAULT_MFR2_LENGTH),
};

static DEFINE_MUTEX(global_dialparamslock);

static int dahdi_chan_ioctl(struct file *file, unsigned int cmd, unsigned long data);

#if defined(CONFIG_DAHDI_MMX) || defined(ECHO_CAN_FP)
#if (defined(CONFIG_X86) && !defined(CONFIG_X86_64)) || defined(CONFIG_I386)
struct fpu_save_buf {
	unsigned long cr0;
	unsigned long fpu_buf[128];
};

static DEFINE_PER_CPU(struct fpu_save_buf, fpu_buf);

/** dahdi_kernel_fpu_begin() - Save floating point registers
 *
 * This function is similar to kernel_fpu_begin() . However it is
 * designed to work in an interrupt context. Restoring must be done with
 * dahdi_kernel_fpu_end().
 *
 * Furthermore, the whole code between the call to
 * dahdi_kernel_fpu_begin() and dahdi_kernel_fpu_end() must reside
 * inside a spinlock. Otherwise the context might be restored to the
 * wrong process.
 *
 * Current implementation is x86/ia32-specific and will not even build on 
 * x86_64)
 * */
static inline void dahdi_kernel_fpu_begin(void)
{
	struct fpu_save_buf *buf = &__get_cpu_var(fpu_buf);
	__asm__ __volatile__ ("movl %%cr0,%0; clts" : "=r" (buf->cr0));
	__asm__ __volatile__ ("fnsave %0" : "=m" (buf->fpu_buf));
}

/** dahdi_kernel_fpu_end() - restore floating point context
 *
 * Must be used with context saved by dahdi_kernel_fpu_begin(). See its
 * documentation for further information.
 */
static inline void dahdi_kernel_fpu_end(void)
{
	struct fpu_save_buf *buf = &__get_cpu_var(fpu_buf);
	__asm__ __volatile__ ("frstor %0" : "=m" (buf->fpu_buf));
	__asm__ __volatile__ ("movl %0,%%cr0" : : "r" (buf->cr0));
}

#else /* We haven't fixed FP context saving/restoring yet */
/* Very strange things can happen when the context is not properly
 * restored. OTOH, some people do report success with this. Hence we
 * so far just issue a warning */
#warning CONFIG_DAHDI_MMX may behave randomly on this platform
#define dahdi_kernel_fpu_begin kernel_fpu_begin
#define dahdi_kernel_fpu_end   kernel_fpu_end
#endif

#endif

/**
 * struct dahdi_timer_rate - A collection of timers of a given rate.
 * @rate_samples: Samples until these timers fire.
 * @cur_samples:  Samples processed since last firing.
 * @sel:	  Wait queue for timer waiters.
 * @timers:	  List of individual timers at this rate.
 * @node:	  For storing on dahdi_timer_rates list.
 *
 */
struct dahdi_timer_rate {
	int rate_samples;
	int cur_samples;
	wait_queue_head_t sel;
	struct list_head timers;
	struct list_head node;
};

/**
 * struct dahdi_timer - A dahdi timer opened from user space.
 * @ping:	1 if we should operate in "continuous mode".
 * @tripped:	Count of times we've tripped.
 * @rate:	The rate this timer fires at.
 * @node:	To store on rate->timers list.
 *
 * When a timer is in "continuous" mode, it should always return immediately
 * from a poll call from user space.
 *
 */
struct dahdi_timer {
	atomic_t ping;
	atomic_t tripped;
	struct dahdi_timer_rate *rate;
	struct list_head node;
};

static LIST_HEAD(dahdi_timer_rates);
static DEFINE_SPINLOCK(dahdi_timer_lock);
static DEFINE_MUTEX(dahdi_timer_mutex);

#define DEFAULT_TONE_ZONE (-1)

struct dahdi_zone {
	int ringcadence[DAHDI_MAX_CADENCE];
	struct dahdi_tone *tones[DAHDI_TONE_MAX];
	/* Each of these is a circular list
	   of dahdi_tones to generate what we
	   want.  Use NULL if the tone is
	   unavailable */
	struct dahdi_tone dtmf[16];		/* DTMF tones for this zone, with desired length */
	struct dahdi_tone dtmf_continuous[16];	/* DTMF tones for this zone, continuous play */
	struct dahdi_tone mfr1[15];		/* MFR1 tones for this zone, with desired length */
	struct dahdi_tone mfr2_fwd[15];		/* MFR2 FWD tones for this zone, with desired length */
	struct dahdi_tone mfr2_rev[15];		/* MFR2 REV tones for this zone, with desired length */
	struct dahdi_tone mfr2_fwd_continuous[16];	/* MFR2 FWD tones for this zone, continuous play */
	struct dahdi_tone mfr2_rev_continuous[16];	/* MFR2 REV tones for this zone, continuous play */
	struct list_head node;
	struct kref refcount;
	const char *name;	/* Informational, only */
	u8 num;
};

static void tone_zone_release(struct kref *kref)
{
	struct dahdi_zone *z = container_of(kref, struct dahdi_zone, refcount);
	kfree(z->name);
	kfree(z);
}

/**
 * tone_zone_put()  - Release the reference on the tone_zone.
 *
 * On old kernels, since kref_put does not have a return value, we'll just
 * always report that we released the memory.
 *
 */
static inline int tone_zone_put(struct dahdi_zone *z)
{
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 12)
	kref_put(&z->refcount, tone_zone_release);
	return 1;
#else
	return kref_put(&z->refcount, tone_zone_release);
#endif
}

static inline void tone_zone_get(struct dahdi_zone *z)
{
	kref_get(&z->refcount);
}

static DEFINE_SPINLOCK(zone_lock);

/* The first zone on the list is the default zone. */
static LIST_HEAD(tone_zones);

/* Protects the span_list and pseudo_chans lists from concurrent access in
 * process context.  The spin_lock is needed to synchronize with the interrupt
 * handler. */
static DEFINE_SPINLOCK(chan_lock);

struct pseudo_chan {
	struct dahdi_chan chan;
	struct list_head node;
};

static inline struct pseudo_chan *chan_to_pseudo(struct dahdi_chan *chan)
{
	return container_of(chan, struct pseudo_chan, chan);
}

enum { FIRST_PSEUDO_CHANNEL = 0x8000, };
/* This list is protected by the chan_lock. */
static LIST_HEAD(pseudo_chans);

/**
 * is_pseudo_chan() - By definition pseudo channels are not on a span.
 */
static inline bool is_pseudo_chan(const struct dahdi_chan *chan)
{
	return (NULL == chan->span);
}

static DEFINE_MUTEX(registration_mutex);
static LIST_HEAD(span_list);

static unsigned long
__for_each_channel(unsigned long (*func)(struct dahdi_chan *chan,
					 unsigned long data),
		   unsigned long data)
{
	int res;
	struct dahdi_span *s;
	struct pseudo_chan *pseudo;

	list_for_each_entry(s, &span_list, spans_node) {
		unsigned long x;
		for (x = 0; x < s->channels; x++) {
			struct dahdi_chan *const chan = s->chans[x];
			res = func(chan, data);
			if (res)
				return res;
		}
	}

	list_for_each_entry(pseudo, &pseudo_chans, node) {
		res = func(&pseudo->chan, data);
		if (res)
			return res;
	}
	return 0;
}

/**
 * _chan_from_num - Lookup a channel
 *
 * Must be called with the registration_mutex held.
 *
 */
static struct dahdi_chan *_chan_from_num(unsigned int channo)
{
	struct dahdi_span *s;
	struct pseudo_chan *pseudo;

	if (channo >= FIRST_PSEUDO_CHANNEL) {
		list_for_each_entry(pseudo, &pseudo_chans, node) {
			if (pseudo->chan.channo == channo)
				return &pseudo->chan;
		}
		return NULL;
	}

	/* When searching for the channel amongst the spans, we can use the
	 * fact that channels on a span must be numbered consecutively to skip
	 * checking each individual channel. */
	list_for_each_entry(s, &span_list, spans_node) {
		unsigned int basechan;
		struct dahdi_chan *chan;

		if (unlikely(!s->channels))
			continue;

		basechan = s->chans[0]->channo;
		if (channo >= (basechan + s->channels))
			continue;

		/* Since all the spans should be on the list in sorted order,
		 * if channo is less than base chan, the caller must be
		 * looking for a channel that has already been removed. */
		if (unlikely(channo < basechan))
			return NULL;

		chan = s->chans[channo - basechan];
		WARN_ON(chan->channo != channo);
		return chan;
	}

	return NULL;
}

static struct dahdi_chan *chan_from_num(unsigned int channo)
{
	struct dahdi_chan *chan;
	mutex_lock(&registration_mutex);
	chan = _chan_from_num(channo);
	mutex_unlock(&registration_mutex);
	return chan;
}

static inline struct dahdi_chan *chan_from_file(struct file *file)
{
	return (file->private_data) ?
			file->private_data : chan_from_num(UNIT(file));
}

/**
 * _find_span() - Find a span by span number.
 *
 * Must be called with registration_mutex held.
 *
 */
static struct dahdi_span *_find_span(int spanno)
{
	struct dahdi_span *s;
	list_for_each_entry(s, &span_list, spans_node) {
		if (s->spanno == spanno) {
			return s;
		}
	}
	return NULL;
}
/**
 * span_find_and_get() - Search for the span by number, and if found take out
 * a reference on it.
 *
 * When you are no longer using the returned pointer, you must release it with
 * a put_span call.
 *
 */
static struct dahdi_span *span_find_and_get(int spanno)
{
	struct dahdi_span *found;

	mutex_lock(&registration_mutex);
	found = _find_span(spanno);
	if (found && !get_span(found))
		found = NULL;
	mutex_unlock(&registration_mutex);
	return found;
}

static unsigned int span_count(void)
{
	unsigned int count = 0;
	struct dahdi_span *s;
	unsigned long flags;
	spin_lock_irqsave(&chan_lock, flags);
	list_for_each_entry(s, &span_list, spans_node)
		++count;
	spin_unlock_irqrestore(&chan_lock, flags);
	return count;
}

static inline bool can_provide_timing(const struct dahdi_span *const s)
{
	return !s->cannot_provide_timing;
}

static int maxconfs;

short __dahdi_mulaw[256];
short __dahdi_alaw[256];

#ifndef CONFIG_CALC_XLAW
u_char __dahdi_lin2mu[16384];

u_char __dahdi_lin2a[16384];
#endif

static u_char defgain[256];

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 10)
#define __RW_LOCK_UNLOCKED() RW_LOCK_UNLOCKED
#endif

#define NUM_SIGS	10

static DEFINE_SPINLOCK(ecfactory_list_lock);

static LIST_HEAD(ecfactory_list);

struct ecfactory {
	const struct dahdi_echocan_factory *ec;
	struct list_head list;
};

int dahdi_register_echocan_factory(const struct dahdi_echocan_factory *ec)
{
	struct ecfactory *cur;
	struct ecfactory *new;

	WARN_ON(!ec->owner);

	new = kzalloc(sizeof(*new), GFP_KERNEL);
	if (!new)
		return -ENOMEM;

	INIT_LIST_HEAD(&new->list);

	spin_lock(&ecfactory_list_lock);

	/* make sure it isn't already registered */
	list_for_each_entry(cur, &ecfactory_list, list) {
		if (cur->ec == ec) {
			spin_unlock(&ecfactory_list_lock);
			kfree(new);
			return -EPERM;
		}
	}

	new->ec = ec;
	list_add_tail(&new->list, &ecfactory_list);

	spin_unlock(&ecfactory_list_lock);

	return 0;
}

void dahdi_unregister_echocan_factory(const struct dahdi_echocan_factory *ec)
{
	struct ecfactory *cur, *next;

	spin_lock(&ecfactory_list_lock);

	list_for_each_entry_safe(cur, next, &ecfactory_list, list) {
		if (cur->ec == ec) {
			list_del(&cur->list);
			kfree(cur);
			break;
		}
	}

	spin_unlock(&ecfactory_list_lock);
}

static inline void rotate_sums(void)
{
	/* Rotate where we sum and so forth */
	static int pos = 0;
	conf_sums_prev = sums + (DAHDI_MAX_CONF + 1) * pos;
	conf_sums = sums + (DAHDI_MAX_CONF + 1) * ((pos + 1) % 3);
	conf_sums_next = sums + (DAHDI_MAX_CONF + 1) * ((pos + 2) % 3);
	pos = (pos + 1) % 3;
	memset(conf_sums_next, 0, maxconfs * sizeof(sumtype));
}

/**
 * is_chan_dacsed() - True if chan is sourcing it's data from another channel.
 *
 */
static inline bool is_chan_dacsed(const struct dahdi_chan *const chan)
{
	return (NULL != chan->dacs_chan);
}

/**
 * can_dacs_chans() - Returns true if it may be possible to dacs two channels.
 *
 */
static bool can_dacs_chans(struct dahdi_chan *dst, struct dahdi_chan *src)
{
	if (src && dst && src->span && dst->span && src->span->ops &&
	    dst->span->ops && src->span->ops->dacs &&
	    (src->span->ops->dacs == dst->span->ops->dacs))
		return true;
	else
		return false;
}

/**
 * dahdi_chan_dacs() - Cross (or uncross) connect two channels.
 * @dst:	Channel on which to transmit the src data.
 * @src:	NULL to disable cross connect, otherwise the source of the
 *		data.
 *
 * This allows those boards that support it to cross connect one channel to
 * another in hardware.  If the cards cannot be crossed, uncross the
 * destination channel by default..
 *
 */
static int dahdi_chan_dacs(struct dahdi_chan *dst, struct dahdi_chan *src)
{
	int ret = 0;
	if (can_dacs_chans(dst, src))
		ret = dst->span->ops->dacs(dst, src);
	else if (dst->span && dst->span->ops->dacs)
		ret = dst->span->ops->dacs(dst, NULL);
	return ret;
}

static void dahdi_disable_dacs(struct dahdi_chan *chan)
{
	dahdi_chan_dacs(chan, NULL);
}

/*!
 * \return quiescent (idle) signalling states, for the various signalling types
 */
static int dahdi_q_sig(struct dahdi_chan *chan)
{
	int	x;
	static const unsigned int in_sig[NUM_SIGS][2] = {
		{ DAHDI_SIG_NONE,  0 },
		{ DAHDI_SIG_EM,    (DAHDI_ABIT << 8) },
		{ DAHDI_SIG_FXSLS, DAHDI_BBIT | (DAHDI_BBIT << 8) },
		{ DAHDI_SIG_FXSGS, DAHDI_ABIT | DAHDI_BBIT | ((DAHDI_ABIT | DAHDI_BBIT) << 8) },
		{ DAHDI_SIG_FXSKS, DAHDI_BBIT | ((DAHDI_ABIT | DAHDI_BBIT) << 8) },
		{ DAHDI_SIG_FXOLS, (DAHDI_ABIT << 8) },
		{ DAHDI_SIG_FXOGS, DAHDI_BBIT | ((DAHDI_ABIT | DAHDI_BBIT) << 8) },
		{ DAHDI_SIG_FXOKS, (DAHDI_ABIT << 8) },
		{ DAHDI_SIG_SF,    0 },
		{ DAHDI_SIG_EM_E1, DAHDI_DBIT | ((DAHDI_ABIT | DAHDI_DBIT) << 8) },
	};

	/* must have span to begin with */
	if (!chan->span)
		return -1;

	/* if RBS does not apply, return error */
	if (!(chan->span->flags & DAHDI_FLAG_RBS) || !chan->span->ops->rbsbits)
		return -1;

	if (chan->sig == DAHDI_SIG_CAS)
		return chan->idlebits;

	for (x = 0; x < NUM_SIGS; x++) {
		if (in_sig[x][0] == chan->sig)
			return in_sig[x][1];
	}

	return -1; /* not found -- error */
}

#ifdef CONFIG_PROC_FS
static const char *sigstr(int sig)
{
	switch (sig) {
	case DAHDI_SIG_FXSLS:
		return "FXSLS";
	case DAHDI_SIG_FXSKS:
		return "FXSKS";
	case DAHDI_SIG_FXSGS:
		return "FXSGS";
	case DAHDI_SIG_FXOLS:
		return "FXOLS";
	case DAHDI_SIG_FXOKS:
		return "FXOKS";
	case DAHDI_SIG_FXOGS:
		return "FXOGS";
	case DAHDI_SIG_EM:
		return "E&M";
	case DAHDI_SIG_EM_E1:
		return "E&M-E1";
	case DAHDI_SIG_CLEAR:
		return "Clear";
	case DAHDI_SIG_HDLCRAW:
		return "HDLCRAW";
	case DAHDI_SIG_HDLCFCS:
		return "HDLCFCS";
	case DAHDI_SIG_HDLCNET:
		return "HDLCNET";
	case DAHDI_SIG_HARDHDLC:
		return "Hardware-assisted HDLC";
	case DAHDI_SIG_MTP2:
		return "MTP2";
	case DAHDI_SIG_SLAVE:
		return "Slave";
	case DAHDI_SIG_CAS:
		return "CAS";
	case DAHDI_SIG_DACS:
		return "DACS";
	case DAHDI_SIG_DACS_RBS:
		return "DACS+RBS";
	case DAHDI_SIG_SF:
		return "SF (ToneOnly)";
	case DAHDI_SIG_NONE:
	default:
		return "Unconfigured";
	}
}

static int fill_alarm_string(char *buf, int count, int alarms)
{
	int len;

	if (alarms <= 0)
		return 0;

	len = snprintf(buf, count, "%s%s%s%s%s%s",
			(alarms & DAHDI_ALARM_BLUE) ? "BLUE " : "",
			(alarms & DAHDI_ALARM_YELLOW) ? "YELLOW " : "",
			(alarms & DAHDI_ALARM_RED) ? "RED " : "",
			(alarms & DAHDI_ALARM_LOOPBACK) ? "LOOP " : "",
			(alarms & DAHDI_ALARM_RECOVER) ? "RECOVERING " : "",
			(alarms & DAHDI_ALARM_NOTOPEN) ? "NOTOPEN " : "");

	return len;
}

/*
 * Sequential proc interface
 */

static void seq_fill_alarm_string(struct seq_file *sfile, int alarms)
{
	char tmp[70];

	if (fill_alarm_string(tmp, sizeof(tmp), alarms))
		seq_printf(sfile, "%s", tmp);
}

static int dahdi_seq_show(struct seq_file *sfile, void *v)
{
	long spanno = (long)sfile->private;
	int x;
	struct dahdi_span *s;

	s = span_find_and_get(spanno);
	if (!s)
		return -ENODEV;

	if (s->name)
		seq_printf(sfile, "Span %d: %s ", s->spanno, s->name);
	if (s->desc)
		seq_printf(sfile, "\"%s\"", s->desc);
	else
		seq_printf(sfile, "\"\"");

	if (s == master)
		seq_printf(sfile, " (MASTER)");

	if (s->lineconfig) {
		/* framing first */
		if (s->lineconfig & DAHDI_CONFIG_B8ZS)
			seq_printf(sfile, " B8ZS/");
		else if (s->lineconfig & DAHDI_CONFIG_AMI)
			seq_printf(sfile, " AMI/");
		else if (s->lineconfig & DAHDI_CONFIG_HDB3)
			seq_printf(sfile, " HDB3/");
		/* then coding */
		if (s->lineconfig & DAHDI_CONFIG_ESF)
			seq_printf(sfile, "ESF");
		else if (s->lineconfig & DAHDI_CONFIG_D4)
			seq_printf(sfile, "D4");
		else if (s->lineconfig & DAHDI_CONFIG_CCS)
			seq_printf(sfile, "CCS");
		/* E1's can enable CRC checking */
		if (s->lineconfig & DAHDI_CONFIG_CRC4)
			seq_printf(sfile, "/CRC4");
	}

	seq_printf(sfile, " ");

	/* list alarms */
	seq_fill_alarm_string(sfile, s->alarms);
	if (s->syncsrc &&
		(s->syncsrc == s->spanno))
		seq_printf(sfile, "ClockSource ");
	seq_printf(sfile, "\n");
	if (s->count.bpv)
		seq_printf(sfile, "\tBPV count: %d\n", s->count.bpv);
	if (s->count.crc4)
		seq_printf(sfile, "\tCRC4 error count: %d\n", s->count.crc4);
	if (s->count.ebit)
		seq_printf(sfile, "\tE-bit error count: %d\n", s->count.ebit);
	if (s->count.fas)
		seq_printf(sfile, "\tFAS error count: %d\n", s->count.fas);
	if (s->parent->irqmisses)
		seq_printf(sfile, "\tIRQ misses: %d\n", s->parent->irqmisses);
	if (s->timingslips)
		seq_printf(sfile, "\tTiming slips: %d\n", s->timingslips);
	seq_printf(sfile, "\n");

	for (x = 0; x < s->channels; x++) {
		struct dahdi_chan *chan = s->chans[x];

		if (chan->name)
			seq_printf(sfile, "\t%4d %s ", chan->channo,
					chan->name);

		if (chan->sig) {
			if (chan->sig == DAHDI_SIG_SLAVE)
				seq_printf(sfile, "%s ",
						sigstr(chan->master->sig));
			else {
				seq_printf(sfile, "%s ", sigstr(chan->sig));
				if (chan->nextslave &&
					(chan->master->channo == chan->channo))
					seq_printf(sfile, "Master ");
			}
		} else if (!chan->sigcap) {
			seq_printf(sfile, "Reserved ");
		}

		if (test_bit(DAHDI_FLAGBIT_OPEN, &chan->flags))
			seq_printf(sfile, "(In use) ");

#ifdef	OPTIMIZE_CHANMUTE
		if (chan->chanmute)
			seq_printf(sfile, "(no pcm) ");
#endif

		seq_fill_alarm_string(sfile, chan->chan_alarms);

		if (chan->ec_factory)
			seq_printf(sfile, "(EC: %s - %s) ",
					chan->ec_factory->get_name(chan),
					chan->ec_state ? "ACTIVE" : "INACTIVE");

		seq_printf(sfile, "\n");
	}
	put_span(s);
	return 0;
}

static int dahdi_proc_open(struct inode *inode, struct file *file)
{
	return single_open(file, dahdi_seq_show, PDE(inode)->data);
}

static const struct file_operations dahdi_proc_ops = {
	.owner		= THIS_MODULE,
	.open		= dahdi_proc_open,
	.read		= seq_read,
	.llseek		= seq_lseek,
	.release	= single_release,
};

#endif

static int dahdi_first_empty_alias(void)
{
	/* Find the first conference which has no alias pointing to it */
	int x;
	for (x=1;x<DAHDI_MAX_CONF;x++) {
		if (!confrev[x])
			return x;
	}
	return -1;
}

static void recalc_maxconfs(void)
{
	int x;

	for (x = DAHDI_MAX_CONF - 1; x > 0; x--) {
		if (confrev[x]) {
			maxconfs = x + 1;
			return;
		}
	}

	maxconfs = 0;
}

static int dahdi_first_empty_conference(void)
{
	/* Find the first conference which has no alias */
	int x;

	for (x = DAHDI_MAX_CONF - 1; x > 0; x--) {
		if (!confalias[x])
			return x;
	}

	return -1;
}

static int dahdi_get_conf_alias(int x)
{
	int a;

	if (confalias[x])
		return confalias[x];

	/* Allocate an alias */
	a = dahdi_first_empty_alias();
	confalias[x] = a;
	confrev[a] = x;

	/* Highest conference may have changed */
	recalc_maxconfs();

	return a;
}

static unsigned long _chan_in_conf(struct dahdi_chan *chan, unsigned long x)
{
	const int confmode = chan->confmode & DAHDI_CONF_MODE_MASK;
	return (chan && (chan->confna == x) &&
	    (confmode == DAHDI_CONF_CONF ||
	     confmode == DAHDI_CONF_CONFANN ||
	     confmode == DAHDI_CONF_CONFMON ||
	     confmode == DAHDI_CONF_CONFANNMON ||
	     confmode == DAHDI_CONF_REALANDPSEUDO)) ? 1 : 0;
}

static void dahdi_check_conf(int x)
{
	unsigned long res;
	unsigned long flags;

	/* return if no valid conf number */
	if (x <= 0)
		return;

	/* Return if there is no alias */
	if (!confalias[x])
		return;

	spin_lock_irqsave(&chan_lock, flags);
	res = __for_each_channel(_chan_in_conf, x);
	spin_unlock_irqrestore(&chan_lock, flags);
	if (res)
		return;

	/* If we get here, nobody is in the conference anymore.  Clear it out
	   both forward and reverse */
	confrev[confalias[x]] = 0;
	confalias[x] = 0;

	/* Highest conference may have changed */
	recalc_maxconfs();
}

/* enqueue an event on a channel */
static void __qevent(struct dahdi_chan *chan, int event)
{
	/* if full, ignore */
	if ((chan->eventoutidx == 0) && (chan->eventinidx == (DAHDI_MAX_EVENTSIZE - 1)))
		return;

	/* if full, ignore */
	if (chan->eventinidx == (chan->eventoutidx - 1))
		return;

	/* save the event */
	chan->eventbuf[chan->eventinidx++] = event;

	/* wrap the index, if necessary */
	if (chan->eventinidx >= DAHDI_MAX_EVENTSIZE)
		chan->eventinidx = 0;

	/* wake em all up */
	wake_up_interruptible(&chan->waitq);

	return;
}

void dahdi_qevent_nolock(struct dahdi_chan *chan, int event)
{
	__qevent(chan, event);
}

void dahdi_qevent_lock(struct dahdi_chan *chan, int event)
{
	unsigned long flags;
	spin_lock_irqsave(&chan->lock, flags);
	__qevent(chan, event);
	spin_unlock_irqrestore(&chan->lock, flags);
}

static inline void calc_fcs(struct dahdi_chan *ss, int inwritebuf)
{
	int x;
	unsigned int fcs = PPP_INITFCS;
	unsigned char *data = ss->writebuf[inwritebuf];
	int len = ss->writen[inwritebuf];

	/* Not enough space to do FCS calculation */
	if (len < 2)
		return;

	for (x = 0; x < len - 2; x++)
		fcs = PPP_FCS(fcs, data[x]);

	fcs ^= 0xffff;
	/* Send out the FCS */
	data[len - 2] = (fcs & 0xff);
	data[len - 1] = (fcs >> 8) & 0xff;
}

static int dahdi_reallocbufs(struct dahdi_chan *ss, int blocksize, int numbufs)
{
	unsigned char *newtxbuf = NULL;
	unsigned char *newrxbuf = NULL;
	unsigned char *oldtxbuf = NULL;
	unsigned char *oldrxbuf = NULL;
	unsigned long flags;
	int x;

	/* Check numbufs */
	if (numbufs < 2)
		numbufs = 2;

	if (numbufs > DAHDI_MAX_NUM_BUFS)
		numbufs = DAHDI_MAX_NUM_BUFS;

	/* We need to allocate our buffers now */
	if (blocksize) {
		newtxbuf = kzalloc(blocksize * numbufs, GFP_KERNEL);
		if (NULL == newtxbuf)
			return -ENOMEM;
		newrxbuf = kzalloc(blocksize * numbufs, GFP_KERNEL);
		if (NULL == newrxbuf) {
			kfree(newtxbuf);
			return -ENOMEM;
		}
	}

	/* Now that we've allocated our new buffers, we can safely
 	   move things around... */

	spin_lock_irqsave(&ss->lock, flags);

	ss->blocksize = blocksize; /* set the blocksize */
	oldrxbuf = ss->readbuf[0]; /* Keep track of the old buffer */
	oldtxbuf = ss->writebuf[0];
	ss->readbuf[0] = NULL;

	if (newrxbuf) {
		BUG_ON(NULL == newtxbuf);
		for (x = 0; x < numbufs; x++) {
			ss->readbuf[x] = newrxbuf + x * blocksize;
			ss->writebuf[x] = newtxbuf + x * blocksize;
		}
	} else {
		for (x = 0; x < numbufs; x++) {
			ss->readbuf[x] = NULL;
			ss->writebuf[x] = NULL;
		}
	}

	/* Mark all buffers as empty */
	for (x = 0; x < numbufs; x++) {
		ss->writen[x] =
		ss->writeidx[x]=
		ss->readn[x]=
		ss->readidx[x] = 0;
	}

	/* Keep track of where our data goes (if it goes
	   anywhere at all) */
	if (newrxbuf) {
		ss->inreadbuf = 0;
		ss->inwritebuf = 0;
	} else {
		ss->inreadbuf = -1;
		ss->inwritebuf = -1;
	}

	ss->outreadbuf = -1;
	ss->outwritebuf = -1;
	ss->numbufs = numbufs;

	if ((ss->txbufpolicy == DAHDI_POLICY_WHEN_FULL) || (ss->txbufpolicy == DAHDI_POLICY_HALF_FULL))
		ss->txdisable = 1;
	else
		ss->txdisable = 0;

	if (ss->rxbufpolicy == DAHDI_POLICY_WHEN_FULL)
		ss->rxdisable = 1;
	else
		ss->rxdisable = 0;

	spin_unlock_irqrestore(&ss->lock, flags);

	kfree(oldtxbuf);
	kfree(oldrxbuf);

	return 0;
}

static int dahdi_hangup(struct dahdi_chan *chan);
static void dahdi_set_law(struct dahdi_chan *chan, int law);

/* Pull a DAHDI_CHUNKSIZE piece off the queue.  Returns
   0 on success or -1 on failure.  If failed, provides
   silence */
static int __buf_pull(struct confq *q, u_char *data, struct dahdi_chan *c)
{
	int oldoutbuf = q->outbuf;
	/* Ain't nuffin to read */
	if (q->outbuf < 0) {
		if (data)
			memset(data, DAHDI_LIN2X(0,c), DAHDI_CHUNKSIZE);
		return -1;
	}
	if (data)
		memcpy(data, q->buf[q->outbuf], DAHDI_CHUNKSIZE);
	q->outbuf = (q->outbuf + 1) % DAHDI_CB_SIZE;

	/* Won't be nuffin next time */
	if (q->outbuf == q->inbuf) {
		q->outbuf = -1;
	}

	/* If they thought there was no space then
	   there is now where we just read */
	if (q->inbuf < 0)
		q->inbuf = oldoutbuf;
	return 0;
}

/* Returns a place to put stuff, or NULL if there is
   no room */

static u_char *__buf_pushpeek(struct confq *q)
{
	if (q->inbuf < 0)
		return NULL;
	return q->buf[q->inbuf];
}

static u_char *__buf_peek(struct confq *q)
{
	if (q->outbuf < 0)
		return NULL;
	return q->buf[q->outbuf];
}

/* Push something onto the queue, or assume what
   is there is valid if data is NULL */
static int __buf_push(struct confq *q, const u_char *data)
{
	int oldinbuf = q->inbuf;
	if (q->inbuf < 0) {
		return -1;
	}
	if (data)
		/* Copy in the data */
		memcpy(q->buf[q->inbuf], data, DAHDI_CHUNKSIZE);

	/* Advance the inbuf pointer */
	q->inbuf = (q->inbuf + 1) % DAHDI_CB_SIZE;

	if (q->inbuf == q->outbuf) {
		/* No space anymore... */
		q->inbuf = -1;
	}
	/* If they don't think data is ready, let
	   them know it is now */
	if (q->outbuf < 0) {
		q->outbuf = oldinbuf;
	}
	return 0;
}

static void reset_conf(struct dahdi_chan *chan)
{
	int x;

	/* Empty out buffers and reset to initialization */

	for (x = 0; x < DAHDI_CB_SIZE; x++)
		chan->confin.buf[x] = chan->confin.buffer + DAHDI_CHUNKSIZE * x;

	chan->confin.inbuf = 0;
	chan->confin.outbuf = -1;

	for (x = 0; x < DAHDI_CB_SIZE; x++)
		chan->confout.buf[x] = chan->confout.buffer + DAHDI_CHUNKSIZE * x;

	chan->confout.inbuf = 0;
	chan->confout.outbuf = -1;
}


static const struct dahdi_echocan_factory *find_echocan(const char *name)
{
	struct ecfactory *cur;
	char *name_upper;
	char *c;
	const char *d;
	char modname_buf[128] = "dahdi_echocan_";
	unsigned int tried_once = 0;

	name_upper = kmalloc(strlen(name) + 1, GFP_KERNEL);
	if (!name_upper)
		return NULL;

	for (c = name_upper, d = name; *d; c++, d++) {
		*c = toupper(*d);
	}

	*c = '\0';

retry:
	spin_lock(&ecfactory_list_lock);

	list_for_each_entry(cur, &ecfactory_list, list) {
		if (!strcmp(name_upper, cur->ec->get_name(NULL))) {
			if (try_module_get(cur->ec->owner)) {
				spin_unlock(&ecfactory_list_lock);
				kfree(name_upper);
				return cur->ec;
			} else {
				spin_unlock(&ecfactory_list_lock);
				kfree(name_upper);
				return NULL;
			}
		}
	}

	spin_unlock(&ecfactory_list_lock);

	if (tried_once) {
		kfree(name_upper);
		return NULL;
	}

	/* couldn't find it, let's try to load it */

	for (c = &modname_buf[strlen(modname_buf)], d = name; *d; c++, d++) {
		*c = tolower(*d);
	}

	request_module("%s", modname_buf);

	tried_once = 1;

	/* and try one more time */
	goto retry;
}

static void release_echocan(const struct dahdi_echocan_factory *ec)
{
	if (ec)
		module_put(ec->owner);
}

/**
 * is_gain_allocated() - True if gain tables were dynamically allocated.
 * @chan:  The channel to check.
 */
static inline bool is_gain_allocated(const struct dahdi_chan *chan)
{
	return (chan->rxgain && (chan->rxgain != defgain));
}

/* 
 * close_channel - close the channel, resetting any channel variables
 * @chan: the dahdi_chan to close
 *
 * This function is called before either the parent span is linked into the
 * span list, or for pseudos, place on the psuedo_list.  Therefore, this
 * function nor it's callers should depend on the channel being findable
 * via those methods.
 */
static void close_channel(struct dahdi_chan *chan)
{
	unsigned long flags;
	const void *rxgain = NULL;
	struct dahdi_echocan_state *ec_state;
	const struct dahdi_echocan_factory *ec_current;
	int oldconf;
	short *readchunkpreec;
#ifdef CONFIG_DAHDI_PPP
	struct ppp_channel *ppp;
#endif

	might_sleep();

	/* XXX Buffers should be send out before reallocation!!! XXX */
	if (!(chan->flags & DAHDI_FLAG_NOSTDTXRX))
		dahdi_reallocbufs(chan, 0, 0);
	spin_lock_irqsave(&chan->lock, flags);
#ifdef CONFIG_DAHDI_PPP
	ppp = chan->ppp;
	chan->ppp = NULL;
#endif
	ec_state = chan->ec_state;
	chan->ec_state = NULL;
	ec_current = chan->ec_current;
	chan->ec_current = NULL;
	readchunkpreec = chan->readchunkpreec;
	chan->readchunkpreec = NULL;
	chan->curtone = NULL;
	if (chan->curzone) {
		struct dahdi_zone *zone = chan->curzone;
		chan->curzone = NULL;
		tone_zone_put(zone);
	}
	chan->cadencepos = 0;
	chan->pdialcount = 0;
	dahdi_hangup(chan);
	chan->itimerset = chan->itimer = 0;
	chan->pulsecount = 0;
	chan->pulsetimer = 0;
	chan->ringdebtimer = 0;
	chan->txdialbuf[0] = '\0';
	chan->digitmode = DIGIT_MODE_DTMF;
	chan->dialing = 0;
	chan->afterdialingtimer = 0;
	  /* initialize IO MUX mask */
	chan->iomask = 0;
	/* save old conf number, if any */
	oldconf = chan->confna;
	  /* initialize conference variables */
	chan->_confn = 0;
	chan->confna = 0;
	chan->confmode = 0;
	if ((chan->sig & __DAHDI_SIG_DACS) != __DAHDI_SIG_DACS)
		chan->dacs_chan = NULL;

	chan->confmute = 0;
	chan->gotgs = 0;
	reset_conf(chan);
	chan->dacs_chan = NULL;

	if (is_gain_allocated(chan))
		rxgain = chan->rxgain;

	chan->rxgain = defgain;
	chan->txgain = defgain;
	chan->eventinidx = chan->eventoutidx = 0;
	chan->flags &= ~(DAHDI_FLAG_LOOPED | DAHDI_FLAG_LINEAR | DAHDI_FLAG_PPP | DAHDI_FLAG_SIGFREEZE);

	dahdi_set_law(chan, DAHDI_LAW_DEFAULT);

	memset(chan->conflast, 0, sizeof(chan->conflast));
	memset(chan->conflast1, 0, sizeof(chan->conflast1));
	memset(chan->conflast2, 0, sizeof(chan->conflast2));

	if (chan->span && oldconf)
		dahdi_disable_dacs(chan);

	if (ec_state) {
		ec_state->ops->echocan_free(chan, ec_state);
		release_echocan(ec_current);
	}

	spin_unlock_irqrestore(&chan->lock, flags);

	/* release conference resource, if any to release */
	if (oldconf)
		dahdi_check_conf(oldconf);

	if (rxgain)
		kfree(rxgain);
	if (readchunkpreec)
		kfree(readchunkpreec);

#ifdef CONFIG_DAHDI_PPP
	if (ppp) {
		tasklet_kill(&chan->ppp_calls);
		skb_queue_purge(&chan->ppp_rq);
		ppp_unregister_channel(ppp);
		kfree(ppp);
	}
#endif

}

static int dahdi_ioctl_freezone(unsigned long data)
{
	struct dahdi_zone *z;
	struct dahdi_zone *found = NULL;
	int num;

	if (get_user(num, (int __user *) data))
		return -EFAULT;

	spin_lock(&zone_lock);
	list_for_each_entry(z, &tone_zones, node) {
		if (z->num == num) {
			found = z;
			break;
		}
	}
	if (found) {
		list_del(&found->node);
		tone_zone_put(found);
	}
	spin_unlock(&zone_lock);
	return 0;
}

static int dahdi_register_tone_zone(struct dahdi_zone *zone)
{
	struct dahdi_zone *cur;
	int res = 0;

	kref_init(&zone->refcount);
	spin_lock(&zone_lock);
	list_for_each_entry(cur, &tone_zones, node) {
		if (cur->num == zone->num) {
			res = -EINVAL;
			break;
		}
	}
	if (!res) {
		list_add_tail(&zone->node, &tone_zones);
		module_printk(KERN_INFO, "Registered tone zone %d (%s)\n",
			      zone->num, zone->name);
	}
	spin_unlock(&zone_lock);

	return res;
}

static int start_tone_digit(struct dahdi_chan *chan, int tone)
{
	struct dahdi_tone *playtone = NULL;
	int base, max;

	if (!chan->curzone)
		return -ENODATA;

	switch (chan->digitmode) {
	case DIGIT_MODE_DTMF:
		/* Set dialing so that a dial operation doesn't interrupt this tone */
		chan->dialing = 1;
		base = DAHDI_TONE_DTMF_BASE;
		max = DAHDI_TONE_DTMF_MAX;
		break;
	case DIGIT_MODE_MFR2_FWD:
		base = DAHDI_TONE_MFR2_FWD_BASE;
		max = DAHDI_TONE_MFR2_FWD_MAX;
		break;
	case DIGIT_MODE_MFR2_REV:
		base = DAHDI_TONE_MFR2_REV_BASE;
		max = DAHDI_TONE_MFR2_REV_MAX;
		break;
	default:
		return -EINVAL;
	}

	if ((tone < base) || (tone > max))
		return -EINVAL;

	switch (chan->digitmode) {
	case DIGIT_MODE_DTMF:
		playtone = &chan->curzone->dtmf_continuous[tone - base];
		break;
	case DIGIT_MODE_MFR2_FWD:
		playtone = &chan->curzone->mfr2_fwd_continuous[tone - base];
		break;
	case DIGIT_MODE_MFR2_REV:
		playtone = &chan->curzone->mfr2_rev_continuous[tone - base];
		break;
	}

	if (!playtone || !playtone->tonesamples)
		return -ENOSYS;

	chan->curtone = playtone;

	return 0;
}

static int start_tone(struct dahdi_chan *chan, int tone)
{
	int res = -EINVAL;

	/* Stop the current tone, no matter what */
	chan->tonep = 0;
	chan->curtone = NULL;
	chan->pdialcount = 0;
	chan->txdialbuf[0] = '\0';
	chan->dialing = 0;

	if (tone == -1) {
		/* Just stop the current tone */
		res = 0;
	} else if (!chan->curzone) {
		static int __warnonce = 1;
		if (__warnonce) {
			__warnonce = 0;
			/* The tonezones are loaded by dahdi_cfg based on /etc/dahdi/system.conf. */
			module_printk(KERN_WARNING, "DAHDI: Cannot start tones until tone zone is loaded.\n");
		}
		/* Note that no tone zone exists at the moment */
		res = -ENODATA;
	} else if ((tone >= 0 && tone <= DAHDI_TONE_MAX)) {
		/* Have a tone zone */
		if (chan->curzone->tones[tone]) {
			chan->curtone = chan->curzone->tones[tone];
			res = 0;
		} else { /* Indicate that zone is loaded but no such tone exists */
			res = -ENOSYS;
		}
	} else if (chan->digitmode == DIGIT_MODE_DTMF ||
			chan->digitmode == DIGIT_MODE_MFR2_FWD ||
			chan->digitmode == DIGIT_MODE_MFR2_REV) {
		res = start_tone_digit(chan, tone);
	} else {
		chan->dialing = 0;
		res = -EINVAL;
	}

	if (chan->curtone)
		dahdi_init_tone_state(&chan->ts, chan->curtone);

	return res;
}

static int set_tone_zone(struct dahdi_chan *chan, int zone)
{
	int res = 0;
	struct dahdi_zone *cur;
	struct dahdi_zone *z;
	unsigned long flags;

	z = NULL;
	spin_lock(&zone_lock);
	if ((DEFAULT_TONE_ZONE == zone) && !list_empty(&tone_zones)) {
		z = list_entry(tone_zones.next, struct dahdi_zone, node);
		tone_zone_get(z);
	} else {
		list_for_each_entry(cur, &tone_zones, node) {
			if (cur->num != (u8)zone)
				continue;
			z = cur;
			tone_zone_get(z);
			break;
		}
	}
	spin_unlock(&zone_lock);

	if (unlikely(!z))
		return -ENODATA;

	spin_lock_irqsave(&chan->lock, flags);
	if (chan->curzone) {
		struct dahdi_zone *zone = chan->curzone;
		chan->curzone = NULL;
		tone_zone_put(zone);
	}
	chan->curzone = z;
	memcpy(chan->ringcadence, z->ringcadence, sizeof(chan->ringcadence));
	spin_unlock_irqrestore(&chan->lock, flags);

	return res;
}

static void dahdi_set_law(struct dahdi_chan *chan, int law)
{
	if (DAHDI_LAW_DEFAULT == law) {
		if (chan->deflaw)
			law = chan->deflaw;
		else
			if (chan->span) law = chan->span->deflaw;
			else law = DAHDI_LAW_MULAW;
	}
	if (law == DAHDI_LAW_ALAW) {
		chan->xlaw = __dahdi_alaw;
#ifdef CONFIG_CALC_XLAW
		chan->lineartoxlaw = __dahdi_lineartoalaw;
#else
		chan->lin2x = __dahdi_lin2a;
#endif
	} else {
		chan->xlaw = __dahdi_mulaw;
#ifdef CONFIG_CALC_XLAW
		chan->lineartoxlaw = __dahdi_lineartoulaw;
#else
		chan->lin2x = __dahdi_lin2mu;
#endif
	}
}

/**
 * __dahdi_init_chan - Initialize the channel data structures.
 * @chan:	The channel to initialize
 *
 */
static void __dahdi_init_chan(struct dahdi_chan *chan)
{
	might_sleep();

	spin_lock_init(&chan->lock);
	init_waitqueue_head(&chan->waitq);
	if (!chan->master)
		chan->master = chan;
	if (!chan->readchunk)
		chan->readchunk = chan->sreadchunk;
	if (!chan->writechunk)
		chan->writechunk = chan->swritechunk;
	chan->rxgain = NULL;
	chan->txgain = NULL;
	close_channel(chan);
}

/**
 * dahdi_chan_reg - Mark the channel registered.
 *
 * This must be called after close channel during registration, normally
 * covered by the call to __dahdi_init_chan, to avoid "HDLC hangage"
 */
static inline void dahdi_chan_reg(struct dahdi_chan *chan)
{
	set_bit(DAHDI_FLAGBIT_REGISTERED, &chan->flags);
}

/**
 * dahdi_lboname() - Convert line build out number to string.
 *
 */
const char *dahdi_lboname(int lbo)
{
	/* names of tx level settings */
	static const char *const dahdi_txlevelnames[] = {
		"0 db (CSU)/0-133 feet (DSX-1)",
		"133-266 feet (DSX-1)",
		"266-399 feet (DSX-1)",
		"399-533 feet (DSX-1)",
		"533-655 feet (DSX-1)",
		"-7.5db (CSU)",
		"-15db (CSU)",
		"-22.5db (CSU)"
	};

	if ((lbo < 0) || (lbo > 7))
		return "Unknown";
	return dahdi_txlevelnames[lbo];
}
EXPORT_SYMBOL(dahdi_lboname);

#if defined(CONFIG_DAHDI_NET) || defined(CONFIG_DAHDI_PPP)
static inline void print_debug_writebuf(struct dahdi_chan* ss, struct sk_buff *skb, int oldbuf)
{
#ifdef CONFIG_DAHDI_DEBUG
	int x;

	module_printk(KERN_NOTICE, "Buffered %d bytes to go out in buffer %d\n", ss->writen[oldbuf], oldbuf);
	module_printk(KERN_DEBUG "");
	for (x=0;x<ss->writen[oldbuf];x++)
		printk("%02x ", ss->writebuf[oldbuf][x]);
	printk("\n");
#endif
}
#endif

#ifdef CONFIG_DAHDI_NET
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 26)
static inline struct net_device_stats *hdlc_stats(struct net_device *dev)
{
	return &dev->stats;
}
#endif

static int dahdi_net_open(struct net_device *dev)
{
	int res = hdlc_open(dev);
	struct dahdi_chan *ms = netdev_to_chan(dev);

/*	if (!dev->hard_start_xmit) return res; is this really necessary? --byg */
	if (res) /* this is necessary to avoid kernel panic when UNSPEC link encap, proven --byg */
		return res;

	if (!ms) {
		module_printk(KERN_NOTICE, "dahdi_net_open: nothing??\n");
		return -EINVAL;
	}
	if (test_bit(DAHDI_FLAGBIT_OPEN, &ms->flags)) {
		module_printk(KERN_NOTICE, "%s is already open!\n", ms->name);
		return -EBUSY;
	}
	if (!dahdi_have_netdev(ms)) {
		module_printk(KERN_NOTICE, "%s is not a net device!\n", ms->name);
		return -EINVAL;
	}
	ms->txbufpolicy = DAHDI_POLICY_IMMEDIATE;
	ms->rxbufpolicy = DAHDI_POLICY_IMMEDIATE;

	res = dahdi_reallocbufs(ms, DAHDI_DEFAULT_MTU_MRU, DAHDI_DEFAULT_NUM_BUFS);
	if (res)
		return res;

	fasthdlc_init(&ms->rxhdlc, (ms->flags & DAHDI_FLAG_HDLC56) ? FASTHDLC_MODE_56 : FASTHDLC_MODE_64);
	fasthdlc_init(&ms->txhdlc, (ms->flags & DAHDI_FLAG_HDLC56) ? FASTHDLC_MODE_56 : FASTHDLC_MODE_64);
	ms->infcs = PPP_INITFCS;

	netif_start_queue(chan_to_netdev(ms));

#ifdef CONFIG_DAHDI_DEBUG
	module_printk(KERN_NOTICE, "DAHDINET: Opened channel %d name %s\n", ms->channo, ms->name);
#endif
	return 0;
}

static int dahdi_register_hdlc_device(struct net_device *dev, const char *dev_name)
{
	int result;

	if (dev_name && *dev_name) {
		if ((result = dev_alloc_name(dev, dev_name)) < 0)
			return result;
	}
	result = register_netdev(dev);
	if (result != 0)
		return -EIO;
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,14)
	if (netif_carrier_ok(dev))
		netif_carrier_off(dev); /* no carrier until DCD goes up */
#endif
	return 0;
}

static int dahdi_net_stop(struct net_device *dev)
{
	hdlc_device *h = dev_to_hdlc(dev);
	struct dahdi_hdlc *hdlc = h->priv;

	struct dahdi_chan *ms = hdlc_to_chan(hdlc);
	if (!ms) {
		module_printk(KERN_NOTICE, "dahdi_net_stop: nothing??\n");
		return 0;
	}
	if (!dahdi_have_netdev(ms)) {
		module_printk(KERN_NOTICE, "dahdi_net_stop: %s is not a net device!\n", ms->name);
		return 0;
	}
	/* Not much to do here.  Just deallocate the buffers */
	netif_stop_queue(chan_to_netdev(ms));
	dahdi_reallocbufs(ms, 0, 0);
	hdlc_close(dev);
	return 0;
}

/* kernel 2.4.20+ has introduced attach function, dunno what to do,
 just copy sources from dscc4 to be sure and ready for further mastering,
 NOOP right now (i.e. really a stub)  --byg */
static int dahdi_net_attach(struct net_device *dev, unsigned short encoding,
        unsigned short parity)
{
/*        struct net_device *dev = hdlc_to_dev(hdlc);
        struct dscc4_dev_priv *dpriv = dscc4_priv(dev);

        if (encoding != ENCODING_NRZ &&
            encoding != ENCODING_NRZI &&
            encoding != ENCODING_FM_MARK &&
            encoding != ENCODING_FM_SPACE &&
            encoding != ENCODING_MANCHESTER)
                return -EINVAL;

        if (parity != PARITY_NONE &&
            parity != PARITY_CRC16_PR0_CCITT &&
            parity != PARITY_CRC16_PR1_CCITT &&
            parity != PARITY_CRC32_PR0_CCITT &&
            parity != PARITY_CRC32_PR1_CCITT)
                return -EINVAL;

        dpriv->encoding = encoding;
        dpriv->parity = parity;*/
        return 0;
}

static struct dahdi_hdlc *dahdi_hdlc_alloc(void)
{
	return kzalloc(sizeof(struct dahdi_hdlc), GFP_KERNEL);
}

static int dahdi_xmit(struct sk_buff *skb, struct net_device *dev)
{
	/* FIXME: this construction seems to be not very optimal for me but I
	 * could find nothing better at the moment (Friday, 10PM :( )  --byg
	 * */
	struct dahdi_chan *ss = netdev_to_chan(dev);
	struct net_device_stats *stats = hdlc_stats(dev);

	int retval = 1;
	int x,oldbuf;
	unsigned int fcs;
	unsigned char *data;
	unsigned long flags;
	/* See if we have any buffers */
	spin_lock_irqsave(&ss->lock, flags);
	if (skb->len > ss->blocksize - 2) {
		module_printk(KERN_ERR, "dahdi_xmit(%s): skb is too large (%d > %d)\n", dev->name, skb->len, ss->blocksize -2);
		stats->tx_dropped++;
		retval = 0;
	} else if (ss->inwritebuf >= 0) {
		/* We have a place to put this packet */
		/* XXX We should keep the SKB and avoid the memcpy XXX */
		data = ss->writebuf[ss->inwritebuf];
		memcpy(data, skb->data, skb->len);
		ss->writen[ss->inwritebuf] = skb->len;
		ss->writeidx[ss->inwritebuf] = 0;
		/* Calculate the FCS */
		fcs = PPP_INITFCS;
		for (x=0;x<skb->len;x++)
			fcs = PPP_FCS(fcs, data[x]);
		/* Invert it */
		fcs ^= 0xffff;
		/* Send it out LSB first */
		data[ss->writen[ss->inwritebuf]++] = (fcs & 0xff);
		data[ss->writen[ss->inwritebuf]++] = (fcs >> 8) & 0xff;
		/* Advance to next window */
		oldbuf = ss->inwritebuf;
		ss->inwritebuf = (ss->inwritebuf + 1) % ss->numbufs;

		if (ss->inwritebuf == ss->outwritebuf) {
			/* Whoops, no more space.  */
		    ss->inwritebuf = -1;

		    netif_stop_queue(chan_to_netdev(ss));
		}
		if (ss->outwritebuf < 0) {
			/* Let the interrupt handler know there's
			   some space for us */
			ss->outwritebuf = oldbuf;
		}
		dev->trans_start = jiffies;
		stats->tx_packets++;
		stats->tx_bytes += ss->writen[oldbuf];
		print_debug_writebuf(ss, skb, oldbuf);
		retval = 0;
		/* Free the SKB */
		dev_kfree_skb_any(skb);
	}
	spin_unlock_irqrestore(&ss->lock, flags);
	return retval;
}

static int dahdi_net_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
	return hdlc_ioctl(dev, ifr, cmd);
}

#endif

#ifdef CONFIG_DAHDI_PPP

static int dahdi_ppp_xmit(struct ppp_channel *ppp, struct sk_buff *skb)
{

	/*
	 * If we can't handle the packet right now, return 0.  If we
	 * we handle or drop it, return 1.  Always free if we return
	 * 1 and never if we return 0
         */
	struct dahdi_chan *ss = ppp->private;
	int x,oldbuf;
	unsigned int fcs;
	unsigned char *data;
	unsigned long flags;
	int retval = 0;

	/* See if we have any buffers */
	spin_lock_irqsave(&ss->lock, flags);
	if (!(test_bit(DAHDI_FLAGBIT_OPEN, &ss->flags))) {
		module_printk(KERN_ERR, "Can't transmit on closed channel\n");
		retval = 1;
	} else if (skb->len > ss->blocksize - 4) {
		module_printk(KERN_ERR, "dahdi_ppp_xmit(%s): skb is too large (%d > %d)\n", ss->name, skb->len, ss->blocksize -2);
		retval = 1;
	} else if (ss->inwritebuf >= 0) {
		/* We have a place to put this packet */
		/* XXX We should keep the SKB and avoid the memcpy XXX */
		data = ss->writebuf[ss->inwritebuf];
		/* Start with header of two bytes */
		/* Add "ALL STATIONS" and "UNNUMBERED" */
		data[0] = 0xff;
		data[1] = 0x03;
		ss->writen[ss->inwritebuf] = 2;

		/* Copy real data and increment amount written */
		memcpy(data + 2, skb->data, skb->len);

		ss->writen[ss->inwritebuf] += skb->len;

		/* Re-set index back to zero */
		ss->writeidx[ss->inwritebuf] = 0;

		/* Calculate the FCS */
		fcs = PPP_INITFCS;
		for (x=0;x<skb->len + 2;x++)
			fcs = PPP_FCS(fcs, data[x]);
		/* Invert it */
		fcs ^= 0xffff;

		/* Point past the real data now */
		data += (skb->len + 2);

		/* Send FCS out LSB first */
		data[0] = (fcs & 0xff);
		data[1] = (fcs >> 8) & 0xff;

		/* Account for FCS length */
		ss->writen[ss->inwritebuf]+=2;

		/* Advance to next window */
		oldbuf = ss->inwritebuf;
		ss->inwritebuf = (ss->inwritebuf + 1) % ss->numbufs;

		if (ss->inwritebuf == ss->outwritebuf) {
			/* Whoops, no more space.  */
			ss->inwritebuf = -1;
		}
		if (ss->outwritebuf < 0) {
			/* Let the interrupt handler know there's
			   some space for us */
			ss->outwritebuf = oldbuf;
		}
		print_debug_writebuf(ss, skb, oldbuf);
		retval = 1;
	}
	spin_unlock_irqrestore(&ss->lock, flags);
	if (retval) {
		/* Get rid of the SKB if we're returning non-zero */
		/* N.B. this is called in process or BH context so
		   dev_kfree_skb is OK. */
		dev_kfree_skb(skb);
	}
	return retval;
}

static int dahdi_ppp_ioctl(struct ppp_channel *ppp, unsigned int cmd, unsigned long flags)
{
	return -EIO;
}

static struct ppp_channel_ops ztppp_ops =
{
	.start_xmit = dahdi_ppp_xmit,
	.ioctl      = dahdi_ppp_ioctl,
};

#endif

/**
 * is_monitor_mode() - True if the confmode indicates that one channel is monitoring another.
 *
 */
static bool is_monitor_mode(int confmode)
{
	confmode &= DAHDI_CONF_MODE_MASK;
	if ((confmode == DAHDI_CONF_MONITOR) ||
	    (confmode == DAHDI_CONF_MONITORTX) ||
	    (confmode == DAHDI_CONF_MONITORBOTH) ||
	    (confmode == DAHDI_CONF_MONITOR_RX_PREECHO) ||
	    (confmode == DAHDI_CONF_MONITOR_TX_PREECHO) ||
	    (confmode == DAHDI_CONF_MONITORBOTH_PREECHO)) {
		return true;
	} else {
		return false;
	}
}

static unsigned long _chan_cleanup(struct dahdi_chan *pos, unsigned long data)
{
	unsigned long flags;
	struct dahdi_chan *const chan = (struct dahdi_chan *)data;
	/* Remove anyone pointing to us as master
	   and make them their own thing */
	if (pos->master == chan)
		pos->master = pos;

	if (((pos->confna == chan->channo) &&
	    is_monitor_mode(pos->confmode)) ||
	    (pos->dacs_chan == chan) ||
	    (pos->conf_chan == chan)) {
		/* Take them out of conference with us */
		/* release conference resource if any */
		if (pos->confna)
			dahdi_check_conf(pos->confna);

		dahdi_disable_dacs(pos);
		spin_lock_irqsave(&pos->lock, flags);
		pos->confna = 0;
		pos->_confn = 0;
		pos->confmode = 0;
		pos->conf_chan = NULL;
		pos->dacs_chan = NULL;
		spin_unlock_irqrestore(&pos->lock, flags);
	}

	return 0;
}

static void dahdi_chan_unreg(struct dahdi_chan *chan)
{
	unsigned long flags;

	might_sleep();

	/* In the case of surprise removal of hardware, make sure any open
	 * file handles to this channel are disassociated with the actual
	 * dahdi_chan. */
	if (chan->file) {
		chan->file->private_data = NULL;
		if (chan->span)
			module_put(chan->span->ops->owner);
	}

	release_echocan(chan->ec_factory);

#ifdef CONFIG_DAHDI_NET
	if (dahdi_have_netdev(chan)) {
		unregister_hdlc_device(chan->hdlcnetdev->netdev);
		free_netdev(chan->hdlcnetdev->netdev);
		kfree(chan->hdlcnetdev);
		chan->hdlcnetdev = NULL;
	}
#endif
	clear_bit(DAHDI_FLAGBIT_REGISTERED, &chan->flags);

#ifdef CONFIG_DAHDI_PPP
	if (chan->ppp) {
		module_printk(KERN_NOTICE, "HUH???  PPP still attached??\n");
	}
#endif
	spin_lock_irqsave(&chan_lock, flags);
	__for_each_channel(_chan_cleanup, (unsigned long)chan);
	spin_unlock_irqrestore(&chan_lock, flags);

	chan->channo = -1;
}

static ssize_t dahdi_chan_read(struct file *file, char __user *usrbuf,
			       size_t count, loff_t *ppos)
{
	struct dahdi_chan *chan = file->private_data;
	int amnt;
	int res, rv;
	int oldbuf,x;
	unsigned long flags;

	/* Make sure count never exceeds 65k, and make sure it's unsigned */
	count &= 0xffff;

	if (unlikely(!chan)) {
		/* We would typically be here because of surprise hardware
		 * removal or driver unbinding while a user space application
		 * has a channel open.  Most telephony applications are run at
		 * elevated priorities so this sleep can prevent the high
		 * priority threads from consuming the CPU if they're not
		 * expecting surprise device removal.
		 */
		msleep(5);
		return -ENODEV;
	}

	if (unlikely(count < 1))
		return -EINVAL;

	for (;;) {
		spin_lock_irqsave(&chan->lock, flags);
		if (chan->eventinidx != chan->eventoutidx) {
			spin_unlock_irqrestore(&chan->lock, flags);
			return -ELAST /* - chan->eventbuf[chan->eventoutidx]*/;
		}
		res = chan->outreadbuf;
		if (chan->rxdisable)
			res = -1;
		spin_unlock_irqrestore(&chan->lock, flags);
		if (res >= 0)
			break;
		if (file->f_flags & O_NONBLOCK)
			return -EAGAIN;
		rv = wait_event_interruptible(chan->waitq,
				(chan->outreadbuf > -1));
		if (rv)
			return rv;
	}
	amnt = count;
	if (chan->flags & DAHDI_FLAG_LINEAR) {
		if (amnt > (chan->readn[res] << 1))
			amnt = chan->readn[res] << 1;
		if (amnt) {
			/* There seems to be a max stack size, so we have
			   to do this in smaller pieces */
			short lindata[128];
			int left = amnt >> 1; /* amnt is in bytes */
			int pos = 0;
			int pass;
			while (left) {
				pass = left;
				if (pass > 128)
					pass = 128;
				for (x = 0; x < pass; x++)
					lindata[x] = DAHDI_XLAW(chan->readbuf[res][x + pos], chan);
				if (copy_to_user(usrbuf + (pos << 1), lindata, pass << 1))
					return -EFAULT;
				left -= pass;
				pos += pass;
			}
		}
	} else {
		if (amnt > chan->readn[res])
			amnt = chan->readn[res];
		if (amnt) {
			if (copy_to_user(usrbuf, chan->readbuf[res], amnt))
				return -EFAULT;
		}
	}
	spin_lock_irqsave(&chan->lock, flags);
	chan->readidx[res] = 0;
	chan->readn[res] = 0;
	oldbuf = res;
	chan->outreadbuf = (res + 1) % chan->numbufs;
	if (chan->outreadbuf == chan->inreadbuf) {
		/* Out of stuff */
		chan->outreadbuf = -1;
		if (chan->rxbufpolicy == DAHDI_POLICY_WHEN_FULL)
			chan->rxdisable = 1;
	}
	if (chan->inreadbuf < 0) {
		/* Notify interrupt handler that we have some space now */
		chan->inreadbuf = oldbuf;
	}
	spin_unlock_irqrestore(&chan->lock, flags);

	return amnt;
}

static int num_filled_bufs(struct dahdi_chan *chan)
{
	int range1, range2;

	if (chan->inwritebuf < 0) {
		return chan->numbufs;
	}

	if (chan->outwritebuf < 0) {
		return 0;
	}

	if (chan->outwritebuf <= chan->inwritebuf) {
		return chan->inwritebuf - chan->outwritebuf;
	}

	/* This means (in > out) and we have wrap around */
	range1 = chan->numbufs - chan->outwritebuf;
	range2 = chan->inwritebuf;

	return range1 + range2;
}

static ssize_t dahdi_chan_write(struct file *file, const char __user *usrbuf,
				size_t count, loff_t *ppos)
{
	unsigned long flags;
	struct dahdi_chan *chan = file->private_data;
	int res, amnt, oldbuf, rv, x;

	/* Make sure count never exceeds 65k, and make sure it's unsigned */
	count &= 0xffff;

	if (unlikely(!chan)) {
		/* We would typically be here because of surprise hardware
		 * removal or driver unbinding while a user space application
		 * has a channel open.  Most telephony applications are run at
		 * elevated priorities so this sleep can prevent the high
		 * priority threads from consuming the CPU if they're not
		 * expecting surprise device removal.
		 */
		msleep(5);
		return -ENODEV;
	}

	if (unlikely(count < 1))
		return -EINVAL;

	for (;;) {
		spin_lock_irqsave(&chan->lock, flags);
		if ((chan->curtone || chan->pdialcount) && !is_pseudo_chan(chan)) {
			chan->curtone = NULL;
			chan->tonep = 0;
			chan->dialing = 0;
			chan->txdialbuf[0] = '\0';
			chan->pdialcount = 0;
		}
		if (chan->eventinidx != chan->eventoutidx) {
			spin_unlock_irqrestore(&chan->lock, flags);
			return -ELAST;
		}
		res = chan->inwritebuf;
		spin_unlock_irqrestore(&chan->lock, flags);
		if (res >= 0)
			break;
		if (file->f_flags & O_NONBLOCK) {
#ifdef BUFFER_DEBUG
			printk("Error: Nonblock\n");
#endif
			return -EAGAIN;
		}
		/* Wait for something to be available */
		rv = wait_event_interruptible(chan->waitq,
					      (chan->inwritebuf >= 0));
		if (rv)
			return rv;
	}

	amnt = count;
	if (chan->flags & DAHDI_FLAG_LINEAR) {
		if (amnt > (chan->blocksize << 1))
			amnt = chan->blocksize << 1;
	} else {
		if (amnt > chan->blocksize)
			amnt = chan->blocksize;
	}

#ifdef CONFIG_DAHDI_DEBUG
	module_printk(KERN_NOTICE, "dahdi_chan_write(chan: %d, res: %d, outwritebuf: %d amnt: %d\n",
		      chan->channo, res, chan->outwritebuf, amnt);
#endif

	if (amnt) {
		if (chan->flags & DAHDI_FLAG_LINEAR) {
			/* There seems to be a max stack size, so we have
			   to do this in smaller pieces */
			short lindata[128];
			int left = amnt >> 1; /* amnt is in bytes */
			int pos = 0;
			int pass;
			while (left) {
				pass = left;
				if (pass > 128)
					pass = 128;
				if (copy_from_user(lindata, usrbuf + (pos << 1), pass << 1)) {
					return -EFAULT;
				}
				left -= pass;
				for (x = 0; x < pass; x++)
					chan->writebuf[res][x + pos] = DAHDI_LIN2X(lindata[x], chan);
				pos += pass;
			}
			chan->writen[res] = amnt >> 1;
		} else {
			if (copy_from_user(chan->writebuf[res], usrbuf, amnt)) {
				return -EFAULT;
			}
			chan->writen[res] = amnt;
		}
#ifdef CONFIG_DAHDI_ECHOCAN_PROCESS_TX
		if ((chan->ec_state) &&
		    (ECHO_MODE_ACTIVE == chan->ec_state->status.mode) &&
		    (chan->ec_state->ops->echocan_process_tx)) {
			struct ec_state *const ec_state = chan->ec_state;
			for (x = 0; x < chan->writen[res]; ++x) {
				short tx;
				tx = DAHDI_XLAW(chan->writebuf[res][x], chan);
				ec_state->ops->echocan_process_tx(ec_state,
								  &tx, 1);
				chan->writebuf[res][x] = DAHDI_LIN2X((int) tx,
								     chan);
			}
		}
#endif
		chan->writeidx[res] = 0;
		if (chan->flags & DAHDI_FLAG_FCS)
			calc_fcs(chan, res);
		oldbuf = res;
		spin_lock_irqsave(&chan->lock, flags);
		chan->inwritebuf = (res + 1) % chan->numbufs;

		if (chan->inwritebuf == chan->outwritebuf) {
			/* Don't stomp on the transmitter, just wait for them to
			   wake us up */
			chan->inwritebuf = -1;
			/* Make sure the transmitter is transmitting in case of POLICY_WHEN_FULL */
			chan->txdisable = 0;
		}

		if (chan->outwritebuf < 0) {
			/* Okay, the interrupt handler has been waiting for us.  Give them a buffer */
			chan->outwritebuf = oldbuf;
		}

		if ((chan->txbufpolicy == DAHDI_POLICY_HALF_FULL) && (chan->txdisable)) {
			if (num_filled_bufs(chan) >= (chan->numbufs >> 1)) {
#ifdef BUFFER_DEBUG
				printk("Reached buffer fill mark of %d\n", num_filled_bufs(chan));
#endif
				chan->txdisable = 0;
			}
		}

#ifdef BUFFER_DEBUG
		if ((chan->statcount <= 0) || (amnt != 128) || (num_filled_bufs(chan) != chan->lastnumbufs)) {
			printk("amnt: %d Number of filled buffers: %d\n", amnt, num_filled_bufs(chan));
			chan->statcount = 32000;
			chan->lastnumbufs = num_filled_bufs(chan);
		}
#endif

		spin_unlock_irqrestore(&chan->lock, flags);

		if (chan->flags & DAHDI_FLAG_NOSTDTXRX && chan->span->ops->hdlc_hard_xmit)
			chan->span->ops->hdlc_hard_xmit(chan);
	}
	return amnt;
}

static int dahdi_ctl_open(struct file *file)
{
	/* Nothing to do, really */
	return 0;
}

static int dahdi_chan_open(struct file *file)
{
	/* Nothing to do here for now either */
	return 0;
}

static int dahdi_ctl_release(struct file *file)
{
	/* Nothing to do */
	return 0;
}

static int dahdi_chan_release(struct file *file)
{
	/* Nothing to do for now */
	return 0;
}

static void set_txtone(struct dahdi_chan *ss, int fac, int init_v2, int init_v3)
{
	if (fac == 0) {
		ss->v2_1 = 0;
		ss->v3_1 = 0;
		return;
	}
	ss->txtone = fac;
	ss->v1_1 = 0;
	ss->v2_1 = init_v2;
	ss->v3_1 = init_v3;
	return;
}

static void dahdi_rbs_sethook(struct dahdi_chan *chan, int txsig, int txstate,
		int timeout)
{
	static const struct {
		unsigned int sig_type;
		/* Index is dahdi_txsig enum */
		unsigned int bits[DAHDI_TXSIG_TOTAL];
	} outs[NUM_SIGS] = {
		{
			/*
			 * We set the idle case of the DAHDI_SIG_NONE to this pattern to make idle E1 CAS
			 * channels happy. Should not matter with T1, since on an un-configured channel,
			 * who cares what the sig bits are as long as they are stable
			 */
			.sig_type = DAHDI_SIG_NONE,
			.bits[DAHDI_TXSIG_ONHOOK]  = DAHDI_BITS_ACD,
		}, {
			.sig_type = DAHDI_SIG_EM,
			.bits[DAHDI_TXSIG_OFFHOOK] = DAHDI_BITS_ABCD,
			.bits[DAHDI_TXSIG_START]   = DAHDI_BITS_ABCD,
		}, {
			.sig_type = DAHDI_SIG_FXSLS,
			.bits[DAHDI_TXSIG_ONHOOK]  = DAHDI_BITS_BD,
			.bits[DAHDI_TXSIG_OFFHOOK] = DAHDI_BITS_ABCD,
			.bits[DAHDI_TXSIG_START]   = DAHDI_BITS_ABCD,
		}, {
			.sig_type = DAHDI_SIG_FXSGS,
			.bits[DAHDI_TXSIG_ONHOOK]  = DAHDI_BITS_BD,
			.bits[DAHDI_TXSIG_OFFHOOK] = DAHDI_BITS_ABCD,
#ifndef CONFIG_CAC_GROUNDSTART
			.bits[DAHDI_TXSIG_START]   = DAHDI_BITS_AC,
#endif
		}, {
			.sig_type = DAHDI_SIG_FXSKS,
			.bits[DAHDI_TXSIG_ONHOOK]  = DAHDI_BITS_BD,
			.bits[DAHDI_TXSIG_OFFHOOK] = DAHDI_BITS_ABCD,
			.bits[DAHDI_TXSIG_START]   = DAHDI_BITS_ABCD,
		}, {
			.sig_type = DAHDI_SIG_FXOLS,
			.bits[DAHDI_TXSIG_ONHOOK]  = DAHDI_BITS_BD,
			.bits[DAHDI_TXSIG_OFFHOOK] = DAHDI_BITS_BD,
		}, {
			.sig_type = DAHDI_SIG_FXOGS,
			.bits[DAHDI_TXSIG_ONHOOK]  = DAHDI_BITS_ABCD,
			.bits[DAHDI_TXSIG_OFFHOOK] = DAHDI_BITS_BD,
		}, {
			.sig_type = DAHDI_SIG_FXOKS,
			.bits[DAHDI_TXSIG_ONHOOK]  = DAHDI_BITS_BD,
			.bits[DAHDI_TXSIG_OFFHOOK] = DAHDI_BITS_BD,
			.bits[DAHDI_TXSIG_KEWL]    = DAHDI_BITS_ABCD,
		}, {
			.sig_type = DAHDI_SIG_SF,
			.bits[DAHDI_TXSIG_ONHOOK]  = DAHDI_BITS_BCD,
			.bits[DAHDI_TXSIG_OFFHOOK] = DAHDI_BITS_ABCD,
			.bits[DAHDI_TXSIG_START]   = DAHDI_BITS_ABCD,
			.bits[DAHDI_TXSIG_KEWL]    = DAHDI_BITS_BCD,
		}, {
			.sig_type = DAHDI_SIG_EM_E1,
			.bits[DAHDI_TXSIG_ONHOOK]  = DAHDI_DBIT,
			.bits[DAHDI_TXSIG_OFFHOOK] = DAHDI_BITS_ABD,
			.bits[DAHDI_TXSIG_START]   = DAHDI_BITS_ABD,
			.bits[DAHDI_TXSIG_KEWL]    = DAHDI_DBIT,
		}
	};
	int x;

	/* if no span, return doing nothing */
	if (!chan->span)
		return;

	if (!(chan->span->flags & DAHDI_FLAG_RBS)) {
		module_printk(KERN_NOTICE, "dahdi_rbs: Tried to set RBS hook state on non-RBS channel %s\n", chan->name);
		return;
	}
	if ((txsig > 3) || (txsig < 0)) {
		module_printk(KERN_NOTICE, "dahdi_rbs: Tried to set RBS hook state %d (> 3) on  channel %s\n", txsig, chan->name);
		return;
	}
	if (!chan->span->ops->rbsbits && !chan->span->ops->hooksig) {
		module_printk(KERN_NOTICE, "dahdi_rbs: Tried to set RBS hook state %d on channel %s while span %s lacks rbsbits or hooksig function\n",
			txsig, chan->name, chan->span->name);
		return;
	}
	/* Don't do anything for RBS */
	if (chan->sig == DAHDI_SIG_DACS_RBS)
		return;
	chan->txstate = txstate;

	/* if tone signalling */
	if (chan->sig == DAHDI_SIG_SF) {
		chan->txhooksig = txsig;
		if (chan->txtone) { /* if set to make tone for tx */
			if ((txsig && !(chan->toneflags & DAHDI_REVERSE_TXTONE)) ||
			 ((!txsig) && (chan->toneflags & DAHDI_REVERSE_TXTONE))) {
				set_txtone(chan,chan->txtone,chan->tx_v2,chan->tx_v3);
			} else {
				set_txtone(chan,0,0,0);
			}
		}
		chan->otimer = timeout * DAHDI_CHUNKSIZE;			/* Otimer is timer in samples */
		return;
	}
	if (chan->span->ops->hooksig) {
		if (chan->txhooksig != txsig) {
			chan->txhooksig = txsig;
			chan->span->ops->hooksig(chan, txsig);
		}
		chan->otimer = timeout * DAHDI_CHUNKSIZE;			/* Otimer is timer in samples */
		return;
	} else {
		for (x = 0; x < NUM_SIGS; x++) {
			if (outs[x].sig_type == chan->sig) {
#ifdef CONFIG_DAHDI_DEBUG
				module_printk(KERN_NOTICE, "Setting bits to %d for channel %s state %d in %d signalling\n", outs[x].bits[txsig], chan->name, txsig, chan->sig);
#endif
				chan->txhooksig = txsig;
				chan->txsig = outs[x].bits[txsig];
				chan->span->ops->rbsbits(chan, chan->txsig);
				chan->otimer = timeout * DAHDI_CHUNKSIZE;	/* Otimer is timer in samples */
				return;
			}
		}
	}
	module_printk(KERN_NOTICE, "dahdi_rbs: Don't know RBS signalling type %d on channel %s\n", chan->sig, chan->name);
}

static int dahdi_cas_setbits(struct dahdi_chan *chan, int bits)
{
	/* if no span, return as error */
	if (!chan->span)
		return -1;
	if (chan->span->ops->rbsbits) {
		chan->txsig = bits;
		chan->span->ops->rbsbits(chan, bits);
	} else {
		module_printk(KERN_NOTICE, "Huh?  CAS setbits, but no RBS bits function\n");
	}

	return 0;
}

static int dahdi_hangup(struct dahdi_chan *chan)
{
	int x, res = 0;

	/* Can't hangup pseudo channels */
	if (!chan->span)
		return 0;

	/* Can't hang up a clear channel */
	if (chan->flags & (DAHDI_FLAG_CLEAR | DAHDI_FLAG_NOSTDTXRX))
		return -EINVAL;

	chan->kewlonhook = 0;

	if ((chan->sig == DAHDI_SIG_FXSLS) || (chan->sig == DAHDI_SIG_FXSKS) ||
			(chan->sig == DAHDI_SIG_FXSGS)) {
		chan->ringdebtimer = RING_DEBOUNCE_TIME;
	}

	if (chan->span->flags & DAHDI_FLAG_RBS) {
		if (chan->sig == DAHDI_SIG_CAS) {
			dahdi_cas_setbits(chan, chan->idlebits);
		} else if ((chan->sig == DAHDI_SIG_FXOKS) && (chan->txstate != DAHDI_TXSTATE_ONHOOK)
			/* if other party is already on-hook we shouldn't do any battery drop */
			&& !((chan->rxhooksig == DAHDI_RXSIG_ONHOOK) && (chan->itimer <= 0))) {
			/* Do RBS signalling on the channel's behalf */
			dahdi_rbs_sethook(chan, DAHDI_TXSIG_KEWL, DAHDI_TXSTATE_KEWL, DAHDI_KEWLTIME);
		} else
			dahdi_rbs_sethook(chan, DAHDI_TXSIG_ONHOOK, DAHDI_TXSTATE_ONHOOK, 0);
	} else {
		/* Let the driver hang up the line if it wants to  */
		if (chan->span->ops->sethook) {
			if (chan->txhooksig != DAHDI_ONHOOK) {
				chan->txhooksig = DAHDI_ONHOOK;
				res = chan->span->ops->sethook(chan, DAHDI_ONHOOK);
			} else
				res = 0;
		}
	}

	/* if not registered yet, just return here */
	if (!test_bit(DAHDI_FLAGBIT_REGISTERED, &chan->flags))
		return res;

	/* Mark all buffers as empty */
	for (x = 0; x < chan->numbufs; x++) {
		chan->writen[x] =
		chan->writeidx[x]=
		chan->readn[x]=
		chan->readidx[x] = 0;
	}

	if (chan->readbuf[0]) {
		chan->inreadbuf = 0;
		chan->inwritebuf = 0;
	} else {
		chan->inreadbuf = -1;
		chan->inwritebuf = -1;
	}
	chan->outreadbuf = -1;
	chan->outwritebuf = -1;
	chan->dialing = 0;
	chan->afterdialingtimer = 0;
	chan->curtone = NULL;
	chan->pdialcount = 0;
	chan->cadencepos = 0;
	chan->txdialbuf[0] = 0;

	return res;
}

static int initialize_channel(struct dahdi_chan *chan)
{
	int res;
	unsigned long flags;
	const void *rxgain = NULL;
	struct dahdi_echocan_state *ec_state;
	const struct dahdi_echocan_factory *ec_current;

	if ((res = dahdi_reallocbufs(chan, DAHDI_DEFAULT_BLOCKSIZE, DAHDI_DEFAULT_NUM_BUFS)))
		return res;

	spin_lock_irqsave(&chan->lock, flags);

	chan->rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
	chan->txbufpolicy = DAHDI_POLICY_IMMEDIATE;

	ec_state = chan->ec_state;
	chan->ec_state = NULL;
	ec_current = chan->ec_current;
	chan->ec_current = NULL;

	chan->txdisable = 0;
	chan->rxdisable = 0;

	chan->digitmode = DIGIT_MODE_DTMF;
	chan->dialing = 0;
	chan->afterdialingtimer = 0;

	chan->cadencepos = 0;
	chan->firstcadencepos = 0; /* By default loop back to first cadence position */

	/* HDLC & FCS stuff */
	fasthdlc_init(&chan->rxhdlc, (chan->flags & DAHDI_FLAG_HDLC56) ? FASTHDLC_MODE_56 : FASTHDLC_MODE_64);
	fasthdlc_init(&chan->txhdlc, (chan->flags & DAHDI_FLAG_HDLC56) ? FASTHDLC_MODE_56 : FASTHDLC_MODE_64);
	chan->infcs = PPP_INITFCS;

	/* Timings for RBS */
	chan->prewinktime = DAHDI_DEFAULT_PREWINKTIME;
	chan->preflashtime = DAHDI_DEFAULT_PREFLASHTIME;
	chan->winktime = DAHDI_DEFAULT_WINKTIME;
	chan->flashtime = DAHDI_DEFAULT_FLASHTIME;

	if (chan->sig & __DAHDI_SIG_FXO)
		chan->starttime = DAHDI_DEFAULT_RINGTIME;
	else
		chan->starttime = DAHDI_DEFAULT_STARTTIME;
	chan->rxwinktime = DAHDI_DEFAULT_RXWINKTIME;
	chan->rxflashtime = DAHDI_DEFAULT_RXFLASHTIME;
	chan->debouncetime = DAHDI_DEFAULT_DEBOUNCETIME;
	chan->pulsemaketime = DAHDI_DEFAULT_PULSEMAKETIME;
	chan->pulsebreaktime = DAHDI_DEFAULT_PULSEBREAKTIME;
	chan->pulseaftertime = DAHDI_DEFAULT_PULSEAFTERTIME;

	/* Initialize RBS timers */
	chan->itimerset = chan->itimer = chan->otimer = 0;
	chan->ringdebtimer = 0;

	/* Reset conferences */
	reset_conf(chan);

	chan->dacs_chan = NULL;

	/* I/O Mask, etc */
	chan->iomask = 0;
	/* release conference resource if any */
	if (chan->confna)
		dahdi_check_conf(chan->confna);
	if ((chan->sig & __DAHDI_SIG_DACS) != __DAHDI_SIG_DACS) {
		chan->confna = 0;
		chan->confmode = 0;
		chan->conf_chan = NULL;
		dahdi_disable_dacs(chan);
	}
	chan->_confn = 0;
	memset(chan->conflast, 0, sizeof(chan->conflast));
	memset(chan->conflast1, 0, sizeof(chan->conflast1));
	memset(chan->conflast2, 0, sizeof(chan->conflast2));
	chan->confmute = 0;
	chan->gotgs = 0;
	chan->curtone = NULL;
	chan->tonep = 0;
	chan->pdialcount = 0;
	if (is_gain_allocated(chan))
		rxgain = chan->rxgain;
	chan->rxgain = defgain;
	chan->txgain = defgain;
	chan->eventinidx = chan->eventoutidx = 0;
	dahdi_set_law(chan, DAHDI_LAW_DEFAULT);
	dahdi_hangup(chan);

	/* Make sure that the audio flag is cleared on a clear channel */
	if ((chan->sig & DAHDI_SIG_CLEAR) || (chan->sig & DAHDI_SIG_HARDHDLC))
		chan->flags &= ~DAHDI_FLAG_AUDIO;

	if ((chan->sig == DAHDI_SIG_CLEAR) || (chan->sig == DAHDI_SIG_HARDHDLC))
		chan->flags &= ~(DAHDI_FLAG_PPP | DAHDI_FLAG_FCS | DAHDI_FLAG_HDLC);

	chan->flags &= ~DAHDI_FLAG_LINEAR;
	if (chan->curzone) {
		/* Take cadence from tone zone */
		memcpy(chan->ringcadence, chan->curzone->ringcadence, sizeof(chan->ringcadence));
	} else {
		/* Do a default */
		memset(chan->ringcadence, 0, sizeof(chan->ringcadence));
		chan->ringcadence[0] = chan->starttime;
		chan->ringcadence[1] = DAHDI_RINGOFFTIME;
	}

	if (ec_state) {
		ec_state->ops->echocan_free(chan, ec_state);
		release_echocan(ec_current);
	}

	spin_unlock_irqrestore(&chan->lock, flags);

	set_tone_zone(chan, DEFAULT_TONE_ZONE);

	if (rxgain)
		kfree(rxgain);

	return 0;
}

static int dahdi_timing_open(struct file *file)
{
	struct dahdi_timer *t;

	t = kzalloc(sizeof(*t), GFP_KERNEL);
	if (!t)
		return -ENOMEM;

	INIT_LIST_HEAD(&t->node);
	file->private_data = t;

	return 0;
}

/**
 * _dahdi_remove_timer - Removes the timer from the rate it's associated with.
 *
 * Must be called with dahdi_timer_mutex held.
 */
static void _dahdi_remove_timer(struct dahdi_timer *timer)
{
	unsigned long flags;
	struct dahdi_timer_rate *const rate = timer->rate;

	spin_lock_irqsave(&dahdi_timer_lock, flags);
	list_del(&timer->node);
	if (rate && list_empty(&rate->timers)) {
		list_del(&rate->node);
		kfree(rate);
	}
	spin_unlock_irqrestore(&dahdi_timer_lock, flags);
	timer->rate = NULL;
}

static int dahdi_timer_release(struct file *file)
{
	struct dahdi_timer *timer = file->private_data;
	if (!timer)
		return 0;

	mutex_lock(&dahdi_timer_mutex);
	_dahdi_remove_timer(timer);
	mutex_unlock(&dahdi_timer_mutex);
	file->private_data = NULL;
	return 0;
}

static const struct file_operations dahdi_chan_fops;

static int dahdi_specchan_open(struct file *file)
{
	int res = 0;
	struct dahdi_chan *const chan = chan_from_file(file);

	if (chan && chan->sig) {
		/* Make sure we're not already open, a net device, or a slave device */
		if (dahdi_have_netdev(chan))
			res = -EBUSY;
		else if (chan->master != chan)
			res = -EBUSY;
		else if ((chan->sig & __DAHDI_SIG_DACS) == __DAHDI_SIG_DACS)
			res = -EBUSY;
		else if (!test_and_set_bit(DAHDI_FLAGBIT_OPEN, &chan->flags)) {
			unsigned long flags;
			res = initialize_channel(chan);
			if (res) {
				/* Reallocbufs must have failed */
				clear_bit(DAHDI_FLAGBIT_OPEN, &chan->flags);
				return res;
			}
			spin_lock_irqsave(&chan->lock, flags);
			if (is_pseudo_chan(chan))
				chan->flags |= DAHDI_FLAG_AUDIO;
			if (chan->span) {
				const struct dahdi_span_ops *const ops =
								chan->span->ops;
				if (!try_module_get(ops->owner)) {
					res = -ENXIO;
				} else if (ops->open) {
					res = ops->open(chan);
					if (res)
						module_put(ops->owner);
				}
			}
			if (!res) {
				chan->file = file;
				file->private_data = chan;
				/* Since we know we're a channel now, we can
				 * update the f_op pointer and bypass a few of
				 * the checks on the minor number. */
				file->f_op = &dahdi_chan_fops;
				spin_unlock_irqrestore(&chan->lock, flags);
			} else {
				spin_unlock_irqrestore(&chan->lock, flags);
				close_channel(chan);
				clear_bit(DAHDI_FLAGBIT_OPEN, &chan->flags);
			}
		} else {
			res = -EBUSY;
		}
	} else
		res = -ENXIO;
	return res;
}

static int dahdi_specchan_release(struct file *file)
{
	int res=0;
	unsigned long flags;
	struct dahdi_chan *chan = chan_from_file(file);

	if (chan) {
		/* Chan lock protects contents against potentially non atomic accesses.
		 * So if the pointer setting is not atomic, we should protect */
#ifdef CONFIG_DAHDI_MIRROR
		if (chan->srcmirror) {
			struct dahdi_chan *const srcmirror = chan->srcmirror;
			spin_lock_irqsave(&srcmirror->lock, flags);
			if (chan == srcmirror->txmirror) {
				module_printk(KERN_INFO, "Chan %d tx mirror " \
					      "to %d stopped\n",
					      srcmirror->txmirror->channo,
					      srcmirror->channo);
				srcmirror->txmirror = NULL;
			}

			if (chan == srcmirror->rxmirror) {
				module_printk(KERN_INFO, "Chan %d rx mirror " \
					      "to %d stopped\n",
					      srcmirror->rxmirror->channo,
					      srcmirror->channo);
				chan->srcmirror->rxmirror = NULL;
			}
			spin_unlock_irqrestore(&chan->srcmirror->lock, flags);
		}
#endif /* CONFIG_DAHDI_MIRROR */

		spin_lock_irqsave(&chan->lock, flags);
		chan->file = NULL;
		file->private_data = NULL;
#ifdef CONFIG_DAHDI_MIRROR
		chan->srcmirror = NULL;
#endif /* CONFIG_DAHDI_MIRROR */

		spin_unlock_irqrestore(&chan->lock, flags);
		close_channel(chan);
		clear_bit(DAHDI_FLAGBIT_OPEN, &chan->flags);
		if (chan->span) {
			struct module *owner = chan->span->ops->owner;

			if (chan->span->ops->close)
				res = chan->span->ops->close(chan);
			module_put(owner);
		}
	} else
		res = -ENXIO;
	return res;
}

static int can_open_timer(void)
{
#ifdef CONFIG_DAHDI_CORE_TIMER
	return 1;
#else
	return (list_empty(&span_list)) ? 0 : 1;
#endif
}

static unsigned int max_pseudo_channels = 512;
static unsigned int num_pseudo_channels;

/**
 * dahdi_alloc_pseudo() - Returns a new pseudo channel.
 *
 * Call with the registration_mutex held since this function will determine a
 * channel number, and must be protected from additional registrations while
 * that is happening.
 *
 */
static struct dahdi_chan *dahdi_alloc_pseudo(struct file *file)
{
	struct pseudo_chan *pseudo;
	unsigned long flags;
	unsigned int channo;
	struct pseudo_chan *p;
	struct list_head *pos = &pseudo_chans;

	/* Don't allow /dev/dahdi/pseudo to open if there is not a timing
	 * source. */
	if (!can_open_timer())
		return NULL;

	if (unlikely(num_pseudo_channels >= max_pseudo_channels))
		return NULL;

	pseudo = kzalloc(sizeof(*pseudo), GFP_KERNEL);
	if (NULL == pseudo)
		return NULL;

	pseudo->chan.sig = DAHDI_SIG_CLEAR;
	pseudo->chan.sigcap = DAHDI_SIG_CLEAR;
	pseudo->chan.flags = DAHDI_FLAG_AUDIO;
	pseudo->chan.span = NULL; /* No span == psuedo channel */

	mutex_lock(&registration_mutex);

	channo = FIRST_PSEUDO_CHANNEL;
	list_for_each_entry(p, &pseudo_chans, node) {
		if (channo != p->chan.channo)
			break;
		pos = &p->node;
		++channo;
	}

	pseudo->chan.channo = channo;
	pseudo->chan.chanpos = channo - FIRST_PSEUDO_CHANNEL + 1;
	__dahdi_init_chan(&pseudo->chan);
	dahdi_chan_reg(&pseudo->chan);

	snprintf(pseudo->chan.name, sizeof(pseudo->chan.name)-1,
		 "Pseudo/%d", pseudo->chan.chanpos);

	file->private_data = &pseudo->chan;

	/* Once we place the pseudo chan on the list...it's registered and
	 * live. */
	spin_lock_irqsave(&chan_lock, flags);
	++num_pseudo_channels;
	list_add(&pseudo->node, pos);
	spin_unlock_irqrestore(&chan_lock, flags);

	return &pseudo->chan;
}

static void dahdi_free_pseudo(struct dahdi_chan *chan)
{
	struct pseudo_chan *pseudo;
	unsigned long flags;

	if (!chan)
		return;

	pseudo = chan_to_pseudo(chan);

	spin_lock_irqsave(&chan_lock, flags);
	list_del(&pseudo->node);
	--num_pseudo_channels;
	spin_unlock_irqrestore(&chan_lock, flags);

	dahdi_chan_unreg(chan);
	kfree(pseudo);
}

static int dahdi_open(struct inode *inode, struct file *file)
{
	int unit = UNIT(file);
	struct dahdi_chan *chan;
	/* Minor 0: Special "control" descriptor */
	if (unit == DAHDI_CTL)
		return dahdi_ctl_open(file);
	if (unit == DAHDI_TRANSCODE) {
		if (!dahdi_transcode_fops) {
			if (request_module("dahdi_transcode")) {
				return -ENXIO;
			}
		}
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
		__MOD_INC_USE_COUNT (dahdi_transcode_fops->owner);
#else
		if (!try_module_get(dahdi_transcode_fops->owner)) {
			return -ENXIO;
		}
#endif
		if (dahdi_transcode_fops && dahdi_transcode_fops->open) {
			return dahdi_transcode_fops->open(inode, file);
		} else {
			/* dahdi_transcode module should have exported a
			 * file_operations table. */
			 WARN_ON(1);
		}
		return -ENXIO;
	}
	if (unit == DAHDI_TIMER) {
		if (can_open_timer()) {
			return dahdi_timing_open(file);
		} else {
			return -ENXIO;
		}
	}
	if (unit == DAHDI_CHANNEL)
		return dahdi_chan_open(file);
	if (unit == DAHDI_PSEUDO) {
		mutex_lock(&registration_mutex);
		chan = dahdi_alloc_pseudo(file);
		mutex_unlock(&registration_mutex);
		if (unlikely(!chan))
			return -ENOMEM;
		return dahdi_specchan_open(file);
	}
	return dahdi_specchan_open(file);
}

/**
 * dahdi_ioctl_defaultzone() - Set defzone to the default.
 * @defzone:	The number of the default zone.
 *
 * The default zone is the zone that will be used if the channels request the
 * default zone in dahdi_ioctl_chanconfig.  The first entry on the tone_zones
 * list is the default zone.  This function searches the list for the zone,
 * and if found, moves it to the head of the list.
 */
static int dahdi_ioctl_defaultzone(unsigned long data)
{
	int defzone;
	struct dahdi_zone *cur;
	struct dahdi_zone *dz = NULL;

	if (get_user(defzone, (int __user *)data))
		return -EFAULT;

	spin_lock(&zone_lock);
	list_for_each_entry(cur, &tone_zones, node) {
		if (cur->num != defzone)
			continue;
		dz = cur;
		break;
	}
	if (dz)
		list_move(&dz->node, &tone_zones);
	spin_unlock(&zone_lock);

	return (dz) ? 0 : -EINVAL;
}

/* No bigger than 32k for everything per tone zone */
#define MAX_SIZE 32768
/* No more than 128 subtones */
#define MAX_TONES 128

/* The tones to be loaded can (will) be a mix of regular tones,
   DTMF tones and MF tones. We need to load DTMF and MF tones
   a bit differently than regular tones because their storage
   format is much simpler (an array structure field of the zone
   structure, rather an array of pointers).
*/
static int dahdi_ioctl_loadzone(unsigned long data)
{
	struct load_zone_workarea {
		struct dahdi_tone *samples[MAX_TONES];
		short next[MAX_TONES];
		struct dahdi_tone_def_header th;
		struct dahdi_tone_def td;
	} *work;

	size_t space;
	size_t size;
	int res;
	int x;
	void *ptr;
	struct dahdi_zone *z = NULL;
	struct dahdi_tone *t = NULL;
	void __user * user_data = (void __user *)data;
	const unsigned char MAX_ZONE = -1;

	work = kzalloc(sizeof(*work), GFP_KERNEL);
	if (!work)
		return -ENOMEM;

	if (copy_from_user(&work->th, user_data, sizeof(work->th))) {
		res = -EFAULT;
		goto error_exit;
	}

	if ((work->th.zone < 0) || (work->th.zone > MAX_ZONE)) {
		res = -EINVAL;
		goto error_exit;
	}

	user_data += sizeof(work->th);

	if ((work->th.count < 0) || (work->th.count > MAX_TONES)) {
		module_printk(KERN_NOTICE, "Too many tones included\n");
		res = -EINVAL;
		goto error_exit;
	}

	space = size = sizeof(*z) + work->th.count * sizeof(*t);

	if (size > MAX_SIZE) {
		res = -E2BIG;
		goto error_exit;
	}

	z = ptr = kzalloc(size, GFP_KERNEL);
	if (!z) {
		res = -ENOMEM;
		goto error_exit;
	}

	ptr = (char *) ptr + sizeof(*z);
	space -= sizeof(*z);

	z->name = kasprintf(GFP_KERNEL, work->th.name);
	if (!z->name) {
		res = -ENOMEM;
		goto error_exit;
	}

	for (x = 0; x < DAHDI_MAX_CADENCE; x++)
		z->ringcadence[x] = work->th.ringcadence[x];

	mutex_lock(&global_dialparamslock);
	for (x = 0; x < work->th.count; x++) {
		enum {
			REGULAR_TONE,
			DTMF_TONE,
			MFR1_TONE,
			MFR2_FWD_TONE,
			MFR2_REV_TONE,
		} tone_type;

		if (space < sizeof(*t)) {
			module_printk(KERN_NOTICE, "Insufficient tone zone space\n");
			res = -EINVAL;
			goto unlock_error_exit;
		}

		res = copy_from_user(&work->td, user_data,
				     sizeof(work->td));
		if (res) {
			res = -EFAULT;
			goto unlock_error_exit;
		}

		user_data += sizeof(work->td);

		if ((work->td.tone >= 0) && (work->td.tone < DAHDI_TONE_MAX)) {
			tone_type = REGULAR_TONE;

			t = work->samples[x] = ptr;

			space -= sizeof(*t);
			ptr = (char *) ptr + sizeof(*t);

			/* Remember which sample is work->next */
			work->next[x] = work->td.next;

			/* Make sure the "next" one is sane */
			if ((work->next[x] >= work->th.count) ||
			    (work->next[x] < 0)) {
				module_printk(KERN_NOTICE,
					      "Invalid 'next' pointer: %d\n",
					      work->next[x]);
				res = -EINVAL;
				goto unlock_error_exit;
			}
		} else if ((work->td.tone >= DAHDI_TONE_DTMF_BASE) &&
			   (work->td.tone <= DAHDI_TONE_DTMF_MAX)) {
			tone_type = DTMF_TONE;
			work->td.tone -= DAHDI_TONE_DTMF_BASE;
			t = &z->dtmf[work->td.tone];
		} else if ((work->td.tone >= DAHDI_TONE_MFR1_BASE) &&
			   (work->td.tone <= DAHDI_TONE_MFR1_MAX)) {
			tone_type = MFR1_TONE;
			work->td.tone -= DAHDI_TONE_MFR1_BASE;
			t = &z->mfr1[work->td.tone];
		} else if ((work->td.tone >= DAHDI_TONE_MFR2_FWD_BASE) &&
			   (work->td.tone <= DAHDI_TONE_MFR2_FWD_MAX)) {
			tone_type = MFR2_FWD_TONE;
			work->td.tone -= DAHDI_TONE_MFR2_FWD_BASE;
			t = &z->mfr2_fwd[work->td.tone];
		} else if ((work->td.tone >= DAHDI_TONE_MFR2_REV_BASE) &&
			   (work->td.tone <= DAHDI_TONE_MFR2_REV_MAX)) {
			tone_type = MFR2_REV_TONE;
			work->td.tone -= DAHDI_TONE_MFR2_REV_BASE;
			t = &z->mfr2_rev[work->td.tone];
		} else {
			module_printk(KERN_NOTICE,
				      "Invalid tone (%d) defined\n",
				      work->td.tone);
			res = -EINVAL;
			goto unlock_error_exit;
		}

		t->fac1 = work->td.fac1;
		t->init_v2_1 = work->td.init_v2_1;
		t->init_v3_1 = work->td.init_v3_1;
		t->fac2 = work->td.fac2;
		t->init_v2_2 = work->td.init_v2_2;
		t->init_v3_2 = work->td.init_v3_2;
		t->modulate = work->td.modulate;

		switch (tone_type) {
		case REGULAR_TONE:
			t->tonesamples = work->td.samples;
			if (!z->tones[work->td.tone])
				z->tones[work->td.tone] = t;
			break;
		case DTMF_TONE:
			t->tonesamples = global_dialparams.dtmf_tonelen;
			t->next = &dtmf_silence;
			z->dtmf_continuous[work->td.tone] = *t;
			z->dtmf_continuous[work->td.tone].next =
				&z->dtmf_continuous[work->td.tone];
			break;
		case MFR1_TONE:
			switch (work->td.tone + DAHDI_TONE_MFR1_BASE) {
			case DAHDI_TONE_MFR1_KP:
			case DAHDI_TONE_MFR1_ST:
			case DAHDI_TONE_MFR1_STP:
			case DAHDI_TONE_MFR1_ST2P:
			case DAHDI_TONE_MFR1_ST3P:
				/* signaling control tones are always 100ms */
				t->tonesamples = 100 * DAHDI_CHUNKSIZE;
				break;
			default:
				t->tonesamples = global_dialparams.mfv1_tonelen;
				break;
			}
			t->next = &mfr1_silence;
			break;
		case MFR2_FWD_TONE:
			t->tonesamples = global_dialparams.mfr2_tonelen;
			t->next = &dtmf_silence;
			z->mfr2_fwd_continuous[work->td.tone] = *t;
			z->mfr2_fwd_continuous[work->td.tone].next =
					&z->mfr2_fwd_continuous[work->td.tone];
			break;
		case MFR2_REV_TONE:
			t->tonesamples = global_dialparams.mfr2_tonelen;
			t->next = &dtmf_silence;
			z->mfr2_rev_continuous[work->td.tone] = *t;
			z->mfr2_rev_continuous[work->td.tone].next =
					&z->mfr2_rev_continuous[work->td.tone];
			break;
		}
	}
	mutex_unlock(&global_dialparamslock);

	for (x = 0; x < work->th.count; x++) {
		if (work->samples[x])
			work->samples[x]->next = work->samples[work->next[x]];
	}

	z->num = work->th.zone;

	/* After we call dahdi_register_tone_zone, the only safe way to free
	 * the zone is with a tone_zone_put call. */
	res = dahdi_register_tone_zone(z);
	if (res)
		tone_zone_put(z);

	kfree(work);
	return res;

unlock_error_exit:
	mutex_unlock(&global_dialparamslock);
error_exit:
	if (z)
		kfree(z->name);
	kfree(z);
	kfree(work);
	return res;
}

void dahdi_init_tone_state(struct dahdi_tone_state *ts, struct dahdi_tone *zt)
{
	ts->v1_1 = 0;
	ts->v2_1 = zt->init_v2_1;
	ts->v3_1 = zt->init_v3_1;
	ts->v1_2 = 0;
	ts->v2_2 = zt->init_v2_2;
	ts->v3_2 = zt->init_v3_2;
	ts->modulate = zt->modulate;
}

struct dahdi_tone *dahdi_mf_tone(const struct dahdi_chan *chan, char digit, int digitmode)
{
	unsigned int tone_index;

	if (!chan->curzone) {
		static int __warnonce = 1;
		if (__warnonce) {
			__warnonce = 0;
			/* The tonezones are loaded by dahdi_cfg based on /etc/dahdi/system.conf. */
			module_printk(KERN_WARNING, "Cannot get dtmf tone until tone zone is loaded.\n");
		}
		return NULL;
	}

	switch (digitmode) {
	case DIGIT_MODE_PULSE:
		/* We should only get here with a pulse digit if we need
		 * to "dial" 'W' (wait 0.5 second) 
		 */
		if (digit == 'W')
			return &tone_pause;

		return NULL;
	case DIGIT_MODE_DTMF:
		switch (digit) {
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			tone_index = DAHDI_TONE_DTMF_0 + (digit - '0');
			break;
		case '*':
			tone_index = DAHDI_TONE_DTMF_s;
			break;
		case '#':
			tone_index = DAHDI_TONE_DTMF_p;
			break;
		case 'A':
		case 'B':
		case 'C':
		case 'D':
			tone_index = DAHDI_TONE_DTMF_A + (digit - 'A');
		case 'W':
			return &tone_pause;
		default:
			return NULL;
		}
		return &chan->curzone->dtmf[tone_index - DAHDI_TONE_DTMF_BASE];
	case DIGIT_MODE_MFR1:
		switch (digit) {
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			tone_index = DAHDI_TONE_MFR1_0 + (digit - '0');
			break;
		case '*':
			tone_index = DAHDI_TONE_MFR1_KP;
			break;
		case '#':
			tone_index = DAHDI_TONE_MFR1_ST;
			break;
		case 'A':
			tone_index = DAHDI_TONE_MFR1_STP;
			break;
		case 'B':
			tone_index = DAHDI_TONE_MFR1_ST2P;
			break;
		case 'C':
			tone_index = DAHDI_TONE_MFR1_ST3P;
			break;
		case 'W':
			return &tone_pause;
		default:
			return NULL;
		}
		return &chan->curzone->mfr1[tone_index - DAHDI_TONE_MFR1_BASE];
	case DIGIT_MODE_MFR2_FWD:
		switch (digit) {
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			tone_index = DAHDI_TONE_MFR2_FWD_1 + (digit - '1');
			break;
		case 'A':
		case 'B':
		case 'C':
		case 'D':
		case 'E':
		case 'F':
			tone_index = DAHDI_TONE_MFR2_FWD_10 + (digit - 'A');
			break;
		case 'W':
			return &tone_pause;
		default:
			return NULL;
		}
		return &chan->curzone->mfr2_fwd[tone_index - DAHDI_TONE_MFR2_FWD_BASE];
	case DIGIT_MODE_MFR2_REV:
		switch (digit) {
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			tone_index = DAHDI_TONE_MFR2_REV_1 + (digit - '1');
			break;
		case 'A':
		case 'B':
		case 'C':
		case 'D':
		case 'E':
		case 'F':
			tone_index = DAHDI_TONE_MFR2_REV_10 + (digit - 'A');
			break;
		case 'W':
			return &tone_pause;
		default:
			return NULL;
		}
		return &chan->curzone->mfr2_rev[tone_index - DAHDI_TONE_MFR2_REV_BASE];
	default:
		return NULL;
	}
}

static void __do_dtmf(struct dahdi_chan *chan)
{
	char c;

	/* Called with chan->lock held */
	while ((c = chan->txdialbuf[0])) {
		memmove(chan->txdialbuf, chan->txdialbuf + 1, sizeof(chan->txdialbuf) - 1);
		switch (c) {
		case 'T':
			chan->digitmode = DIGIT_MODE_DTMF;
			chan->tonep = 0;
			break;
		case 'M':
			chan->digitmode = DIGIT_MODE_MFR1;
			chan->tonep = 0;
			break;
		case 'O':
			chan->digitmode = DIGIT_MODE_MFR2_FWD;
			chan->tonep = 0;
			break;
		case 'R':
			chan->digitmode = DIGIT_MODE_MFR2_REV;
			chan->tonep = 0;
			break;
		case 'P':
			chan->digitmode = DIGIT_MODE_PULSE;
			chan->tonep = 0;
			break;
		default:
			if ((c != 'W') && (chan->digitmode == DIGIT_MODE_PULSE)) {
				if ((c >= '0') && (c <= '9') && (chan->txhooksig == DAHDI_TXSIG_OFFHOOK)) {
					chan->pdialcount = (c == '0') ? 10 : c - '0';
					dahdi_rbs_sethook(chan, DAHDI_TXSIG_ONHOOK, DAHDI_TXSTATE_PULSEBREAK,
						       chan->pulsebreaktime);
					return;
				}
			} else {
				chan->curtone = dahdi_mf_tone(chan, c, chan->digitmode);
				chan->tonep = 0;
				if (chan->curtone) {
					dahdi_init_tone_state(&chan->ts, chan->curtone);
					return;
				}
			}
		}
	}

	/* Notify userspace process if there is nothing left */
	chan->dialing = 0;
	__qevent(chan, DAHDI_EVENT_DIALCOMPLETE);
}

static int dahdi_release(struct inode *inode, struct file *file)
{
	int unit = UNIT(file);
	int res;
	struct dahdi_chan *chan;

	if (unit == DAHDI_CTL)
		return dahdi_ctl_release(file);
	if (unit == DAHDI_TIMER) {
		return dahdi_timer_release(file);
	}
	if (unit == DAHDI_TRANSCODE) {
		/* We should not be here because the dahdi_transcode.ko module
		 * should have updated the file_operations for this file
		 * handle when the file was opened. */
		WARN_ON(1);
		return -EFAULT;
	}
	if (unit == DAHDI_CHANNEL) {
		chan = file->private_data;
		if (!chan)
			return dahdi_chan_release(file);
		else
			return dahdi_specchan_release(file);
	}
	if (unit == DAHDI_PSEUDO) {
		chan = file->private_data;
		if (chan) {
			res = dahdi_specchan_release(file);
			dahdi_free_pseudo(chan);
		} else {
			module_printk(KERN_NOTICE, "Pseudo release and no private data??\n");
			res = 0;
		}
		return res;
	}
	return dahdi_specchan_release(file);
}

/**
 * dahdi_alarm_channel() - notify userspace channel is (not) in alarm
 * @chan:	the DAHDI channel
 * @alarms:	alarm bits set
 *
 * Notify userspace about a change in alarm status of this channel.
 * 
 * Note that channel drivers should only use this function directly if
 * they have a single port per channel. Whole-span alarms should be sent
 * using dahdi_alarm_notify() .
 *
 * Does nothing if alarms on the channel have not changed. If they have,
 * triggers sending either DAHDI_EVENT_NOALARM (if they were cleared) or
 * DAHDI_EVENT_ALARM (otherwise).
 *
 * Currently it is only used by drivers of FXO ports to notify (with a
 * red alarm) they have no battery current.
 */
void dahdi_alarm_channel(struct dahdi_chan *chan, int alarms)
{
	unsigned long flags;

	spin_lock_irqsave(&chan->lock, flags);
	if (chan->chan_alarms != alarms) {
		chan->chan_alarms = alarms;
		dahdi_qevent_nolock(chan, alarms ? DAHDI_EVENT_ALARM : DAHDI_EVENT_NOALARM);
	}
	spin_unlock_irqrestore(&chan->lock, flags);
}

static inline bool is_analog_span(const struct dahdi_span *s)
{
	return (s->linecompat == 0);
}

static void __dahdi_find_master_span(void)
{
	struct dahdi_span *s;
	unsigned long flags;
	struct dahdi_span *old_master;

	spin_lock_irqsave(&chan_lock, flags);
	old_master = master;
	list_for_each_entry(s, &span_list, spans_node) {
		if (s->alarms)
			continue;
		if (!is_analog_span(s) &&
		    !test_bit(DAHDI_FLAGBIT_RUNNING, &s->flags))
			continue;
		if (!can_provide_timing(s))
			continue;
		if (master == s)
			continue;

		master = s;
		break;
	}
	spin_unlock_irqrestore(&chan_lock, flags);

	if ((debug & DEBUG_MAIN) && (old_master != master))
		module_printk(KERN_NOTICE, "Master changed to %s\n", s->name);
}

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20)
static void _dahdi_find_master_span(void *work)
{
	__dahdi_find_master_span();
}
static DECLARE_WORK(find_master_work, _dahdi_find_master_span, NULL);
#else
static void _dahdi_find_master_span(struct work_struct *work)
{
	__dahdi_find_master_span();
}
static DECLARE_WORK(find_master_work, _dahdi_find_master_span);
#endif

static void dahdi_find_master_span(void)
{
	schedule_work(&find_master_work);
}

void dahdi_alarm_notify(struct dahdi_span *span)
{
	int x;

	span->alarms &= ~DAHDI_ALARM_LOOPBACK;
	/* Determine maint status */
	if (span->maintstat || span->mainttimer)
		span->alarms |= DAHDI_ALARM_LOOPBACK;
	/* DON'T CHANGE THIS AGAIN. THIS WAS DONE FOR A REASON.
 	   The expression (a != b) does *NOT* do the same thing
	   as ((!a) != (!b)) */
	/* if change in general state */
	if ((!span->alarms) != (!span->lastalarms)) {
		span->lastalarms = span->alarms;
		for (x = 0; x < span->channels; x++)
			dahdi_alarm_channel(span->chans[x], span->alarms);

		/* If we're going into or out of alarm we should try to find a
		 * new master that may be a better fit. */
		dahdi_find_master_span();

		/* Report more detailed alarms */
		if (debug & DEBUG_MAIN) {
			if (span->alarms & DAHDI_ALARM_LOS) {
				module_printk(KERN_NOTICE,
					"Span %d: Loss of signal\n",
					span->spanno);
			}
			if (span->alarms & DAHDI_ALARM_LFA) {
				module_printk(KERN_NOTICE,
					"Span %d: Loss of Frame Alignment\n",
					span->spanno);
			}
			if (span->alarms & DAHDI_ALARM_LMFA) {
				module_printk(KERN_NOTICE,
					"Span %d: Loss of Multi-Frame "\
					"Alignment\n", span->spanno);
			}
		}
	}
}

static int
dahdi_timer_ioctl(struct file *file, unsigned int cmd,
		  unsigned long data, struct dahdi_timer *timer)
{
	int j;
	struct dahdi_timer_rate *rate, *c_rate;
	unsigned long flags;

	switch(cmd) {
	case DAHDI_TIMERCONFIG:
		get_user(j, (int __user *)data);
		if (j < 0)
			j = 0;

		mutex_lock(&dahdi_timer_mutex);
		if (timer->rate)
			_dahdi_remove_timer(timer);

		rate = NULL;
		list_for_each_entry(c_rate, &dahdi_timer_rates, node) {
			if (c_rate->rate_samples == j) {
				rate = c_rate;
				break;
			}
		}
		if (!rate) {
			/* If we didn't find a rate, we need to create a new
			 * one */
			rate = kzalloc(sizeof(*rate), GFP_KERNEL);
			if (!rate) {
				mutex_unlock(&dahdi_timer_mutex);
				return -ENOMEM;
			}
			init_waitqueue_head(&rate->sel);
			rate->rate_samples = rate->cur_samples = j;
			INIT_LIST_HEAD(&rate->timers);
			timer->rate = rate;
			list_add_tail(&timer->node, &rate->timers);
			spin_lock_irqsave(&dahdi_timer_lock, flags);
			list_add_tail(&rate->node, &dahdi_timer_rates);
			spin_unlock_irqrestore(&dahdi_timer_lock, flags);
		} else {
			/* Otherwise, just add this new timer to the existing
			 * rates. */
			timer->rate = rate;
			spin_lock_irqsave(&dahdi_timer_lock, flags);
			list_add_tail(&timer->node, &rate->timers);
			spin_unlock_irqrestore(&dahdi_timer_lock, flags);
		}
		mutex_unlock(&dahdi_timer_mutex);
		break;

	case DAHDI_TIMERACK:
		get_user(j, (int __user *)data);
		if ((j < 1) || (j > atomic_read(&timer->tripped)))
			j = atomic_read(&timer->tripped);
		atomic_sub(j, &timer->tripped);
		break;
	case DAHDI_GETEVENT:  /* Get event on queue */
		j = DAHDI_EVENT_NONE;
		  /* set up for no event */
		if (atomic_read(&timer->tripped))
			j = DAHDI_EVENT_TIMER_EXPIRED;
		if (atomic_read(&timer->ping))
			j = DAHDI_EVENT_TIMER_PING;
		put_user(j, (int __user *)data);
		break;
	case DAHDI_TIMERPING:
		atomic_set(&timer->ping, 1);
		if (timer->rate)
			wake_up_interruptible(&timer->rate->sel);
		break;
	case DAHDI_TIMERPONG:
		atomic_set(&timer->ping, 0);
		break;
	default:
		return -ENOTTY;
	}
	return 0;
}

static int dahdi_ioctl_getgains(struct file *file, unsigned long data)
{
	int res = 0;
	struct dahdi_gains *gain;
	int j;
	void __user * const user_data = (void __user *)data;
	struct dahdi_chan *chan;

	gain = kzalloc(sizeof(*gain), GFP_KERNEL);
	if (!gain)
		return -ENOMEM;

	if (copy_from_user(gain, user_data, sizeof(*gain))) {
		res = -EFAULT;
		goto cleanup;
	}
	chan = (!gain->chan) ? chan_from_file(file) :
			       chan_from_num(gain->chan);
	if (!chan) {
		res = -EINVAL;
		goto cleanup;
	}

	if (!(chan->flags & DAHDI_FLAG_AUDIO)) {
		res = -EINVAL;
		goto cleanup;
	}
	gain->chan = chan->channo;
	for (j = 0; j < 256; ++j)  {
		gain->txgain[j] = chan->txgain[j];
		gain->rxgain[j] = chan->rxgain[j];
	}
	if (copy_to_user(user_data, gain, sizeof(*gain))) {
		res = -EFAULT;
		goto cleanup;
	}
cleanup:

	kfree(gain);
	return res;
}

static int dahdi_ioctl_setgains(struct file *file, unsigned long data)
{
	int res = 0;
	struct dahdi_gains *gain;
	unsigned char *txgain, *rxgain;
	int j;
	unsigned long flags;
	const int GAIN_TABLE_SIZE = sizeof(defgain);
	void __user * const user_data = (void __user *)data;
	struct dahdi_chan *chan;

	gain = kzalloc(sizeof(*gain), GFP_KERNEL);
	if (!gain)
		return -ENOMEM;

	if (copy_from_user(gain, user_data, sizeof(*gain))) {
		res = -EFAULT;
		goto cleanup;
	}

	chan = (!gain->chan) ? chan_from_file(file) :
			       chan_from_num(gain->chan);
	if (!chan) {
		res = -EINVAL;
		goto cleanup;
	}
	if (!(chan->flags & DAHDI_FLAG_AUDIO)) {
		res = -EINVAL;
		goto cleanup;
	}

	rxgain = kzalloc(GAIN_TABLE_SIZE*2, GFP_KERNEL);
	if (!rxgain) {
		res = -ENOMEM;
		goto cleanup;
	}

	gain->chan = chan->channo;
	txgain = rxgain + GAIN_TABLE_SIZE;

	for (j = 0; j < GAIN_TABLE_SIZE; ++j) {
		rxgain[j] = gain->rxgain[j];
		txgain[j] = gain->txgain[j];
	}

	if (!memcmp(rxgain, defgain, GAIN_TABLE_SIZE) &&
	    !memcmp(txgain, defgain, GAIN_TABLE_SIZE)) {
		kfree(rxgain);
		spin_lock_irqsave(&chan->lock, flags);
		if (is_gain_allocated(chan))
			kfree(chan->rxgain);
		chan->rxgain = defgain;
		chan->txgain = defgain;
		spin_unlock_irqrestore(&chan->lock, flags);
	} else {
		/* This is a custom gain setting */
		spin_lock_irqsave(&chan->lock, flags);
		if (is_gain_allocated(chan))
			kfree(chan->rxgain);
		chan->rxgain = rxgain;
		chan->txgain = txgain;
		spin_unlock_irqrestore(&chan->lock, flags);
	}

	if (copy_to_user(user_data, gain, sizeof(*gain))) {
		res = -EFAULT;
		goto cleanup;
	}
cleanup:

	kfree(gain);
	return res;
}

static int dahdi_ioctl_chandiag(struct file *file, unsigned long data)
{
	unsigned long flags;
	int channo;
	/* there really is no need to initialize this structure because when it is used it has
	 * already been completely overwritten, but apparently the compiler cannot figure that
	 * out and warns about uninitialized usage... so initialize it.
	 */
	struct dahdi_echocan_state ec_state = { .ops = NULL, };
	struct dahdi_chan *chan;
	struct dahdi_chan *temp;

	/* get channel number from user */
	get_user(channo, (int __user *)data);

	chan = chan_from_num(channo);
	if (!chan)
		return -EINVAL;

	temp = kmalloc(sizeof(*chan), GFP_KERNEL);
	if (!temp)
		return -ENOMEM;

	spin_lock_irqsave(&chan->lock, flags);
	*temp = *chan;
	if (temp->ec_state)
		ec_state = *temp->ec_state;
	if (temp->curzone)
		tone_zone_get(temp->curzone);
	spin_unlock_irqrestore(&chan->lock, flags);

	module_printk(KERN_INFO, "Dump of DAHDI Channel %d (%s,%d,%d):\n\n",
		      channo, temp->name, temp->channo, temp->chanpos);
	module_printk(KERN_INFO, "flags: %x hex, writechunk: %p, readchunk: %p\n",
		      (unsigned int) temp->flags, temp->writechunk, temp->readchunk);
	module_printk(KERN_INFO, "rxgain: %p, txgain: %p, gainalloc: %d\n",
		      temp->rxgain, temp->txgain, is_gain_allocated(temp));
	module_printk(KERN_INFO, "span: %p, sig: %x hex, sigcap: %x hex\n",
		      temp->span, temp->sig, temp->sigcap);
	module_printk(KERN_INFO, "inreadbuf: %d, outreadbuf: %d, inwritebuf: %d, outwritebuf: %d\n",
		      temp->inreadbuf, temp->outreadbuf, temp->inwritebuf, temp->outwritebuf);
	module_printk(KERN_INFO, "blocksize: %d, numbufs: %d, txbufpolicy: %d, txbufpolicy: %d\n",
		      temp->blocksize, temp->numbufs, temp->txbufpolicy, temp->rxbufpolicy);
	module_printk(KERN_INFO, "txdisable: %d, rxdisable: %d, iomask: %d\n",
		      temp->txdisable, temp->rxdisable, temp->iomask);
	module_printk(KERN_INFO, "curzone: %p, tonezone: %d, curtone: %p, tonep: %d\n",
		      temp->curzone,
		      ((temp->curzone) ? temp->curzone->num : -1),
		      temp->curtone, temp->tonep);
	module_printk(KERN_INFO, "digitmode: %d, txdialbuf: %s, dialing: %d, aftdialtimer: %d, cadpos. %d\n",
		      temp->digitmode, temp->txdialbuf, temp->dialing,
		      temp->afterdialingtimer, temp->cadencepos);
	module_printk(KERN_INFO, "confna: %d, confn: %d, confmode: %d, confmute: %d\n",
		      temp->confna, temp->_confn, temp->confmode, temp->confmute);
	module_printk(KERN_INFO, "ec: %p, deflaw: %d, xlaw: %p\n",
		      temp->ec_state, temp->deflaw, temp->xlaw);
	if (temp->ec_state) {
		module_printk(KERN_INFO, "echostate: %02x, echotimer: %d, echolastupdate: %d\n",
			      ec_state.status.mode, ec_state.status.pretrain_timer, ec_state.status.last_train_tap);
	}
	module_printk(KERN_INFO, "itimer: %d, otimer: %d, ringdebtimer: %d\n\n",
		      temp->itimer, temp->otimer, temp->ringdebtimer);

	if (temp->curzone)
		tone_zone_put(temp->curzone);
	kfree(temp);
	return 0;
}

/**
 * dahdi_ioctl_getparams() - Get channel parameters.
 *
 */
static int dahdi_ioctl_getparams(struct file *file, unsigned long data)
{
	size_t size_to_copy;
	struct dahdi_params param;
	bool return_master = false;
	struct dahdi_chan *chan;
	int j;
	size_to_copy = sizeof(struct dahdi_params);
	if (copy_from_user(&param, (void __user *)data, size_to_copy))
		return -EFAULT;

	/* check to see if the caller wants to receive our master channel
	 * number */
	if (param.channo & DAHDI_GET_PARAMS_RETURN_MASTER) {
		return_master = true;
		param.channo &= ~DAHDI_GET_PARAMS_RETURN_MASTER;
	}

	/* Pick the right channo's */
	chan = chan_from_file(file);
	if (!chan)
		chan = chan_from_num(param.channo);

	if (!chan)
		return -EINVAL;

	/* point to relevant structure */
	param.sigtype = chan->sig;  /* get signalling type */
	/* return non-zero if rx not in idle state */
	if (chan->span) {
		j = dahdi_q_sig(chan);
		if (j >= 0) { /* if returned with success */
			param.rxisoffhook = ((chan->rxsig & (j >> 8)) !=
							(j & 0xff));
		} else {
			const int sig = chan->rxhooksig;
			param.rxisoffhook = ((sig != DAHDI_RXSIG_ONHOOK) &&
				(sig != DAHDI_RXSIG_INITIAL));
		}
	} else if ((chan->txstate == DAHDI_TXSTATE_KEWL) ||
		   (chan->txstate == DAHDI_TXSTATE_AFTERKEWL)) {
		param.rxisoffhook = 1;
	} else {
		param.rxisoffhook = 0;
	}

	if (chan->span &&
	    chan->span->ops->rbsbits && !(chan->sig & DAHDI_SIG_CLEAR)) {
		param.rxbits = chan->rxsig;
		param.txbits = chan->txsig;
		param.idlebits = chan->idlebits;
	} else {
		param.rxbits = -1;
		param.txbits = -1;
		param.idlebits = 0;
	}
	if (chan->span &&
	    (chan->span->ops->rbsbits || chan->span->ops->hooksig) &&
	    !(chan->sig & DAHDI_SIG_CLEAR)) {
		param.rxhooksig = chan->rxhooksig;
		param.txhooksig = chan->txhooksig;
	} else {
		param.rxhooksig = -1;
		param.txhooksig = -1;
	}
	param.prewinktime = chan->prewinktime;
	param.preflashtime = chan->preflashtime;
	param.winktime = chan->winktime;
	param.flashtime = chan->flashtime;
	param.starttime = chan->starttime;
	param.rxwinktime = chan->rxwinktime;
	param.rxflashtime = chan->rxflashtime;
	param.debouncetime = chan->debouncetime;
	param.channo = chan->channo;
	param.chan_alarms = chan->chan_alarms;

	/* if requested, put the master channel number in the top 16 bits of
	 * the result */
	if (return_master)
		param.channo |= chan->master->channo << 16;

	param.pulsemaketime = chan->pulsemaketime;
	param.pulsebreaktime = chan->pulsebreaktime;
	param.pulseaftertime = chan->pulseaftertime;
	param.spanno = (chan->span) ? chan->span->spanno : 0;
	strlcpy(param.name, chan->name, sizeof(param.name));
	param.chanpos = chan->chanpos;
	param.sigcap = chan->sigcap;
	/* Return current law */
	if (chan->xlaw == __dahdi_alaw)
		param.curlaw = DAHDI_LAW_ALAW;
	else
		param.curlaw = DAHDI_LAW_MULAW;

	if (copy_to_user((void __user *)data, &param, size_to_copy))
		return -EFAULT;

	return 0;
}

/**
 * dahdi_ioctl_setparams() - Set channel parameters.
 *
 */
static int dahdi_ioctl_setparams(struct file *file, unsigned long data)
{
	struct dahdi_params param;
	struct dahdi_chan *chan;

	if (copy_from_user(&param, (void __user *)data, sizeof(param)))
		return -EFAULT;

	param.chan_alarms = 0; /* be explicit about the above */

	/* Pick the right channo's */
	chan = chan_from_file(file);
	if (!chan)
		chan = chan_from_num(param.channo);

	if (!chan)
		return -EINVAL;

	/* point to relevant structure */
	/* NOTE: sigtype is *not* included in this */
	  /* get timing paramters */
	chan->prewinktime = param.prewinktime;
	chan->preflashtime = param.preflashtime;
	chan->winktime = param.winktime;
	chan->flashtime = param.flashtime;
	chan->starttime = param.starttime;
	/* Update ringtime if not using a tone zone */
	if (!chan->curzone)
		chan->ringcadence[0] = chan->starttime;
	chan->rxwinktime = param.rxwinktime;
	chan->rxflashtime = param.rxflashtime;
	chan->debouncetime = param.debouncetime;
	chan->pulsemaketime = param.pulsemaketime;
	chan->pulsebreaktime = param.pulsebreaktime;
	chan->pulseaftertime = param.pulseaftertime;
	return 0;
}

/**
 * dahdi_ioctl_spanstat() - Return statistics for a span.
 *
 */
static int dahdi_ioctl_spanstat(struct file *file, unsigned long data)
{
	int ret = 0;
	struct dahdi_spaninfo spaninfo;
	struct dahdi_span *s;
	int j;
	size_t size_to_copy;
	bool via_chan = false;

	size_to_copy = sizeof(struct dahdi_spaninfo);
	if (copy_from_user(&spaninfo, (void __user *)data, size_to_copy))
		return -EFAULT;
	if (!spaninfo.spanno) {
		struct dahdi_chan *const chan = chan_from_file(file);
		if (!chan)
			return -EINVAL;

		s = chan->span;
		via_chan = true;
	} else {
		s = span_find_and_get(spaninfo.spanno);
	}
	if (!s)
		return -EINVAL;

	spaninfo.spanno = s->spanno; /* put the span # in here */
	spaninfo.totalspans = span_count();
	strlcpy(spaninfo.desc, s->desc, sizeof(spaninfo.desc));
	strlcpy(spaninfo.name, s->name, sizeof(spaninfo.name));
	spaninfo.alarms = s->alarms;		/* get alarm status */
	spaninfo.rxlevel = s->rxlevel;	/* get rx level */
	spaninfo.txlevel = s->txlevel;	/* get tx level */

	spaninfo.bpvcount = s->count.bpv;
	spaninfo.crc4count = s->count.crc4;
	spaninfo.ebitcount = s->count.ebit;
	spaninfo.fascount = s->count.fas;
	spaninfo.fecount = s->count.fe;
	spaninfo.cvcount = s->count.cv;
	spaninfo.becount = s->count.be;
	spaninfo.prbs = s->count.prbs;
	spaninfo.errsec = s->count.errsec;

	spaninfo.irqmisses = s->parent->irqmisses;	/* get IRQ miss count */
	spaninfo.syncsrc = s->syncsrc;	/* get active sync source */
	spaninfo.totalchans = s->channels;
	spaninfo.numchans = 0;
	for (j = 0; j < s->channels; j++) {
		if (s->chans[j]->sig)
			spaninfo.numchans++;
	}
	spaninfo.lbo = s->lbo;
	spaninfo.lineconfig = s->lineconfig;
	spaninfo.irq = 0;
	spaninfo.linecompat = s->linecompat;
	strlcpy(spaninfo.lboname, dahdi_lboname(s->lbo),
			  sizeof(spaninfo.lboname));
	if (s->parent->manufacturer) {
		strlcpy(spaninfo.manufacturer, s->parent->manufacturer,
			sizeof(spaninfo.manufacturer));
	}
	if (s->parent->devicetype) {
		strlcpy(spaninfo.devicetype, s->parent->devicetype,
			sizeof(spaninfo.devicetype));
	}
	if (s->parent->location) {
		strlcpy(spaninfo.location, s->parent->location,
			sizeof(spaninfo.location));
	}
	if (s->spantype) {
		strlcpy(spaninfo.spantype, s->spantype,
				  sizeof(spaninfo.spantype));
	}

	if (copy_to_user((void __user *)data, &spaninfo, size_to_copy))
		ret = -EFAULT;

	if (!via_chan)
		put_span(s);

	return ret;
}

/**
 * dahdi_ioctl_spanstat_v1() - Return statistics for a span in a legacy format.
 *
 */
static int dahdi_ioctl_spanstat_v1(struct file *file, unsigned long data)
{
	int ret = 0;
	struct dahdi_spaninfo_v1 spaninfo_v1;
	struct dahdi_span *s;
	int j;
	bool via_chan = false;

	if (copy_from_user(&spaninfo_v1, (void __user *)data,
			   sizeof(spaninfo_v1))) {
		return -EFAULT;
	}

	if (!spaninfo_v1.spanno) {
		struct dahdi_chan *const chan = chan_from_file(file);
		if (!chan)
			return -EINVAL;

		s = chan->span;
		via_chan = true;
	} else {
		s = span_find_and_get(spaninfo_v1.spanno);
	}

	if (!s)
		return -EINVAL;

	spaninfo_v1.spanno = s->spanno; /* put the span # in here */
	spaninfo_v1.totalspans = 0;
	spaninfo_v1.totalspans = span_count();
	strlcpy(spaninfo_v1.desc,
			  s->desc,
			  sizeof(spaninfo_v1.desc));
	strlcpy(spaninfo_v1.name,
			  s->name,
			  sizeof(spaninfo_v1.name));
	spaninfo_v1.alarms = s->alarms;
	spaninfo_v1.bpvcount = s->count.bpv;
	spaninfo_v1.rxlevel = s->rxlevel;
	spaninfo_v1.txlevel = s->txlevel;
	spaninfo_v1.crc4count = s->count.crc4;
	spaninfo_v1.ebitcount = s->count.ebit;
	spaninfo_v1.fascount = s->count.fas;
	spaninfo_v1.irqmisses = s->parent->irqmisses;
	spaninfo_v1.syncsrc = s->syncsrc;
	spaninfo_v1.totalchans = s->channels;
	spaninfo_v1.numchans = 0;
	for (j = 0; j < s->channels; j++) {
		if (s->chans[j]->sig)
			spaninfo_v1.numchans++;
	}
	spaninfo_v1.lbo = s->lbo;
	spaninfo_v1.lineconfig = s->lineconfig;
	spaninfo_v1.irq = 0;
	spaninfo_v1.linecompat = s->linecompat;
	strlcpy(spaninfo_v1.lboname,
			  dahdi_lboname(s->lbo),
			  sizeof(spaninfo_v1.lboname));

	if (s->parent->manufacturer) {
		strlcpy(spaninfo_v1.manufacturer, s->parent->manufacturer,
			sizeof(spaninfo_v1.manufacturer));
	}

	if (s->parent->devicetype) {
		strlcpy(spaninfo_v1.devicetype, s->parent->devicetype,
			sizeof(spaninfo_v1.devicetype));
	}

	strlcpy(spaninfo_v1.location, s->parent->location,
		sizeof(spaninfo_v1.location));

	if (s->spantype) {
		strlcpy(spaninfo_v1.spantype,
				  s->spantype,
				  sizeof(spaninfo_v1.spantype));
	}

	if (copy_to_user((void __user *)data, &spaninfo_v1,
			 sizeof(spaninfo_v1))) {
		ret = -EFAULT;
	}
	if (!via_chan)
		put_span(s);
	return ret;
}

static int dahdi_common_ioctl(struct file *file, unsigned int cmd,
			      unsigned long data)
{
	switch (cmd) {
		/* get channel parameters */
	case DAHDI_GET_PARAMS_V1: /* Intentional drop through. */
	case DAHDI_GET_PARAMS:
		return dahdi_ioctl_getparams(file, data);

	case DAHDI_SET_PARAMS:
		return dahdi_ioctl_setparams(file, data);

	case DAHDI_GETGAINS_V1: /* Intentional drop through. */
	case DAHDI_GETGAINS:  /* get gain stuff */
		return dahdi_ioctl_getgains(file, data);

	case DAHDI_SETGAINS:  /* set gain stuff */
		return dahdi_ioctl_setgains(file, data);

	case DAHDI_SPANSTAT:
		return dahdi_ioctl_spanstat(file, data);

	case DAHDI_SPANSTAT_V1:
		return dahdi_ioctl_spanstat_v1(file, data);

	case DAHDI_CHANDIAG_V1: /* Intentional drop through. */
	case DAHDI_CHANDIAG:
		return dahdi_ioctl_chandiag(file, data);
	default:
		return -ENOTTY;
	}
	return 0;
}

static int (*dahdi_dynamic_ioctl)(unsigned int cmd, unsigned long data);

void dahdi_set_dynamic_ioctl(int (*func)(unsigned int cmd, unsigned long data))
{
	dahdi_dynamic_ioctl = func;
}

static int (*dahdi_hpec_ioctl)(unsigned int cmd, unsigned long data);

void dahdi_set_hpec_ioctl(int (*func)(unsigned int cmd, unsigned long data))
{
	dahdi_hpec_ioctl = func;
}

static void recalc_slaves(struct dahdi_chan *chan)
{
	int x;
	struct dahdi_chan *last = chan;

	/* Makes no sense if you don't have a span */
	if (!chan->span)
		return;

#ifdef CONFIG_DAHDI_DEBUG
	module_printk(KERN_NOTICE, "Recalculating slaves on %s\n", chan->name);
#endif

	/* Link all slaves appropriately */
	for (x=chan->chanpos;x<chan->span->channels;x++)
		if (chan->span->chans[x]->master == chan) {
#ifdef CONFIG_DAHDI_DEBUG
			module_printk(KERN_NOTICE, "Channel %s, slave to %s, last is %s, its next will be %d\n",
				      chan->span->chans[x]->name, chan->name, last->name, x);
#endif
			last->nextslave = chan->span->chans[x];
			last = last->nextslave;
		}
	/* Terminate list */
	last->nextslave = NULL;
#ifdef CONFIG_DAHDI_DEBUG
	module_printk(KERN_NOTICE, "Done Recalculating slaves on %s (last is %s)\n", chan->name, last->name);
#endif
}

#if defined(CONFIG_DAHDI_NET) && defined(HAVE_NET_DEVICE_OPS)
static const struct net_device_ops dahdi_netdev_ops = {
	.ndo_open       = dahdi_net_open,
	.ndo_stop       = dahdi_net_stop,
	.ndo_do_ioctl   = dahdi_net_ioctl,
	.ndo_start_xmit = dahdi_xmit,
};
#endif

static int dahdi_ioctl_chanconfig(unsigned long data)
{
	int res = 0;
	int y;
	struct dahdi_chanconfig ch;
	struct dahdi_chan *newmaster;
	struct dahdi_chan *chan;
	struct dahdi_chan *dacs_chan = NULL;
	unsigned long flags;
	int sigcap;

	if (copy_from_user(&ch, (void __user *)data, sizeof(ch)))
		return -EFAULT;

	chan = chan_from_num(ch.chan);
	if (!chan)
		return -EINVAL;

	if (ch.sigtype == DAHDI_SIG_SLAVE) {
		newmaster = chan_from_num(ch.master);
		if (!newmaster)
			return -EINVAL;
		ch.sigtype = newmaster->sig;
	} else if ((ch.sigtype & __DAHDI_SIG_DACS) == __DAHDI_SIG_DACS) {
		newmaster = chan;
		dacs_chan = chan_from_num(ch.idlebits);
		if (!dacs_chan)
			return -EINVAL;
	} else {
		newmaster = chan;
	}
	spin_lock_irqsave(&chan->lock, flags);
#ifdef CONFIG_DAHDI_NET
	if (dahdi_have_netdev(chan)) {
		if (chan_to_netdev(chan)->flags & IFF_UP) {
			spin_unlock_irqrestore(&chan->lock, flags);
			module_printk(KERN_WARNING, "Can't switch HDLC net mode on channel %s, since current interface is up\n", chan->name);
			return -EBUSY;
		}
		spin_unlock_irqrestore(&chan->lock, flags);
		unregister_hdlc_device(chan->hdlcnetdev->netdev);
		spin_lock_irqsave(&chan->lock, flags);
		free_netdev(chan->hdlcnetdev->netdev);
		kfree(chan->hdlcnetdev);
		chan->hdlcnetdev = NULL;
		clear_bit(DAHDI_FLAGBIT_NETDEV, &chan->flags);
	}
#else
	if (ch.sigtype == DAHDI_SIG_HDLCNET) {
		spin_unlock_irqrestore(&chan->lock, flags);
		module_printk(KERN_WARNING, "DAHDI networking not supported by this build.\n");
		return -ENOSYS;
	}
#endif
	sigcap = chan->sigcap;
	/* If they support clear channel, then they support the HDLC and such through
	   us.  */
	if (sigcap & DAHDI_SIG_CLEAR)
		sigcap |= (DAHDI_SIG_HDLCRAW | DAHDI_SIG_HDLCFCS | DAHDI_SIG_HDLCNET | DAHDI_SIG_DACS);

	if ((sigcap & ch.sigtype) != ch.sigtype)
		res = -EINVAL;

	if (chan->master != chan) {
		struct dahdi_chan *oldmaster = chan->master;

		/* Clear the master channel */
		chan->master = chan;
		chan->nextslave = NULL;
		/* Unlink this channel from the master's channel list */
		recalc_slaves(oldmaster);
	}

	if (!res) {
		chan->sig = ch.sigtype;
		if (chan->sig == DAHDI_SIG_CAS)
			chan->idlebits = ch.idlebits;
		else
			chan->idlebits = 0;
		if ((ch.sigtype & DAHDI_SIG_CLEAR) == DAHDI_SIG_CLEAR) {
			/* Set clear channel flag if appropriate */
			chan->flags &= ~DAHDI_FLAG_AUDIO;
			chan->flags |= DAHDI_FLAG_CLEAR;
		} else {
			/* Set audio flag and not clear channel otherwise */
			chan->flags |= DAHDI_FLAG_AUDIO;
			chan->flags &= ~DAHDI_FLAG_CLEAR;
		}
		if ((ch.sigtype & DAHDI_SIG_HDLCRAW) == DAHDI_SIG_HDLCRAW) {
			/* Set the HDLC flag */
			chan->flags |= DAHDI_FLAG_HDLC;
		} else {
			/* Clear the HDLC flag */
			chan->flags &= ~DAHDI_FLAG_HDLC;
		}
		if ((ch.sigtype & DAHDI_SIG_HDLCFCS) == DAHDI_SIG_HDLCFCS) {
			/* Set FCS to be calculated if appropriate */
			chan->flags |= DAHDI_FLAG_FCS;
		} else {
			/* Clear FCS flag */
			chan->flags &= ~DAHDI_FLAG_FCS;
		}
		if ((ch.sigtype & __DAHDI_SIG_DACS) == __DAHDI_SIG_DACS) {
			if (unlikely(!dacs_chan)) {
				spin_unlock_irqrestore(&chan->lock, flags);
				return -EINVAL;
			}
			/* Setup conference properly */
			chan->confmode = DAHDI_CONF_DIGITALMON;
			chan->confna = ch.idlebits;
			chan->dacs_chan = dacs_chan;
			res = dahdi_chan_dacs(chan, dacs_chan);
		} else {
			dahdi_disable_dacs(chan);
		}
		chan->master = newmaster;
		/* Note new slave if we are not our own master */
		if (newmaster != chan) {
			recalc_slaves(chan->master);
		}
		if ((ch.sigtype & DAHDI_SIG_HARDHDLC) == DAHDI_SIG_HARDHDLC) {
			chan->flags &= ~DAHDI_FLAG_FCS;
			chan->flags &= ~DAHDI_FLAG_HDLC;
			chan->flags |= DAHDI_FLAG_NOSTDTXRX;
		} else {
			chan->flags &= ~DAHDI_FLAG_NOSTDTXRX;
		}

		if ((ch.sigtype & DAHDI_SIG_MTP2) == DAHDI_SIG_MTP2)
			chan->flags |= DAHDI_FLAG_MTP2;
		else
			chan->flags &= ~DAHDI_FLAG_MTP2;
	}

	if (!res && chan->span->ops->chanconfig)
		res = chan->span->ops->chanconfig(chan, ch.sigtype);

#ifdef CONFIG_DAHDI_NET
	if (!res &&
	    (newmaster == chan) &&
	    (chan->sig == DAHDI_SIG_HDLCNET)) {
		chan->hdlcnetdev = dahdi_hdlc_alloc();
		if (chan->hdlcnetdev) {
/*				struct hdlc_device *hdlc = chan->hdlcnetdev;
			struct net_device *d = hdlc_to_dev(hdlc); mmm...get it right later --byg */

			chan->hdlcnetdev->netdev = alloc_hdlcdev(chan->hdlcnetdev);
			if (chan->hdlcnetdev->netdev) {
				chan->hdlcnetdev->chan = chan;
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
				SET_MODULE_OWNER(chan->hdlcnetdev->netdev);
#endif
				chan->hdlcnetdev->netdev->irq = chan->span->irq;
				chan->hdlcnetdev->netdev->tx_queue_len = 50;
#ifdef HAVE_NET_DEVICE_OPS
				chan->hdlcnetdev->netdev->netdev_ops = &dahdi_netdev_ops;
#else
				chan->hdlcnetdev->netdev->do_ioctl = dahdi_net_ioctl;
				chan->hdlcnetdev->netdev->open = dahdi_net_open;
				chan->hdlcnetdev->netdev->stop = dahdi_net_stop;
#endif
				dev_to_hdlc(chan->hdlcnetdev->netdev)->attach = dahdi_net_attach;
				dev_to_hdlc(chan->hdlcnetdev->netdev)->xmit = dahdi_xmit;
				spin_unlock_irqrestore(&chan->lock, flags);
				/* Briefly restore interrupts while we register the device */
				res = dahdi_register_hdlc_device(chan->hdlcnetdev->netdev, ch.netdev_name);
				spin_lock_irqsave(&chan->lock, flags);
			} else {
				module_printk(KERN_NOTICE, "Unable to allocate hdlc: *shrug*\n");
				res = -1;
			}
			if (!res)
				set_bit(DAHDI_FLAGBIT_NETDEV, &chan->flags);
		} else {
			module_printk(KERN_NOTICE, "Unable to allocate netdev: out of memory\n");
			res = -1;
		}
	}
#endif
	if ((chan->sig == DAHDI_SIG_HDLCNET) &&
	    (chan == newmaster) &&
	    !dahdi_have_netdev(chan))
		module_printk(KERN_NOTICE, "Unable to register HDLC device for channel %s\n", chan->name);
	if (!res) {
		/* Setup default law */
		chan->deflaw = ch.deflaw;
		/* Copy back any modified settings */
		spin_unlock_irqrestore(&chan->lock, flags);
		if (copy_to_user((void __user *)data, &ch, sizeof(ch)))
			return -EFAULT;
		spin_lock_irqsave(&chan->lock, flags);
		/* And hangup */
		dahdi_hangup(chan);
		y = dahdi_q_sig(chan) & 0xff;
		if (y >= 0)
			chan->rxsig = (unsigned char) y;
		chan->rxhooksig = DAHDI_RXSIG_INITIAL;
	}
#ifdef CONFIG_DAHDI_DEBUG
	module_printk(KERN_NOTICE, "Configured channel %s, flags %04lx, sig %04x\n", chan->name, chan->flags, chan->sig);
#endif
	spin_unlock_irqrestore(&chan->lock, flags);

	return res;
}

/**
 * dahdi_ioctl_set_dialparms - Set the global dial parameters.
 * @data:	Pointer to user space that contains dahdi_dialparams.
 */
static int dahdi_ioctl_set_dialparams(unsigned long data)
{
	unsigned int i;
	struct dahdi_dialparams tdp;
	struct dahdi_zone *z;
	struct dahdi_dialparams *const gdp = &global_dialparams;

	if (copy_from_user(&tdp, (void __user *)data, sizeof(tdp)))
		return -EFAULT;

	mutex_lock(&global_dialparamslock);

	if ((tdp.dtmf_tonelen >= 10) && (tdp.dtmf_tonelen <= 4000))
		gdp->dtmf_tonelen = tdp.dtmf_tonelen;

	if ((tdp.mfv1_tonelen >= 10) && (tdp.mfv1_tonelen <= 4000))
		gdp->mfv1_tonelen = tdp.mfv1_tonelen;

	if ((tdp.mfr2_tonelen >= 10) && (tdp.mfr2_tonelen <= 4000))
		gdp->mfr2_tonelen = tdp.mfr2_tonelen;

	/* update the lengths in all currently loaded zones */
	spin_lock(&zone_lock);
	list_for_each_entry(z, &tone_zones, node) {

		for (i = 0; i < ARRAY_SIZE(z->dtmf); i++) {
			z->dtmf[i].tonesamples =
				gdp->dtmf_tonelen * DAHDI_CHUNKSIZE;
		}

		/* for MFR1, we only adjust the length of the digits */
		for (i = DAHDI_TONE_MFR1_0; i <= DAHDI_TONE_MFR1_9; i++) {
			z->mfr1[i - DAHDI_TONE_MFR1_BASE].tonesamples =
				gdp->mfv1_tonelen * DAHDI_CHUNKSIZE;
		}

		for (i = 0; i < ARRAY_SIZE(z->mfr2_fwd); i++) {
			z->mfr2_fwd[i].tonesamples =
				gdp->mfr2_tonelen * DAHDI_CHUNKSIZE;
		}

		for (i = 0; i < ARRAY_SIZE(z->mfr2_rev); i++) {
			z->mfr2_rev[i].tonesamples =
				gdp->mfr2_tonelen * DAHDI_CHUNKSIZE;
		}
	}
	spin_unlock(&zone_lock);

	dtmf_silence.tonesamples = gdp->dtmf_tonelen * DAHDI_CHUNKSIZE;
	mfr1_silence.tonesamples = gdp->mfv1_tonelen * DAHDI_CHUNKSIZE;
	mfr2_silence.tonesamples = gdp->mfr2_tonelen * DAHDI_CHUNKSIZE;

	mutex_unlock(&global_dialparamslock);

	return 0;
}

static int dahdi_ioctl_get_dialparams(unsigned long data)
{
	struct dahdi_dialparams tdp;

	mutex_lock(&global_dialparamslock);
	tdp = global_dialparams;
	mutex_unlock(&global_dialparamslock);
	if (copy_to_user((void __user *)data, &tdp, sizeof(tdp)))
		return -EFAULT;
	return 0;
}

static int dahdi_ioctl_indirect(struct file *file, unsigned long data)
{
	int res;
	struct dahdi_indirect_data ind;
	void *old;
	static bool warned;
	struct dahdi_chan *chan;

	if (copy_from_user(&ind, (void __user *)data, sizeof(ind)))
		return -EFAULT;

	chan = chan_from_num(ind.chan);
	if (!chan)
		return -EINVAL;

	if (!warned) {
		warned = true;
		module_printk(KERN_WARNING, "Using deprecated " \
			      "DAHDI_INDIRECT.  Please update " \
			      "dahdi-tools.\n");
	}

	/* Since dahdi_chan_ioctl expects to be called on file handles
	 * associated with channels, we'll temporarily set the
	 * private_data pointer on the ctl file handle just for this
	 * call. */
	old = file->private_data;
	file->private_data = chan;
	res = dahdi_chan_ioctl(file, ind.op, (unsigned long) ind.data);
	file->private_data = old;
	return res;
}

static int dahdi_ioctl_spanconfig(unsigned long data)
{
	int res = 0;
	struct dahdi_lineconfig lc;
	struct dahdi_span *s;

	if (copy_from_user(&lc, (void __user *)data, sizeof(lc)))
		return -EFAULT;
	s = span_find_and_get(lc.span);
	if (!s)
		return -ENXIO;

	if ((lc.lineconfig & 0x1ff0 & s->linecompat) !=
	    (lc.lineconfig & 0x1ff0)) {
		put_span(s);
		return -EINVAL;
	}
	if (s->ops->spanconfig) {
		s->lineconfig = lc.lineconfig;
		s->lbo = lc.lbo;
		s->txlevel = lc.lbo;
		s->rxlevel = 0;

		res = s->ops->spanconfig(s, &lc);
	}
	put_span(s);
	return res;
}

static int dahdi_ioctl_startup(unsigned long data)
{
	/* I/O CTL's for control interface */
	int j;
	int res = 0;
	int x, y;
	unsigned long flags;
	struct dahdi_span *s;

	if (get_user(j, (int __user *)data))
		return -EFAULT;
	s = span_find_and_get(j);
	if (!s)
		return -ENXIO;

	if (s->flags & DAHDI_FLAG_RUNNING) {
		put_span(s);
		return 0;
	}

	if (s->ops->startup)
		res = s->ops->startup(s);

	if (!res) {
		/* Mark as running and hangup any channels */
		s->flags |= DAHDI_FLAG_RUNNING;
		for (x = 0; x < s->channels; x++) {
			y = dahdi_q_sig(s->chans[x]) & 0xff;
			if (y >= 0)
				s->chans[x]->rxsig = (unsigned char)y;
			spin_lock_irqsave(&s->chans[x]->lock, flags);
			dahdi_hangup(s->chans[x]);
			spin_unlock_irqrestore(&s->chans[x]->lock, flags);
			/*
			 * Set the rxhooksig back to
			 * DAHDI_RXSIG_INITIAL so that new events are
			 * queued on the channel with the actual
			 * received hook state.
			 *
			 */
			s->chans[x]->rxhooksig = DAHDI_RXSIG_INITIAL;
		}
	}
	put_span(s);
	return 0;
}

static int dahdi_ioctl_shutdown(unsigned long data)
{
	/* I/O CTL's for control interface */
	int j;
	int res = 0;
	int x;
	struct dahdi_span *s;

	if (get_user(j, (int __user *)data))
		return -EFAULT;
	s = span_find_and_get(j);
	if (!s)
		return -ENXIO;

	/* Unconfigure channels */
	for (x = 0; x < s->channels; x++)
		s->chans[x]->sig = 0;

	if (s->ops->shutdown)
		res =  s->ops->shutdown(s);
	s->flags &= ~DAHDI_FLAG_RUNNING;
	put_span(s);
	return 0;
}

static int dahdi_ioctl_attach_echocan(unsigned long data)
{
	unsigned long flags;
	struct dahdi_chan *chan;
	struct dahdi_attach_echocan ae;
	const struct dahdi_echocan_factory *new = NULL, *old;

	if (copy_from_user(&ae, (void __user *)data, sizeof(ae)))
		return -EFAULT;

	chan = chan_from_num(ae.chan);
	if (!chan)
		return -EINVAL;

	ae.echocan[sizeof(ae.echocan) - 1] = 0;
	if (ae.echocan[0]) {
		new = find_echocan(ae.echocan);
		if (!new)
			return -EINVAL;
	}

	spin_lock_irqsave(&chan->lock, flags);
	old = chan->ec_factory;
	chan->ec_factory = new;
	spin_unlock_irqrestore(&chan->lock, flags);

	if (old)
		release_echocan(old);

	return 0;
}

static int dahdi_ioctl_sfconfig(unsigned long data)
{
	int res = 0;
	unsigned long flags;
	struct dahdi_chan *chan;
	struct dahdi_sfconfig sf;

	if (copy_from_user(&sf, (void __user *)data, sizeof(sf)))
		return -EFAULT;
	chan = chan_from_num(sf.chan);
	if (!chan)
		return -EINVAL;

	if (chan->sig != DAHDI_SIG_SF)
		return -EINVAL;

	spin_lock_irqsave(&chan->lock, flags);
	chan->rxp1 = sf.rxp1;
	chan->rxp2 = sf.rxp2;
	chan->rxp3 = sf.rxp3;
	chan->txtone = sf.txtone;
	chan->tx_v2 = sf.tx_v2;
	chan->tx_v3 = sf.tx_v3;
	chan->toneflags = sf.toneflag;
	if (sf.txtone) { /* if set to make tone for tx */
		if ((chan->txhooksig &&
		     !(sf.toneflag & DAHDI_REVERSE_TXTONE)) ||
		     ((!chan->txhooksig) &&
		       (sf.toneflag & DAHDI_REVERSE_TXTONE))) {
			set_txtone(chan, sf.txtone, sf.tx_v2, sf.tx_v3);
		} else {
			set_txtone(chan, 0, 0, 0);
		}
	}
	spin_unlock_irqrestore(&chan->lock, flags);
	return res;
}

static int dahdi_ioctl_get_version(unsigned long data)
{
	struct dahdi_versioninfo vi;
	struct ecfactory *cur;
	size_t space = sizeof(vi.echo_canceller) - 1;

	memset(&vi, 0, sizeof(vi));
	strlcpy(vi.version, dahdi_version, sizeof(vi.version));
	spin_lock(&ecfactory_list_lock);
	list_for_each_entry(cur, &ecfactory_list, list) {
		strncat(vi.echo_canceller + strlen(vi.echo_canceller),
			cur->ec->get_name(NULL), space);
		space -= strlen(cur->ec->get_name(NULL));
		if (space < 1)
			break;
		if (cur->list.next && (cur->list.next != &ecfactory_list)) {
			strncat(vi.echo_canceller + strlen(vi.echo_canceller),
				", ", space);
			space -= 2;
			if (space < 1)
				break;
		}
	}
	spin_unlock(&ecfactory_list_lock);
	if (copy_to_user((void __user *)data, &vi, sizeof(vi)))
		return -EFAULT;

	return 0;
}

static int dahdi_ioctl_maint(unsigned long data)
{
	int i;
	unsigned long flags;
	int rv;
	struct dahdi_span *s;
	struct dahdi_maintinfo maint;

	  /* get struct from user */
	if (copy_from_user(&maint, (void __user *)data, sizeof(maint)))
		return -EFAULT;
	s = span_find_and_get(maint.spanno);
	if (!s)
		return -EINVAL;
	if (!s->ops->maint) {
		put_span(s);
		return -ENOSYS;
	}
	spin_lock_irqsave(&s->lock, flags);
	  /* save current maint state */
	i = s->maintstat;
	  /* set maint mode */
	s->maintstat = maint.command;
	switch (maint.command) {
	case DAHDI_MAINT_NONE:
	case DAHDI_MAINT_LOCALLOOP:
	case DAHDI_MAINT_NETWORKLINELOOP:
	case DAHDI_MAINT_NETWORKPAYLOADLOOP:
		/* if same, ignore it */
		if (i == maint.command)
			break;
		rv = s->ops->maint(s, maint.command);
		spin_unlock_irqrestore(&s->lock, flags);
		if (rv) {
			put_span(s);
			return rv;
		}
		spin_lock_irqsave(&s->lock, flags);
		break;
	case DAHDI_MAINT_LOOPUP:
	case DAHDI_MAINT_LOOPDOWN:
		s->mainttimer = DAHDI_LOOPCODE_TIME * DAHDI_CHUNKSIZE;
		rv = s->ops->maint(s, maint.command);
		spin_unlock_irqrestore(&s->lock, flags);
		if (rv) {
			put_span(s);
			return rv;
		}
		spin_lock_irqsave(&s->lock, flags);
		break;
	case DAHDI_MAINT_FAS_DEFECT:
	case DAHDI_MAINT_MULTI_DEFECT:
	case DAHDI_MAINT_CRC_DEFECT:
	case DAHDI_MAINT_CAS_DEFECT:
	case DAHDI_MAINT_PRBS_DEFECT:
	case DAHDI_MAINT_BIPOLAR_DEFECT:
	case DAHDI_MAINT_PRBS:
	case DAHDI_RESET_COUNTERS:
	case DAHDI_MAINT_ALARM_SIM:
		/* Prevent notifying an alarm state for generic
		   maintenance functions, unless the driver is
		   already in a maint state */
		if (!i)
			s->maintstat = 0;

		rv = s->ops->maint(s, maint.command);
		spin_unlock_irqrestore(&s->lock, flags);
		if (rv) {
			put_span(s);
			return rv;
		}
		spin_lock_irqsave(&s->lock, flags);
		break;
	default:
		spin_unlock_irqrestore(&s->lock, flags);
		module_printk(KERN_NOTICE,
			      "Unknown maintenance event: %d\n",
			      maint.command);
		put_span(s);
		return -ENOSYS;
	}
	dahdi_alarm_notify(s);  /* process alarm-related events */
	spin_unlock_irqrestore(&s->lock, flags);
	put_span(s);

	return 0;
}

static int
dahdi_ctl_ioctl(struct file *file, unsigned int cmd, unsigned long data)
{
	switch (cmd) {
	case DAHDI_INDIRECT:
		return dahdi_ioctl_indirect(file, data);
	case DAHDI_SPANCONFIG:
		return dahdi_ioctl_spanconfig(data);
	case DAHDI_STARTUP:
		return dahdi_ioctl_startup(data);
	case DAHDI_SHUTDOWN:
		return dahdi_ioctl_shutdown(data);
	case DAHDI_ATTACH_ECHOCAN:
		return dahdi_ioctl_attach_echocan(data);
	case DAHDI_CHANCONFIG:
		return dahdi_ioctl_chanconfig(data);
	case DAHDI_SFCONFIG:
		return dahdi_ioctl_sfconfig(data);
	case DAHDI_DEFAULTZONE:
		return dahdi_ioctl_defaultzone(data);
	case DAHDI_LOADZONE:
		return dahdi_ioctl_loadzone(data);
	case DAHDI_FREEZONE:
		return dahdi_ioctl_freezone(data);
	case DAHDI_SET_DIALPARAMS:
		return dahdi_ioctl_set_dialparams(data);
	case DAHDI_GET_DIALPARAMS:
		return dahdi_ioctl_get_dialparams(data);
	case DAHDI_GETVERSION:
		return dahdi_ioctl_get_version(data);
	case DAHDI_MAINT:
		return dahdi_ioctl_maint(data);
	case DAHDI_DYNAMIC_CREATE:
	case DAHDI_DYNAMIC_DESTROY:
		if (dahdi_dynamic_ioctl) {
			return dahdi_dynamic_ioctl(cmd, data);
		} else {
			request_module("dahdi_dynamic");
			if (dahdi_dynamic_ioctl)
				return dahdi_dynamic_ioctl(cmd, data);
		}
		return -ENOSYS;
	case DAHDI_EC_LICENSE_CHALLENGE:
	case DAHDI_EC_LICENSE_RESPONSE:
		if (dahdi_hpec_ioctl) {
			return dahdi_hpec_ioctl(cmd, data);
		} else {
			request_module("dahdi_echocan_hpec");
			if (dahdi_hpec_ioctl)
				return dahdi_hpec_ioctl(cmd, data);
		}
		return -ENOSYS;
	}

	return dahdi_common_ioctl(file, cmd, data);
}

static int ioctl_dahdi_dial(struct dahdi_chan *chan, unsigned long data)
{
	struct dahdi_dialoperation *tdo;
	unsigned long flags;
	char *s;
	int rv;
	void __user * const user_data = (void __user *)data;

	tdo = kmalloc(sizeof(*tdo), GFP_KERNEL);

	if (!tdo)
		return -ENOMEM;

	if (copy_from_user(tdo, user_data, sizeof(*tdo)))
		return -EFAULT;
	rv = 0;
	/* Force proper NULL termination and uppercase entry */
	tdo->dialstr[DAHDI_MAX_DTMF_BUF - 1] = '\0';
	for (s = tdo->dialstr; *s; s++)
		*s = toupper(*s);
	spin_lock_irqsave(&chan->lock, flags);
	if (!chan->curzone) {
		spin_unlock_irqrestore(&chan->lock, flags);
		/* The tone zones are loaded by dahdi_cfg from /etc/dahdi/system.conf */
		module_printk(KERN_WARNING, "Cannot dial until a tone zone is loaded.\n");
		return -ENODATA;
	}
	switch (tdo->op) {
	case DAHDI_DIAL_OP_CANCEL:
		chan->curtone = NULL;
		chan->dialing = 0;
		chan->txdialbuf[0] = '\0';
		chan->tonep = 0;
		chan->pdialcount = 0;
		break;
	case DAHDI_DIAL_OP_REPLACE:
		strcpy(chan->txdialbuf, tdo->dialstr);
		chan->dialing = 1;
		__do_dtmf(chan);
		break;
	case DAHDI_DIAL_OP_APPEND:
		if (strlen(tdo->dialstr) + strlen(chan->txdialbuf) >= (DAHDI_MAX_DTMF_BUF - 1)) {
			rv = -EBUSY;
			break;
		}
		strlcpy(chan->txdialbuf + strlen(chan->txdialbuf), tdo->dialstr,
			DAHDI_MAX_DTMF_BUF - strlen(chan->txdialbuf));
		if (!chan->dialing) {
			chan->dialing = 1;
			__do_dtmf(chan);
		}
		break;
	default:
		rv = -EINVAL;
	}
	spin_unlock_irqrestore(&chan->lock, flags);
	return rv;
}

static int dahdi_ioctl_setconf(struct file *file, unsigned long data)
{
	struct dahdi_confinfo conf;
	struct dahdi_chan *chan;
	struct dahdi_chan *conf_chan = NULL;
	unsigned long flags;
	unsigned int confmode;
	int oldconf;

	if (copy_from_user(&conf, (void __user *)data, sizeof(conf)))
		return -EFAULT;

	confmode = conf.confmode & DAHDI_CONF_MODE_MASK;

	chan = (conf.chan) ? chan_from_num(conf.chan) :
			     chan_from_file(file);
	if (!chan)
		return -EINVAL;

	if (!(chan->flags & DAHDI_FLAG_AUDIO))
		return -EINVAL;

	if ((DAHDI_CONF_DIGITALMON == confmode) ||
	    is_monitor_mode(conf.confmode)) {
		conf_chan = chan_from_num(conf.confno);
		if (!conf_chan)
			return -EINVAL;
	} else {
		/* make sure conf number makes sense, too */
		if ((conf.confno < -1) || (conf.confno > DAHDI_MAX_CONF))
			return -EINVAL;
	}

	/* if taking off of any conf, must have 0 mode */
	if ((!conf.confno) && conf.confmode)
		return -EINVAL;
	/* likewise if 0 mode must have no conf */
	if ((!conf.confmode) && conf.confno)
		return -EINVAL;
	dahdi_check_conf(conf.confno);
	conf.chan = chan->channo;  /* return with real channel # */
	spin_lock_irqsave(&chan_lock, flags);
	spin_lock(&chan->lock);
	if (conf.confno == -1)
		conf.confno = dahdi_first_empty_conference();
	if ((conf.confno < 1) && (conf.confmode)) {
		/* No more empty conferences */
		spin_unlock(&chan->lock);
		spin_unlock_irqrestore(&chan_lock, flags);
		return -EBUSY;
	}
	  /* if changing confs, clear last added info */
	if (conf.confno != chan->confna) {
		memset(chan->conflast, 0, DAHDI_MAX_CHUNKSIZE);
		memset(chan->conflast1, 0, DAHDI_MAX_CHUNKSIZE);
		memset(chan->conflast2, 0, DAHDI_MAX_CHUNKSIZE);
	}
	oldconf = chan->confna;  /* save old conference number */
	chan->confna = conf.confno;   /* set conference number */
	chan->conf_chan = conf_chan;
	chan->confmode = conf.confmode;  /* set conference mode */
	chan->_confn = 0;		     /* Clear confn */
	if (chan->span && chan->span->ops->dacs) {
		if ((confmode == DAHDI_CONF_DIGITALMON) &&
		    (chan->txgain == defgain) &&
		    (chan->rxgain == defgain) &&
		    (conf_chan->txgain == defgain) &&
		    (conf_chan->rxgain == defgain)) {
			dahdi_chan_dacs(chan, conf_chan);
		} else {
			dahdi_disable_dacs(chan);
		}
	}
	/* if we are going onto a conf */
	if (conf.confno &&
	    (confmode == DAHDI_CONF_CONF ||
	     confmode == DAHDI_CONF_CONFANN ||
	     confmode == DAHDI_CONF_CONFMON ||
	     confmode == DAHDI_CONF_CONFANNMON ||
	     confmode == DAHDI_CONF_REALANDPSEUDO)) {
		/* Get alias */
		chan->_confn = dahdi_get_conf_alias(conf.confno);
	}

	if (conf_chan) {
		if ((confmode == DAHDI_CONF_MONITOR_RX_PREECHO) ||
		    (confmode == DAHDI_CONF_MONITOR_TX_PREECHO) ||
		    (confmode == DAHDI_CONF_MONITORBOTH_PREECHO)) {
			void *temp = kmalloc(sizeof(*chan->readchunkpreec) *
					     DAHDI_CHUNKSIZE, GFP_ATOMIC);
			conf_chan->readchunkpreec = temp;
		} else {
			kfree(conf_chan->readchunkpreec);
			conf_chan->readchunkpreec = NULL;
		}
	}

	spin_unlock(&chan->lock);
	spin_unlock_irqrestore(&chan_lock, flags);
	dahdi_check_conf(oldconf);
	if (copy_to_user((void __user *)data, &conf, sizeof(conf)))
		return -EFAULT;
	return 0;
}

/**
 * dahdi_ioctl_confdiag() - Output debug info about conferences to console.
 *
 * This is a pure debugging aide since the only result is to the console.
 *
 * TODO: Does anyone use this anymore?  Should it be hidden behind a debug
 * compile time option?
 */
static int dahdi_ioctl_confdiag(struct file *file, unsigned long data)
{
	struct dahdi_chan *chan;
	unsigned long flags;
	int rv;
	int i;
	int j;
	int c;

	chan = chan_from_file(file);
	if (!chan)
		return -EINVAL;

	if (!(chan->flags & DAHDI_FLAG_AUDIO))
		return -EINVAL;

	get_user(j, (int __user *)data);  /* get conf # */

	/* loop thru the interesting ones */
	for (i = ((j) ? j : 1); i <= ((j) ? j : DAHDI_MAX_CONF); i++) {
		struct dahdi_span *s;
		struct pseudo_chan *pseudo;
		c = 0;
		spin_lock_irqsave(&chan_lock, flags);
		list_for_each_entry(s, &span_list, spans_node) {
			int k;
			for (k = 0; k < s->channels; k++) {
				chan = s->chans[k];
				if (chan->confna != i)
					continue;
				if (!c)
					module_printk(KERN_NOTICE, "Conf #%d:\n", i);
				c = 1;
				module_printk(KERN_NOTICE, "chan %d, mode %x\n",
					      chan->channo, chan->confmode);
			}
		}
		list_for_each_entry(pseudo, &pseudo_chans, node) {
			/* skip if not in this conf */
			if (pseudo->chan.confna != i)
				continue;
			if (!c)
				module_printk(KERN_NOTICE, "Conf #%d:\n", i);
			c = 1;
			module_printk(KERN_NOTICE, "chan %d, mode %x\n",
				      pseudo->chan.channo, pseudo->chan.confmode);
		}
		spin_unlock_irqrestore(&chan_lock, flags);
		rv = 0;
		if (c)
			module_printk(KERN_NOTICE, "\n");
	}
	return 0;
}

static int dahdi_ioctl_getconf(struct file *file, unsigned long data)
{
	struct dahdi_confinfo conf;
	struct dahdi_chan *chan;

	if (copy_from_user(&conf, (void __user *)data, sizeof(conf)))
		return -EFAULT;

	chan = (!conf.chan) ? chan_from_file(file) :
			      chan_from_num(conf.chan);
	if (!chan)
		return -EINVAL;

	if (!(chan->flags & DAHDI_FLAG_AUDIO))
		return -EINVAL;
	conf.chan = chan->channo;  /* get channel number */
	conf.confno = chan->confna;  /* get conference number */
	conf.confmode = chan->confmode; /* get conference mode */
	if (copy_to_user((void __user *)data, &conf, sizeof(conf)))
		return -EFAULT;

	return 0;
}

/**
 * dahdi_ioctl_iomux() - Wait for *something* to happen.
 *
 * This is now basically like the wait_event_interruptible function, but with
 * a much more involved wait condition.
 */
static int dahdi_ioctl_iomux(struct file *file, unsigned long data)
{
	struct dahdi_chan *const chan = chan_from_file(file);
	unsigned long flags;
	unsigned int iomask;
	DEFINE_WAIT(wait);

	if (get_user(iomask, (int __user *)data))
		return -EFAULT;

	if (unlikely(!iomask || !chan))
		return -EINVAL;

	while (1) {
		unsigned int wait_result;

		wait_result = 0;
		prepare_to_wait(&chan->waitq, &wait, TASK_INTERRUPTIBLE);

		spin_lock_irqsave(&chan->lock, flags);
		chan->iomask = iomask;
		if (iomask & DAHDI_IOMUX_READ) {
			if ((chan->outreadbuf > -1)  && !chan->rxdisable)
				wait_result |= DAHDI_IOMUX_READ;
		}
		if (iomask & DAHDI_IOMUX_WRITE) {
			if (chan->inwritebuf > -1)
				wait_result |= DAHDI_IOMUX_WRITE;
		}
		if (iomask & DAHDI_IOMUX_WRITEEMPTY) {
			/* if everything empty -- be sure the transmitter is
			 * enabled */
			chan->txdisable = 0;
			if (chan->outwritebuf < 0)
				wait_result |= DAHDI_IOMUX_WRITEEMPTY;
		}
		if (iomask & DAHDI_IOMUX_SIGEVENT) {
			if (chan->eventinidx != chan->eventoutidx)
				wait_result |= DAHDI_IOMUX_SIGEVENT;
		}
		spin_unlock_irqrestore(&chan->lock, flags);

		if (wait_result || (iomask & DAHDI_IOMUX_NOWAIT)) {
			put_user(wait_result, (int __user *)data);
			break;
		}

		if (signal_pending(current)) {
			finish_wait(&chan->waitq, &wait);
			return -ERESTARTSYS;
		}

		schedule();
	}

	finish_wait(&chan->waitq, &wait);
	spin_lock_irqsave(&chan->lock, flags);
	chan->iomask = 0;
	spin_unlock_irqrestore(&chan->lock, flags);
	return 0;
}

#ifdef CONFIG_DAHDI_MIRROR
static int dahdi_ioctl_rxmirror(struct file *file, unsigned long data)
{
	int res;
	int i;
	unsigned long flags;
	struct dahdi_chan *const chan = chan_from_file(file);
	struct dahdi_chan *srcmirror;

	if (!chan || chan->srcmirror)
		return -ENODEV;

	res = get_user(i, (int __user *)data);
	if (res)
		return res;

	srcmirror = chan_from_num(i);
	if (!srcmirror)
		return -EINVAL;

	module_printk(KERN_INFO, "Chan %d rx mirrored to %d\n",
		      srcmirror->channo, chan->channo);

	spin_lock_irqsave(&srcmirror->lock, flags);
	if (srcmirror->rxmirror == NULL)
		srcmirror->rxmirror = chan;

	spin_unlock_irqrestore(&srcmirror->lock, flags);
	if (srcmirror->rxmirror != chan) {
		module_printk(KERN_INFO, "Chan %d cannot be rxmirrored, " \
			      "already in use\n", srcmirror->channo);
		return -EFAULT;
	}

	spin_lock_irqsave(&chan->lock, flags);
	chan->srcmirror = srcmirror;
	chan->flags = srcmirror->flags;
	chan->sig =  srcmirror->sig;
	clear_bit(DAHDI_FLAGBIT_OPEN, &chan->flags);
	spin_unlock_irqrestore(&chan->lock, flags);

	return 0;
}

static int dahdi_ioctl_txmirror(struct file *file, unsigned long data)
{
	int res;
	int i;
	unsigned long flags;
	struct dahdi_chan *const chan = chan_from_file(file);
	struct dahdi_chan *srcmirror;

	if (!chan || chan->srcmirror)
		return -ENODEV;

	res = get_user(i, (int __user *)data);
	if (res)
		return res;

	srcmirror = chan_from_num(i);
	if (!srcmirror)
		return -EINVAL;

	module_printk(KERN_INFO, "Chan %d tx mirrored to %d\n",
		      srcmirror->channo, chan->channo);

	spin_lock_irqsave(&srcmirror->lock, flags);
	srcmirror->txmirror = chan;
	if (srcmirror->txmirror == NULL)
		srcmirror->txmirror = chan;
	spin_unlock_irqrestore(&srcmirror->lock, flags);

	if (srcmirror->txmirror != chan) {
		module_printk(KERN_INFO, "Chan %d cannot be txmirrored, " \
			      "already in use\n", i);
		return -EFAULT;
	}

	spin_lock_irqsave(&chan->lock, flags);
	chan->srcmirror = srcmirror;
	chan->flags = srcmirror->flags;
	chan->sig =  srcmirror->sig;
	clear_bit(DAHDI_FLAGBIT_OPEN, &chan->flags);
	spin_unlock_irqrestore(&chan->lock, flags);

	return 0;
}
#endif /* CONFIG_DAHDI_MIRROR */

static int
dahdi_chanandpseudo_ioctl(struct file *file, unsigned int cmd,
			  unsigned long data)
{
	struct dahdi_chan *chan = chan_from_file(file);
	union {
		struct dahdi_bufferinfo bi;
		struct dahdi_ring_cadence cad;
	} stack;
	unsigned long flags;
	int i, j, rv;
	void __user * const user_data = (void __user *)data;

	if (!chan)
		return -EINVAL;
	switch(cmd) {
#ifdef CONFIG_DAHDI_MIRROR
	case DAHDI_RXMIRROR:
		return dahdi_ioctl_rxmirror(file, data);

	case DAHDI_TXMIRROR:
		return dahdi_ioctl_txmirror(file, data);
#endif /* CONFIG_DAHDI_MIRROR */

	case DAHDI_DIALING:
		spin_lock_irqsave(&chan->lock, flags);
		j = chan->dialing;
		spin_unlock_irqrestore(&chan->lock, flags);
		if (copy_to_user(user_data, &j, sizeof(int)))
			return -EFAULT;
		return 0;
	case DAHDI_DIAL:
		return ioctl_dahdi_dial(chan, data);
	case DAHDI_GET_BUFINFO:
		memset(&stack.bi, 0, sizeof(stack.bi));
		stack.bi.rxbufpolicy = chan->rxbufpolicy;
		stack.bi.txbufpolicy = chan->txbufpolicy;
		stack.bi.numbufs = chan->numbufs;
		stack.bi.bufsize = chan->blocksize;
		/* XXX FIXME! XXX */
		stack.bi.readbufs = -1;
		stack.bi.writebufs = -1;
		if (copy_to_user(user_data, &stack.bi, sizeof(stack.bi)))
			return -EFAULT;
		break;
	case DAHDI_SET_BUFINFO:
		if (copy_from_user(&stack.bi, user_data, sizeof(stack.bi)))
			return -EFAULT;
		if (stack.bi.bufsize > DAHDI_MAX_BLOCKSIZE)
			return -EINVAL;
		if (stack.bi.bufsize < 16)
			return -EINVAL;
		if (stack.bi.bufsize * stack.bi.numbufs > DAHDI_MAX_BUF_SPACE)
			return -EINVAL;
		/* It does not make sense to allow user mode to change the
		 * receive buffering policy.  DAHDI always provides received
		 * buffers to upper layers immediately.  Transmission is
		 * different since we might want to allow the kernel to build
		 * up a buffer in order to prevent underruns from the
		 * interrupt context. */
		chan->txbufpolicy = stack.bi.txbufpolicy & 0x3;
		if ((rv = dahdi_reallocbufs(chan,  stack.bi.bufsize, stack.bi.numbufs)))
			return (rv);
		break;
	case DAHDI_GET_BLOCKSIZE:  /* get blocksize */
		/* return block size */
		put_user(chan->blocksize, (int __user *)data);
		break;
	case DAHDI_SET_BLOCKSIZE:  /* set blocksize */
		get_user(j, (int __user *)data);
		/* cannot be larger than max amount */
		if (j > DAHDI_MAX_BLOCKSIZE) return(-EINVAL);
		/* cannot be less then 16 */
		if (j < 16) return(-EINVAL);
		/* allocate a single kernel buffer which we then
		sub divide into four pieces */
		if ((rv = dahdi_reallocbufs(chan, j, chan->numbufs)))
			return (rv);
		break;
	case DAHDI_FLUSH:  /* flush input buffer, output buffer, and/or event queue */
		get_user(i, (int __user *)data);  /* get param */
		spin_lock_irqsave(&chan->lock, flags);
		if (i & DAHDI_FLUSH_READ)  /* if for read (input) */
		   {
			  /* initialize read buffers and pointers */
			chan->inreadbuf = 0;
			chan->outreadbuf = -1;
			for (j=0;j<chan->numbufs;j++) {
				/* Do we need this? */
				chan->readn[j] = 0;
				chan->readidx[j] = 0;
			}
			wake_up_interruptible(&chan->waitq);  /* wake_up_interruptible waiting on read */
		   }
		if (i & DAHDI_FLUSH_WRITE) /* if for write (output) */
		   {
			  /* initialize write buffers and pointers */
			chan->outwritebuf = -1;
			chan->inwritebuf = 0;
			for (j=0;j<chan->numbufs;j++) {
				/* Do we need this? */
				chan->writen[j] = 0;
				chan->writeidx[j] = 0;
			}
			wake_up_interruptible(&chan->waitq); /* wake_up_interruptible waiting on write */
		   }
		if (i & DAHDI_FLUSH_EVENT) /* if for events */
		   {
			   /* initialize the event pointers */
			chan->eventinidx = chan->eventoutidx = 0;
		   }
		spin_unlock_irqrestore(&chan->lock, flags);
		break;
	case DAHDI_SYNC:  /* wait for no tx */
		for(;;)  /* loop forever */
		   {
			spin_lock_irqsave(&chan->lock, flags);
			  /* Know if there is a write pending */
			i = (chan->outwritebuf > -1);
			spin_unlock_irqrestore(&chan->lock, flags);
			if (!i)
				break; /* skip if none */
			rv = wait_event_interruptible(chan->waitq,
						      (chan->outwritebuf > -1));
			if (rv)
				return rv;
		   }
		break;
	case DAHDI_IOMUX: /* wait for something to happen */
		return dahdi_ioctl_iomux(file, data);

	case DAHDI_GETEVENT:  /* Get event on queue */
		  /* set up for no event */
		j = DAHDI_EVENT_NONE;
		spin_lock_irqsave(&chan->lock, flags);
		  /* if some event in queue */
		if (chan->eventinidx != chan->eventoutidx)
		   {
			j = chan->eventbuf[chan->eventoutidx++];
			  /* get the data, bump index */
			  /* if index overflow, set to beginning */
			if (chan->eventoutidx >= DAHDI_MAX_EVENTSIZE)
				chan->eventoutidx = 0;
		   }
		spin_unlock_irqrestore(&chan->lock, flags);
		put_user(j, (int __user *)data);
		break;
	case DAHDI_CONFMUTE:  /* set confmute flag */
		get_user(j, (int __user *)data);  /* get conf # */
		if (!(chan->flags & DAHDI_FLAG_AUDIO)) return (-EINVAL);
		spin_lock_irqsave(&chan_lock, flags);
		chan->confmute = j;
		spin_unlock_irqrestore(&chan_lock, flags);
		break;
	case DAHDI_GETCONFMUTE:  /* get confmute flag */
		if (!(chan->flags & DAHDI_FLAG_AUDIO)) return (-EINVAL);
		j = chan->confmute;
		put_user(j, (int __user *)data);  /* get conf # */
		rv = 0;
		break;
	case DAHDI_SETTONEZONE:
		get_user(j, (int __user *) data);
		rv = set_tone_zone(chan, j);
		return rv;
	case DAHDI_GETTONEZONE:
		spin_lock_irqsave(&chan->lock, flags);
		j = (chan->curzone) ? chan->curzone->num : 0;
		spin_unlock_irqrestore(&chan->lock, flags);
		put_user(j, (int __user *) data);
		break;
	case DAHDI_SENDTONE:
		get_user(j, (int __user *)data);
		spin_lock_irqsave(&chan->lock, flags);
		rv = start_tone(chan, j);
		spin_unlock_irqrestore(&chan->lock, flags);
		return rv;
	case DAHDI_GETCONF_V1: /* intentional drop through */
	case DAHDI_GETCONF:  /* get conf stuff */
		return dahdi_ioctl_getconf(file, data);

	case DAHDI_SETCONF_V1: /* Intentional fall through. */
	case DAHDI_SETCONF:  /* set conf stuff */
		return dahdi_ioctl_setconf(file, data);

	case DAHDI_CONFDIAG_V1: /* Intentional fall-through */
	case DAHDI_CONFDIAG:  /* output diagnostic info to console */
		return dahdi_ioctl_confdiag(file, data);

	case DAHDI_CHANNO:  /* get channel number of stream */
		/* return channel number */
		put_user(chan->channo, (int __user *)data);
		break;
	case DAHDI_SETLAW:
		get_user(j, (int __user *)data);
		if ((j < 0) || (j > DAHDI_LAW_ALAW))
			return -EINVAL;
		dahdi_set_law(chan, j);
		break;
	case DAHDI_SETLINEAR:
		get_user(j, (int __user *)data);
		/* Makes no sense on non-audio channels */
		if (!(chan->flags & DAHDI_FLAG_AUDIO))
			return -EINVAL;

		if (j)
			chan->flags |= DAHDI_FLAG_LINEAR;
		else
			chan->flags &= ~DAHDI_FLAG_LINEAR;
		break;
	case DAHDI_SETCADENCE:
		if (data) {
			/* Use specific ring cadence */
			if (copy_from_user(&stack.cad, user_data,
					   sizeof(stack.cad))) {
				return -EFAULT;
			}
			memcpy(chan->ringcadence, &stack.cad, sizeof(chan->ringcadence));
			chan->firstcadencepos = 0;
			/* Looking for negative ringing time indicating where to loop back into ringcadence */
			for (i=0; i<DAHDI_MAX_CADENCE; i+=2 ) {
				if (chan->ringcadence[i]<0) {
					chan->ringcadence[i] *= -1;
					chan->firstcadencepos = i;
					break;
				}
			}
		} else {
			/* Reset to default */
			chan->firstcadencepos = 0;
			if (chan->curzone) {
				memcpy(chan->ringcadence, chan->curzone->ringcadence, sizeof(chan->ringcadence));
				/* Looking for negative ringing time indicating where to loop back into ringcadence */
				for (i=0; i<DAHDI_MAX_CADENCE; i+=2 ) {
					if (chan->ringcadence[i]<0) {
						chan->ringcadence[i] *= -1;
						chan->firstcadencepos = i;
						break;
					}
				}
			} else {
				memset(chan->ringcadence, 0, sizeof(chan->ringcadence));
				chan->ringcadence[0] = chan->starttime;
				chan->ringcadence[1] = DAHDI_RINGOFFTIME;
			}
		}
		break;
	default:
		/* Check for common ioctl's and private ones */
		rv = dahdi_common_ioctl(file, cmd, data);
		/* if no span, just return with value */
		if (!chan->span) return rv;
		if ((rv == -ENOTTY) && chan->span->ops->ioctl)
			rv = chan->span->ops->ioctl(chan, cmd, data);
		return rv;

	}
	return 0;
}

#ifdef CONFIG_DAHDI_PPP
/*
 * This is called at softirq (BH) level when there are calls
 * we need to make to the ppp_generic layer.  We do it this
 * way because the ppp_generic layer functions may not be called
 * at interrupt level.
 */
static void do_ppp_calls(unsigned long data)
{
	struct dahdi_chan *chan = (struct dahdi_chan *) data;
	struct sk_buff *skb;

	if (!chan->ppp)
		return;
	if (chan->do_ppp_wakeup) {
		chan->do_ppp_wakeup = 0;
		ppp_output_wakeup(chan->ppp);
	}
	while ((skb = skb_dequeue(&chan->ppp_rq)) != NULL)
		ppp_input(chan->ppp, skb);
	if (chan->do_ppp_error) {
		chan->do_ppp_error = 0;
		ppp_input_error(chan->ppp, 0);
	}
}
#endif

static int
ioctl_echocancel(struct dahdi_chan *chan, struct dahdi_echocanparams *ecp,
		 const void __user *data)
{
	struct dahdi_echocan_state *ec = NULL, *ec_state;
	const struct dahdi_echocan_factory *ec_current;
	struct dahdi_echocanparam *params;
	int ret = 0;
	unsigned long flags;

	if (ecp->param_count > DAHDI_MAX_ECHOCANPARAMS)
		return -E2BIG;

	if (ecp->tap_length == 0) {
		/* disable mode, don't need to inspect params */
		spin_lock_irqsave(&chan->lock, flags);
		ec_state = chan->ec_state;
		chan->ec_state = NULL;
		ec_current = chan->ec_current;
		chan->ec_current = NULL;
		spin_unlock_irqrestore(&chan->lock, flags);
		if (ec_state) {
			ec_state->ops->echocan_free(chan, ec_state);
			release_echocan(ec_current);
		}

		return 0;
	}

	params = kmalloc(sizeof(params[0]) * DAHDI_MAX_ECHOCANPARAMS, GFP_KERNEL);

	if (!params)
		return -ENOMEM;

	/* enable mode, need the params */

	if (copy_from_user(params, data,
			   sizeof(params[0]) * ecp->param_count)) {
		ret = -EFAULT;
		goto exit_with_free;
	}

	/* free any echocan that may be on the channel already */
	spin_lock_irqsave(&chan->lock, flags);
	ec_state = chan->ec_state;
	chan->ec_state = NULL;
	ec_current = chan->ec_current;
	chan->ec_current = NULL;
	spin_unlock_irqrestore(&chan->lock, flags);
	if (ec_state) {
		ec_state->ops->echocan_free(chan, ec_state);
		release_echocan(ec_current);
	}

	switch (ecp->tap_length) {
	case 32:
	case 64:
	case 128:
	case 256:
	case 512:
	case 1024:
		break;
	default:
		ecp->tap_length = deftaps;
	}

	ec_current = NULL;

	if (chan->ec_factory) {
		/* try to get another reference to the module providing
		   this channel's echo canceler */
		if (!try_module_get(chan->ec_factory->owner)) {
			module_printk(KERN_ERR, "Cannot get a reference to the"
				      " '%s' echo canceler\n",
				      chan->ec_factory->get_name(chan));
			goto exit_with_free;
		}

		/* got the reference, copy the pointer and use it for making
		   an echo canceler instance if possible */
		ec_current = chan->ec_factory;

		ret = ec_current->echocan_create(chan, ecp, params, &ec);
		if (ret) {
			release_echocan(ec_current);

			goto exit_with_free;
		}
		if (!ec) {
			module_printk(KERN_ERR, "%s failed to allocate an " \
				      "dahdi_echocan_state instance.\n",
				      ec_current->get_name(chan));
			ret = -EFAULT;
			goto exit_with_free;
		}
	}

	if (ec) {
		spin_lock_irqsave(&chan->lock, flags);
		chan->ec_current = ec_current;
		chan->ec_state = ec;
		ec->status.mode = ECHO_MODE_ACTIVE;
		if (!ec->features.CED_tx_detect) {
			echo_can_disable_detector_init(&chan->ec_state->txecdis);
		}
		if (!ec->features.CED_rx_detect) {
			echo_can_disable_detector_init(&chan->ec_state->rxecdis);
		}
		spin_unlock_irqrestore(&chan->lock, flags);
	}

exit_with_free:
	kfree(params);

	return ret;
}

static void set_echocan_fax_mode(struct dahdi_chan *chan, unsigned int channo, const char *reason, unsigned int enable)
{
	if (enable) {
		if (!chan->ec_state)
			module_printk(KERN_NOTICE, "Ignoring FAX mode request because of %s for channel %d with no echo canceller\n", reason, channo);
		else if (chan->ec_state->status.mode == ECHO_MODE_FAX)
			module_printk(KERN_NOTICE, "Ignoring FAX mode request because of %s for echo canceller already in FAX mode on channel %d\n", reason, channo);
		else if (chan->ec_state->status.mode != ECHO_MODE_ACTIVE)
			module_printk(KERN_NOTICE, "Ignoring FAX mode request because of %s for echo canceller not in active mode on channel %d\n", reason, channo);
		else if (chan->ec_state->features.NLP_automatic) {
			/* for echocans that automatically do the right thing, just
			 * mark it as being in FAX mode without making any
			 * changes, as none are necessary.
			*/
			chan->ec_state->status.mode = ECHO_MODE_FAX;
		} else if (chan->ec_state->features.NLP_toggle) {
			module_printk(KERN_NOTICE, "Disabled echo canceller NLP because of %s on channel %d\n", reason, channo);
			dahdi_qevent_nolock(chan, DAHDI_EVENT_EC_NLP_DISABLED);
			chan->ec_state->ops->echocan_NLP_toggle(chan->ec_state, 0);
			chan->ec_state->status.mode = ECHO_MODE_FAX;
		} else {
			module_printk(KERN_NOTICE, "Idled echo canceller because of %s on channel %d\n", reason, channo);
			chan->ec_state->status.mode = ECHO_MODE_IDLE;
		}
	} else {
		if (!chan->ec_state)
			module_printk(KERN_NOTICE, "Ignoring voice mode request because of %s for channel %d with no echo canceller\n", reason, channo);
		else if (chan->ec_state->status.mode == ECHO_MODE_ACTIVE)
			module_printk(KERN_NOTICE, "Ignoring voice mode request because of %s for echo canceller already in voice mode on channel %d\n", reason, channo);
		else if ((chan->ec_state->status.mode != ECHO_MODE_FAX) &&
			 (chan->ec_state->status.mode != ECHO_MODE_IDLE))
			module_printk(KERN_NOTICE, "Ignoring voice mode request because of %s for echo canceller not in FAX or idle mode on channel %d\n", reason, channo);
		else if (chan->ec_state->features.NLP_automatic) {
			/* for echocans that automatically do the right thing, just
			 * mark it as being in active mode without making any
			 * changes, as none are necessary.
			*/
			chan->ec_state->status.mode = ECHO_MODE_ACTIVE;
		} else if (chan->ec_state->features.NLP_toggle) {
			module_printk(KERN_NOTICE, "Enabled echo canceller NLP because of %s on channel %d\n", reason, channo);
			dahdi_qevent_nolock(chan, DAHDI_EVENT_EC_NLP_ENABLED);
			chan->ec_state->ops->echocan_NLP_toggle(chan->ec_state, 1);
			chan->ec_state->status.mode = ECHO_MODE_ACTIVE;
		} else {
			module_printk(KERN_NOTICE, "Activated echo canceller because of %s on channel %d\n", reason, channo);
			chan->ec_state->status.mode = ECHO_MODE_ACTIVE;
		}
	}
}

static inline bool
is_txstate(struct dahdi_chan *const chan, const int txstate)
{
	bool ret;
	unsigned long flags;

	spin_lock_irqsave(&chan->lock, flags);
	ret = (txstate == chan->txstate);
	spin_unlock_irqrestore(&chan->lock, flags);
	return ret;
}

static int dahdi_chan_ioctl(struct file *file, unsigned int cmd, unsigned long data)
{
	struct dahdi_chan *const chan = chan_from_file(file);
	unsigned long flags;
	int j;
	int ret;
	int oldconf;
	const void *rxgain = NULL;

	if (!chan)
		return -ENOSYS;

	WARN_ON(!chan->master);

	switch(cmd) {
	case DAHDI_SETSIGFREEZE:
		get_user(j, (int __user *)data);
		spin_lock_irqsave(&chan->lock, flags);
		if (j) {
			chan->flags |= DAHDI_FLAG_SIGFREEZE;
		} else {
			chan->flags &= ~DAHDI_FLAG_SIGFREEZE;
		}
		spin_unlock_irqrestore(&chan->lock, flags);
		break;
	case DAHDI_GETSIGFREEZE:
		spin_lock_irqsave(&chan->lock, flags);
		if (chan->flags & DAHDI_FLAG_SIGFREEZE)
			j = 1;
		else
			j = 0;
		spin_unlock_irqrestore(&chan->lock, flags);
		put_user(j, (int __user *)data);
		break;
	case DAHDI_AUDIOMODE:
		/* Only literal clear channels can be put in  */
		if (chan->sig != DAHDI_SIG_CLEAR) return (-EINVAL);
		get_user(j, (int __user *)data);
		if (j) {
			spin_lock_irqsave(&chan->lock, flags);
			chan->flags |= DAHDI_FLAG_AUDIO;
			chan->flags &= ~(DAHDI_FLAG_HDLC | DAHDI_FLAG_FCS);
			spin_unlock_irqrestore(&chan->lock, flags);
		} else {
			/* Coming out of audio mode, also clear all
			   conferencing and gain related info as well
			   as echo canceller */
			struct dahdi_echocan_state *ec_state;
			const struct dahdi_echocan_factory *ec_current;

			spin_lock_irqsave(&chan->lock, flags);
			chan->flags &= ~DAHDI_FLAG_AUDIO;
			/* save old conf number, if any */
			oldconf = chan->confna;
			  /* initialize conference variables */
			chan->_confn = 0;
			chan->confna = 0;
			chan->conf_chan = NULL;
			dahdi_disable_dacs(chan);
			chan->confmode = 0;
			chan->confmute = 0;
			memset(chan->conflast, 0, sizeof(chan->conflast));
			memset(chan->conflast1, 0, sizeof(chan->conflast1));
			memset(chan->conflast2, 0, sizeof(chan->conflast2));
			ec_state = chan->ec_state;
			chan->ec_state = NULL;
			ec_current = chan->ec_current;
			chan->ec_current = NULL;
			/* release conference resource, if any to release */
			reset_conf(chan);
			if (is_gain_allocated(chan))
				rxgain = chan->rxgain;
			else
				rxgain = NULL;

			chan->rxgain = defgain;
			chan->txgain = defgain;
			spin_unlock_irqrestore(&chan->lock, flags);

			if (ec_state) {
				ec_state->ops->echocan_free(chan, ec_state);
				release_echocan(ec_current);
			}

			if (rxgain)
				kfree(rxgain);
			if (oldconf) dahdi_check_conf(oldconf);
		}
#ifdef	DAHDI_AUDIO_NOTIFY
		if (chan->span->ops->audio_notify)
			chan->span->ops->audio_notify(chan, j);
#endif
		break;
	case DAHDI_HDLCPPP:
#ifdef CONFIG_DAHDI_PPP
		if (chan->sig != DAHDI_SIG_CLEAR) return (-EINVAL);
		get_user(j, (int __user *)data);
		if (j) {
			if (!chan->ppp) {
				chan->ppp = kzalloc(sizeof(struct ppp_channel), GFP_KERNEL);
				if (chan->ppp) {
					struct dahdi_echocan_state *tec;
					const struct dahdi_echocan_factory *ec_current;

					chan->ppp->private = chan;
					chan->ppp->ops = &ztppp_ops;
					chan->ppp->mtu = DAHDI_DEFAULT_MTU_MRU;
					chan->ppp->hdrlen = 0;
					skb_queue_head_init(&chan->ppp_rq);
					chan->do_ppp_wakeup = 0;
					tasklet_init(&chan->ppp_calls, do_ppp_calls,
						     (unsigned long)chan);
					if ((ret = dahdi_reallocbufs(chan, DAHDI_DEFAULT_MTU_MRU, DAHDI_DEFAULT_NUM_BUFS))) {
						kfree(chan->ppp);
						chan->ppp = NULL;
						return ret;
					}

					if ((ret = ppp_register_channel(chan->ppp))) {
						kfree(chan->ppp);
						chan->ppp = NULL;
						return ret;
					}
					tec = chan->ec_state;
					chan->ec_state = NULL;
					ec_current = chan->ec_current;
					chan->ec_current = NULL;
					/* Make sure there's no gain */
					if (is_gain_allocated(chan))
						kfree(chan->rxgain);
					chan->rxgain = defgain;
					chan->txgain = defgain;
					chan->flags &= ~DAHDI_FLAG_AUDIO;
					chan->flags |= (DAHDI_FLAG_PPP | DAHDI_FLAG_HDLC | DAHDI_FLAG_FCS);

					if (tec) {
						tec->ops->echocan_free(chan, tec);
						release_echocan(ec_current);
					}
				} else
					return -ENOMEM;
			}
		} else {
			chan->flags &= ~(DAHDI_FLAG_PPP | DAHDI_FLAG_HDLC | DAHDI_FLAG_FCS);
			if (chan->ppp) {
				struct ppp_channel *ppp = chan->ppp;
				chan->ppp = NULL;
				tasklet_kill(&chan->ppp_calls);
				skb_queue_purge(&chan->ppp_rq);
				ppp_unregister_channel(ppp);
				kfree(ppp);
			}
		}
#else
		module_printk(KERN_NOTICE, "PPP support not compiled in\n");
		return -ENOSYS;
#endif
		break;
	case DAHDI_HDLCRAWMODE:
		if (chan->sig != DAHDI_SIG_CLEAR)	return (-EINVAL);
		get_user(j, (int __user *)data);
		chan->flags &= ~(DAHDI_FLAG_AUDIO | DAHDI_FLAG_HDLC | DAHDI_FLAG_FCS);
		if (j) {
			chan->flags |= DAHDI_FLAG_HDLC;
			fasthdlc_init(&chan->rxhdlc, (chan->flags & DAHDI_FLAG_HDLC56) ? FASTHDLC_MODE_56 : FASTHDLC_MODE_64);
			fasthdlc_init(&chan->txhdlc, (chan->flags & DAHDI_FLAG_HDLC56) ? FASTHDLC_MODE_56 : FASTHDLC_MODE_64);
		}
		break;
	case DAHDI_HDLCFCSMODE:
		if (chan->sig != DAHDI_SIG_CLEAR)	return (-EINVAL);
		get_user(j, (int __user *)data);
		chan->flags &= ~(DAHDI_FLAG_AUDIO | DAHDI_FLAG_HDLC | DAHDI_FLAG_FCS);
		if (j) {
			chan->flags |= DAHDI_FLAG_HDLC | DAHDI_FLAG_FCS;
			fasthdlc_init(&chan->rxhdlc, (chan->flags & DAHDI_FLAG_HDLC56) ? FASTHDLC_MODE_56 : FASTHDLC_MODE_64);
			fasthdlc_init(&chan->txhdlc, (chan->flags & DAHDI_FLAG_HDLC56) ? FASTHDLC_MODE_56 : FASTHDLC_MODE_64);
		}
		break;
	case DAHDI_HDLC_RATE:
		get_user(j, (int __user *)data);
		if (j == 56) {
			chan->flags |= DAHDI_FLAG_HDLC56;
		} else {
			chan->flags &= ~DAHDI_FLAG_HDLC56;
		}

		fasthdlc_init(&chan->rxhdlc, (chan->flags & DAHDI_FLAG_HDLC56) ? FASTHDLC_MODE_56 : FASTHDLC_MODE_64);
		fasthdlc_init(&chan->txhdlc, (chan->flags & DAHDI_FLAG_HDLC56) ? FASTHDLC_MODE_56 : FASTHDLC_MODE_64);
		break;
	case DAHDI_ECHOCANCEL_PARAMS:
	{
		struct dahdi_echocanparams ecp;

		if (!(chan->flags & DAHDI_FLAG_AUDIO))
			return -EINVAL;
		ret = copy_from_user(&ecp,
				     (struct dahdi_echocanparams __user *)data,
				     sizeof(ecp));
		if (ret)
			return -EFAULT;
		data += sizeof(ecp);
		ret = ioctl_echocancel(chan, &ecp, (void __user *)data);
		if (ret)
			return ret;
		break;
	}
	case DAHDI_ECHOCANCEL:
	{
		struct dahdi_echocanparams ecp;

		if (!(chan->flags & DAHDI_FLAG_AUDIO))
			return -EINVAL;
		get_user(j, (int __user *) data);
		ecp.tap_length = j;
		ecp.param_count = 0;
		if ((ret = ioctl_echocancel(chan, &ecp, NULL)))
			return ret;
		break;
	}
	case DAHDI_ECHOTRAIN:
		/* get pre-training time from user */
		get_user(j, (int __user *)data);
		if ((j < 0) || (j >= DAHDI_MAX_PRETRAINING))
			return -EINVAL;
		j <<= 3;
		spin_lock_irqsave(&chan->lock, flags);
		if (chan->ec_state) {
			/* Start pretraining stage */
			if (chan->ec_state->ops->echocan_traintap) {
				chan->ec_state->status.mode = ECHO_MODE_PRETRAINING;
				chan->ec_state->status.pretrain_timer = j;
			}
			spin_unlock_irqrestore(&chan->lock, flags);
		} else {
			spin_unlock_irqrestore(&chan->lock, flags);
			return -EINVAL;
		}
		break;
	case DAHDI_ECHOCANCEL_FAX_MODE:
		if (!chan->ec_state) {
			return -EINVAL;
		} else {
			get_user(j, (int __user *) data);
			spin_lock_irqsave(&chan->lock, flags);
			set_echocan_fax_mode(chan, chan->channo, "ioctl", j ? 1 : 0);
			spin_unlock_irqrestore(&chan->lock, flags);
		}
		break;
	case DAHDI_SETTXBITS:
		if (chan->sig != DAHDI_SIG_CAS)
			return -EINVAL;
		get_user(j, (int __user *)data);
		dahdi_cas_setbits(chan, j);
		break;
	case DAHDI_GETRXBITS:
		put_user(chan->rxsig, (int __user *)data);
		break;
	case DAHDI_LOOPBACK:
		get_user(j, (int __user *)data);
		spin_lock_irqsave(&chan->lock, flags);
		if (j)
			chan->flags |= DAHDI_FLAG_LOOPED;
		else
			chan->flags &= ~DAHDI_FLAG_LOOPED;
		spin_unlock_irqrestore(&chan->lock, flags);
		break;
	case DAHDI_HOOK:
		get_user(j, (int __user *)data);
		if (chan->flags & DAHDI_FLAG_CLEAR)
			return -EINVAL;
		if (chan->sig == DAHDI_SIG_CAS)
			return -EINVAL;
		/* if no span, just do nothing */
		if (!chan->span) return(0);
		spin_lock_irqsave(&chan->lock, flags);
		/* if dialing, stop it */
		chan->curtone = NULL;
		chan->dialing = 0;
		chan->txdialbuf[0] = '\0';
		chan->tonep = 0;
		chan->pdialcount = 0;
		spin_unlock_irqrestore(&chan->lock, flags);
		if (chan->span->flags & DAHDI_FLAG_RBS) {
			switch (j) {
			case DAHDI_ONHOOK:
				spin_lock_irqsave(&chan->lock, flags);
				dahdi_hangup(chan);
				spin_unlock_irqrestore(&chan->lock, flags);
				break;
			case DAHDI_OFFHOOK:
				spin_lock_irqsave(&chan->lock, flags);
				if ((chan->txstate == DAHDI_TXSTATE_KEWL) ||
				  (chan->txstate == DAHDI_TXSTATE_AFTERKEWL)) {
					spin_unlock_irqrestore(&chan->lock, flags);
					return -EBUSY;
				}
				dahdi_rbs_sethook(chan, DAHDI_TXSIG_OFFHOOK, DAHDI_TXSTATE_DEBOUNCE, chan->debouncetime);
				spin_unlock_irqrestore(&chan->lock, flags);
				break;
			case DAHDI_RING:
			case DAHDI_START:
				spin_lock_irqsave(&chan->lock, flags);
				if (!chan->curzone) {
					spin_unlock_irqrestore(&chan->lock, flags);
					module_printk(KERN_WARNING, "Cannot start tone until a tone zone is loaded.\n");
					return -ENODATA;
				}
				if (chan->txstate != DAHDI_TXSTATE_ONHOOK) {
					spin_unlock_irqrestore(&chan->lock, flags);
					return -EBUSY;
				}
				if (chan->sig & __DAHDI_SIG_FXO) {
					ret = 0;
					chan->cadencepos = 0;
					ret = chan->ringcadence[0];
					dahdi_rbs_sethook(chan, DAHDI_TXSIG_START, DAHDI_TXSTATE_RINGON, ret);
				} else
					dahdi_rbs_sethook(chan, DAHDI_TXSIG_START, DAHDI_TXSTATE_START, chan->starttime);
				spin_unlock_irqrestore(&chan->lock, flags);
				if (file->f_flags & O_NONBLOCK)
					return -EINPROGRESS;
				break;
			case DAHDI_WINK:
				spin_lock_irqsave(&chan->lock, flags);
				if (chan->txstate != DAHDI_TXSTATE_ONHOOK) {
					spin_unlock_irqrestore(&chan->lock, flags);
					return -EBUSY;
				}
				dahdi_rbs_sethook(chan, DAHDI_TXSIG_ONHOOK, DAHDI_TXSTATE_PREWINK, chan->prewinktime);
				spin_unlock_irqrestore(&chan->lock, flags);
				if (file->f_flags & O_NONBLOCK)
					return -EINPROGRESS;
				wait_event_interruptible(chan->waitq,
					is_txstate(chan, DAHDI_TXSIG_ONHOOK));
				if (signal_pending(current))
					return -ERESTARTSYS;
				break;
			case DAHDI_FLASH:
				spin_lock_irqsave(&chan->lock, flags);
				if (chan->txstate != DAHDI_TXSTATE_OFFHOOK) {
					spin_unlock_irqrestore(&chan->lock, flags);
					return -EBUSY;
				}
				dahdi_rbs_sethook(chan, DAHDI_TXSIG_OFFHOOK, DAHDI_TXSTATE_PREFLASH, chan->preflashtime);
				spin_unlock_irqrestore(&chan->lock, flags);
				if (file->f_flags & O_NONBLOCK)
					return -EINPROGRESS;
				wait_event_interruptible(chan->waitq,
					is_txstate(chan, DAHDI_TXSIG_OFFHOOK));
				if (signal_pending(current))
					return -ERESTARTSYS;
				break;
			case DAHDI_RINGOFF:
				spin_lock_irqsave(&chan->lock, flags);
				dahdi_rbs_sethook(chan, DAHDI_TXSIG_ONHOOK, DAHDI_TXSTATE_ONHOOK, 0);
				spin_unlock_irqrestore(&chan->lock, flags);
				break;
			default:
				return -EINVAL;
			}
		} else if (chan->span->ops->sethook) {
			if (chan->txhooksig != j) {
				chan->txhooksig = j;
				chan->span->ops->sethook(chan, j);
			}
		} else
			return -ENOSYS;
		break;
#ifdef CONFIG_DAHDI_PPP
	case PPPIOCGCHAN:
		if (chan->flags & DAHDI_FLAG_PPP) {
			return put_user(ppp_channel_index(chan->ppp),
					(int __user *)data) ? -EFAULT : 0;
		} else {
			return -EINVAL;
		}
		break;
	case PPPIOCGUNIT:
		if (chan->flags & DAHDI_FLAG_PPP) {
			return put_user(ppp_unit_number(chan->ppp),
					(int __user *)data) ? -EFAULT : 0;
		} else {
			return -EINVAL;
		}
		break;
#endif
	case DAHDI_BUFFER_EVENTS:
		if (get_user(j, (int __user *)data))
			return -EFAULT;
		if (j)
			set_bit(DAHDI_FLAGBIT_BUFEVENTS, &chan->flags);
		else
			clear_bit(DAHDI_FLAGBIT_BUFEVENTS, &chan->flags);

		break;
	default:
		return dahdi_chanandpseudo_ioctl(file, cmd, data);
	}
	return 0;
}

static int dahdi_prechan_ioctl(struct file *file, unsigned int cmd, unsigned long data)
{
	int channo;
	int res;

	if (file->private_data) {
		module_printk(KERN_NOTICE, "Huh?  Prechan already has private data??\n");
	}
	switch(cmd) {
	case DAHDI_SPECIFY:
		get_user(channo, (int __user *)data);
		file->private_data = chan_from_num(channo);
		if (!file->private_data)
			return -EINVAL;
		res = dahdi_specchan_open(file);
		if (res)
			file->private_data = NULL;
		return res;
	default:
		return -ENOSYS;
	}
	return 0;
}

static long
dahdi_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long data)
{
	int unit = UNIT(file);
	struct dahdi_timer *timer;
	int ret;

#if defined(HAVE_UNLOCKED_IOCTL) && defined(CONFIG_BKL)
	lock_kernel();
#endif

	if (unit == DAHDI_CTL) {
		ret = dahdi_ctl_ioctl(file, cmd, data);
		goto unlock_exit;
	}

	if (unit == DAHDI_TRANSCODE) {
		/* dahdi_transcode should have updated the file_operations on
		 * this file object on open, so we shouldn't be here. */
		WARN_ON(1);
		ret = -EFAULT;
		goto unlock_exit;
	}

	if (unit == DAHDI_TIMER) {
		timer = file->private_data;
		if (timer)
			ret = dahdi_timer_ioctl(file, cmd, data, timer);
		else
			ret = -EINVAL;
		goto unlock_exit;
	}
	if (unit == DAHDI_CHANNEL) {
		if (file->private_data)
			ret = dahdi_chan_ioctl(file, cmd, data);
		else
			ret = dahdi_prechan_ioctl(file, cmd, data);
		goto unlock_exit;
	}
	if (unit == DAHDI_PSEUDO) {
		if (!file->private_data) {
			module_printk(KERN_NOTICE, "No pseudo channel structure to read?\n");
			ret = -EINVAL;
			goto unlock_exit;
		}
		ret = dahdi_chanandpseudo_ioctl(file, cmd, data);
		goto unlock_exit;
	}

	if (!file->private_data) {
		ret = -ENXIO;
		goto unlock_exit;
	}

	ret = dahdi_chan_ioctl(file, cmd, data);

unlock_exit:
#if defined(HAVE_UNLOCKED_IOCTL) && defined(CONFIG_BKL)
	unlock_kernel();
#endif
	return ret;
}

#ifndef HAVE_UNLOCKED_IOCTL
static int dahdi_ioctl(struct inode *inode, struct file *file,
		unsigned int cmd, unsigned long data)
{
	return dahdi_unlocked_ioctl(file, cmd, data);
}
#endif

#ifdef HAVE_COMPAT_IOCTL
static long dahdi_ioctl_compat(struct file *file, unsigned int cmd,
		unsigned long data)
{
	if (cmd == DAHDI_SFCONFIG)
		return -ENOTTY; /* Not supported yet */

	return dahdi_unlocked_ioctl(file, cmd, data);
}
#endif

/**
 * _get_next_channo - Return the next taken channel number from the span list.
 * @span:	The span with which to start the search.
 *
 * Returns -1 if there aren't any channels on span or any of the following
 * spans, otherwise, returns the channel number of the first channel.
 *
 * Must be callled with registration_mutex held.
 *
 */
static unsigned int _get_next_channo(const struct dahdi_span *span)
{
	const struct list_head *pos = &span->spans_node;
	while (pos != &span_list) {
		span = list_entry(pos, struct dahdi_span, spans_node);
		if (span->channels)
			return span->chans[0]->channo;
		pos = pos->next;
	}
	return -1;
}

static void
set_spanno_and_basechan(struct dahdi_span *span, u32 spanno, u32 basechan)
{
	int i;
	span->spanno = spanno;
	for (i = 0; i < span->channels; ++i)
		span->chans[i]->channo = basechan + i;
}

/**
 * _assign_spanno_and_basechan - Assign next available span and channel numbers.
 *
 * This function will set span->spanno and channo for all the member channels.
 * It will assign the first available location.
 *
 * Must be called with registration_mutex held.
 *
 */
static int _assign_spanno_and_basechan(struct dahdi_span *span)
{
	struct dahdi_span *pos;
	unsigned int next_channo;
	unsigned int spanno = 1;
	unsigned int basechan = 1;

	list_for_each_entry(pos, &span_list, spans_node) {

		if (pos->spanno <= spanno) {
			spanno = pos->spanno + 1;
			basechan = pos->chans[0]->channo + pos->channels;
			continue;
		}

		next_channo = _get_next_channo(pos);
		if ((basechan + span->channels) >= next_channo)
			break;

		/* We can't fit here, let's look at the next location. */
		spanno = pos->spanno + 1;
		if (pos->channels)
			basechan = pos->chans[0]->channo + pos->channels;
	}

	set_spanno_and_basechan(span, spanno, basechan);
	trace_printk("%s: spanno: %d basechan: %d span->spanno: %d\n",
		     dev_name(&span->parent->dev), spanno, basechan,
		     span->spanno);
	return 0;
}

static inline struct dahdi_span *span_from_node(struct list_head *node)
{
	return container_of(node, struct dahdi_span, spans_node);
}

/*
 * Call with registration_mutex held.  Make sure all the spans are on the list
 * ordered by span.
 *
 */
static void _dahdi_add_span_to_span_list(struct dahdi_span *span)
{
	unsigned long flags;
	struct dahdi_span *pos;

	if (list_empty(&span_list)) {
		list_add_tail(&span->spans_node, &span_list);
		return;
	}

	list_for_each_entry(pos, &span_list, spans_node) {
		WARN_ON(0 == pos->spanno);
		if (pos->spanno <= span->spanno)
			continue;
	}

	trace_printk("%s: pos->spanno=%d span->spanno: %d\n",
		     dev_name(&span->parent->dev), pos->spanno, span->spanno);

	spin_lock_irqsave(&chan_lock, flags);
	list_add_tail(&span->spans_node, &pos->spans_node);
	spin_unlock_irqrestore(&chan_lock, flags);
}

/**
 * _check_spanno_and_basechan - Check if we can fit the new span in the requested location.
 *
 * Must be called with registration_mutex held.
 *
 */
static int
_check_spanno_and_basechan(struct dahdi_span *span, u32 spanno, u32 basechan)
{
	struct dahdi_span *pos;
	unsigned int next_channo;

	list_for_each_entry(pos, &span_list, spans_node) {

		if (pos->spanno <= spanno)
			continue;

		next_channo = _get_next_channo(pos);
		if (!next_channo)
			break;

		if ((basechan + span->channels) >= next_channo)
			break;

		/* Cannot fit the span into the requested location. Abort. */
		return -EINVAL;
	}

	set_spanno_and_basechan(span, spanno, basechan);
	return 0;
}


struct dahdi_device *dahdi_create_device(void)
{
	struct dahdi_device *ddev;
	ddev = kzalloc(sizeof(*ddev), GFP_KERNEL);
	if (!ddev)
		return NULL;
	INIT_LIST_HEAD(&ddev->spans);
	dahdi_sysfs_init_device(ddev);
	return ddev;
}
EXPORT_SYMBOL(dahdi_create_device);

void dahdi_free_device(struct dahdi_device *ddev)
{
	put_device(&ddev->dev);
}
EXPORT_SYMBOL(dahdi_free_device);

/**
 * __dahdi_init_span - Setup all the data structures for the span.
 * @span:	The span of interest.
 *
 */
static void __dahdi_init_span(struct dahdi_span *span)
{
	int x;

	INIT_LIST_HEAD(&span->spans_node);
	spin_lock_init(&span->lock);
	clear_bit(DAHDI_FLAGBIT_REGISTERED, &span->flags);

	if (!span->deflaw) {
		module_printk(KERN_NOTICE, "Span %s didn't specify default "
			      "law. Assuming mulaw, please fix driver!\n",
			      span->name);
		span->deflaw = DAHDI_LAW_MULAW;
	}

	for (x = 0; x < span->channels; ++x) {
		span->chans[x]->span = span;
		__dahdi_init_chan(span->chans[x]);
	}
}

/**
 * _dahdi_register_span() - Register a new DAHDI span
 * @span:	the DAHDI span
 * @spanno:	The span number we would like assigned. If 0, the first
 *		available spanno/basechan will be used.
 * @basechan:	The base channel number we would like. Ignored if spanno is 0.
 * @prefmaster:	will the new span be preferred as a master?
 *
 * Registers a span for usage with DAHDI. All the channel numbers in it
 * will get the lowest available channel numbers.
 *
 * If prefmaster is set to anything > 0, span will attempt to become the
 * master DAHDI span at registration time. If 0: it will only become
 * master if no other span is currently the master (i.e.: it is the
 * first one).
 *
 * Must be called with registration_mutex held, and the span must have already
 * been initialized ith the __dahdi_init_span call.
 *
 */
static int _dahdi_register_span(struct dahdi_span *span, unsigned int spanno,
				unsigned int basechan, int prefmaster)
{
	int res = 0;
	unsigned int x;

	if (!span || !span->ops || !span->ops->owner)
		return -EINVAL;

	if (test_bit(DAHDI_FLAGBIT_REGISTERED, &span->flags)) {
		dev_info(span->parent->dev.parent,
			 "local span %d is already registered as span %d "
			 "with base channel %d\n", span->offset, span->spanno,
			 span->chans[0]->channo);
		return -EINVAL;
	}

	/* Look through the span list to find the first available span number.
	 * The spans are kept on this list in sorted order. We'll also save
	 * off the next available channel number to use. */

	if (0 == spanno)
		res = _assign_spanno_and_basechan(span);
	else
		res = _check_spanno_and_basechan(span, spanno, basechan);

	if (res)
		return res;

	trace_printk("span->spanno: %d\n", span->spanno);

	for (x = 0; x < span->channels; x++)
		dahdi_chan_reg(span->chans[x]);

#ifdef CONFIG_PROC_FS
	{
		char tempfile[17];
		snprintf(tempfile, sizeof(tempfile), "%d", span->spanno);
		span->proc_entry = create_proc_entry(tempfile, 0444,
					root_proc_entry);
		if (!span->proc_entry) {
			res = -EFAULT;
			span_err(span, "Error creating procfs entry\n");
			goto cleanup;
		}
		span->proc_entry->data = (void *)(long)span->spanno;
		span->proc_entry->proc_fops = &dahdi_proc_ops;
	}
#endif

	res = span_sysfs_create(span);
	if (res)
		goto cleanup;

	if (debug & DEBUG_MAIN) {
		module_printk(KERN_NOTICE, "Registered Span %d ('%s') with "
				"%d channels\n", span->spanno, span->name, span->channels);
	}

	_dahdi_add_span_to_span_list(span);

	set_bit(DAHDI_FLAGBIT_REGISTERED, &span->flags);
	if (span->ops->registered)
		span->ops->registered(span);

	__dahdi_find_master_span();

	return 0;

cleanup:
#ifdef CONFIG_PROC_FS
	if (span->proc_entry) {
		char tempfile[17];

		snprintf(tempfile, sizeof(tempfile), "dahdi/%d", span->spanno);
		remove_proc_entry(tempfile, NULL);
		span->proc_entry = NULL;
	}
#endif
	for (x = 0; x < span->channels; x++) {
		struct dahdi_chan *chan = span->chans[x];
		if (test_bit(DAHDI_FLAGBIT_REGISTERED, &chan->flags))
			dahdi_chan_unreg(chan);
	}
	return res;
}

int dahdi_register_span(struct dahdi_span *span, unsigned int spanno,
			unsigned int basechan, int prefmaster)
{
	int ret;
	mutex_lock(&registration_mutex);
	ret = _dahdi_register_span(span, spanno, basechan, prefmaster);
	mutex_unlock(&registration_mutex);
	return ret;
}

int dahdi_register_device_spans(struct dahdi_device *ddev)
{
	struct dahdi_span *span;
	mutex_lock(&registration_mutex);
	list_for_each_entry(span, &ddev->spans, device_node)
		_dahdi_register_span(span, 0, 0, 1);
	mutex_unlock(&registration_mutex);
	return 0;
}

static int auto_register_spans = 1;
static const char *UNKNOWN = "";

/**
 * _dahdi_register_device - Registers the spans of a DAHDI device.
 * @ddev:	the DAHDI device
 *
 * If auto_register_spans is 0, add the device to the device list and wait for
 * userspace to finish registration. Otherwise, go ahead and register the
 * spans in order as was done historically.
 *
 * Must hold registration_mutex when this function is called.
 *
 */
static int _dahdi_register_device(struct dahdi_device *ddev,
				  struct device *parent)
{
	struct dahdi_span *s;
	int idx;
	int ret;

	ddev->manufacturer	= (ddev->manufacturer) ?: UNKNOWN;
	ddev->location		= (ddev->location) ?: UNKNOWN;
	ddev->devicetype	= (ddev->devicetype) ?: UNKNOWN;

	idx = 0;
	list_for_each_entry(s, &ddev->spans, device_node) {
		s->parent = ddev;
		s->spanno = 0;
		s->span_idx = idx++;
		__dahdi_init_span(s);
	}

	ret = dahdi_sysfs_add_device(ddev, parent);
	if (ret)
		return ret;

	if (!auto_register_spans)
		return 0;

	list_for_each_entry(s, &ddev->spans, device_node)
		ret = _dahdi_register_span(s, 0, 0, 1);

	return ret;
}

/**
 * dahdi_register_device() - unregister a new DAHDI device
 * @ddev:	the DAHDI device
 *
 * Registers a device for usage with DAHDI.
 *
 */
int dahdi_register_device(struct dahdi_device *ddev, struct device *parent)
{
	int ret;

	if (!ddev)
		return -EINVAL;

	mutex_lock(&registration_mutex);
	ret = _dahdi_register_device(ddev, parent);
	mutex_unlock(&registration_mutex);

	return ret;
}
EXPORT_SYMBOL(dahdi_register_device);

/**
 * _dahdi_unregister_span() - unregister a DAHDI span
 * @span:	the DAHDI span
 * @prefmaster:	will the new span be preferred as a master?
 *
 * Registers a span for usage with DAHDI. All the channel numbers in it
 * will get the lowest available channel numbers.
 *
 * If prefmaster is set to anything > 0, span will attempt to become the
 * master DAHDI span at registration time. If 0: it will only become
 * master if no other span is currently the master (i.e.: it is the
 * first one).
 *
 * Unregisters a span that has been previously registered with
 * dahdi_register_span().
 *
 * Must be called with the registration_mutex held.
 *
 */
static int _dahdi_unregister_span(struct dahdi_span *span)
{
	int x;
	struct dahdi_span *new_master, *s;
	unsigned long flags;

	spin_lock_irqsave(&chan_lock, flags);
	list_del_init(&span->spans_node);
	spin_unlock_irqrestore(&chan_lock, flags);
	span->spanno = 0;
	clear_bit(DAHDI_FLAGBIT_REGISTERED, &span->flags);

	/* Shutdown the span if it's running */
	if ((span->flags & DAHDI_FLAG_RUNNING) && span->ops->shutdown)
		span->ops->shutdown(span);

	if (debug & DEBUG_MAIN)
		module_printk(KERN_NOTICE, "Unregistering Span '%s' with %d channels\n", span->name, span->channels);
#ifdef CONFIG_PROC_FS
	if (span->proc_entry)
		remove_proc_entry(span->proc_entry->name, root_proc_entry);
#endif /* CONFIG_PROC_FS */

	span_sysfs_remove(span);

	for (x=0;x<span->channels;x++)
		dahdi_chan_unreg(span->chans[x]);

	new_master = master; /* FIXME: locking */
	if (master == span)
		new_master = NULL;

	spin_lock_irqsave(&chan_lock, flags);
	list_for_each_entry(s, &span_list, spans_node) {
		if ((s == new_master) || !can_provide_timing(s))
			continue;
		new_master = s;
		break;
	}
	spin_unlock_irqrestore(&chan_lock, flags);
	if (master != new_master) {
		if (debug & DEBUG_MAIN) {
			module_printk(KERN_NOTICE, "%s: Span ('%s') is new master\n", __FUNCTION__,
				      (new_master)? new_master->name: "no master");
		}
	}
	master = new_master;
	return 0;
}

int dahdi_unregister_span(struct dahdi_span *span)
{
	module_printk(KERN_NOTICE, "%s: %s\n", __FUNCTION__, span->name);
	mutex_lock(&registration_mutex);
	_dahdi_unregister_span(span);
	list_del_init(&span->device_node);
	mutex_unlock(&registration_mutex);
	return 0;
}
EXPORT_SYMBOL(dahdi_unregister_span);

/**
 * dahdi_unregister_device() - unregister a DAHDI device
 * @span:	the DAHDI span
 *
 * Unregisters a device that has been previously registered with
 * dahdi_register_device().
 *
 */
void dahdi_unregister_device(struct dahdi_device *ddev)
{
	struct dahdi_span *s;
	WARN_ON(!ddev);
	might_sleep();
	if (unlikely(!ddev))
		return;

	mutex_lock(&registration_mutex);
	list_for_each_entry(s, &ddev->spans, device_node)
		_dahdi_unregister_span(s);
	mutex_unlock(&registration_mutex);

	dahdi_sysfs_unregister_device(ddev);

	if (UNKNOWN == ddev->location)
		ddev->location = NULL;
	if (UNKNOWN == ddev->manufacturer)
		ddev->manufacturer = NULL;
	if (UNKNOWN == ddev->devicetype)
		ddev->devicetype = NULL;

}
EXPORT_SYMBOL(dahdi_unregister_device);

/*
** This routine converts from linear to ulaw
**
** Craig Reese: IDA/Supercomputing Research Center
** Joe Campbell: Department of Defense
** 29 September 1989
**
** References:
** 1) CCITT Recommendation G.711  (very difficult to follow)
** 2) "A New Digital Technique for Implementation of Any
**     Continuous PCM Companding Law," Villeret, Michel,
**     et al. 1973 IEEE Int. Conf. on Communications, Vol 1,
**     1973, pg. 11.12-11.17
** 3) MIL-STD-188-113,"Interoperability and Performance Standards
**     for Analog-to_Digital Conversion Techniques,"
**     17 February 1987
**
** Input: Signed 16 bit linear sample
** Output: 8 bit ulaw sample
*/

#define ZEROTRAP    /* turn on the trap as per the MIL-STD */
#define BIAS 0x84   /* define the add-in bias for 16 bit samples */
#define CLIP 32635

#ifdef CONFIG_CALC_XLAW
unsigned char
#else
static unsigned char  __init
#endif
__dahdi_lineartoulaw(short sample)
{
  static int exp_lut[256] = {0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,
                             4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
                             5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
                             5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
                             6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
                             6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
                             6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
                             6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7};
  int sign, exponent, mantissa;
  unsigned char ulawbyte;

  /* Get the sample into sign-magnitude. */
  sign = (sample >> 8) & 0x80;          /* set aside the sign */
  if (sign != 0) sample = -sample;              /* get magnitude */
  if (sample > CLIP) sample = CLIP;             /* clip the magnitude */

  /* Convert from 16 bit linear to ulaw. */
  sample = sample + BIAS;
  exponent = exp_lut[(sample >> 7) & 0xFF];
  mantissa = (sample >> (exponent + 3)) & 0x0F;
  ulawbyte = ~(sign | (exponent << 4) | mantissa);
#ifdef ZEROTRAP
  if (ulawbyte == 0) ulawbyte = 0x02;   /* optional CCITT trap */
#endif
  if (ulawbyte == 0xff) ulawbyte = 0x7f;   /* never return 0xff */
  return(ulawbyte);
}

#define AMI_MASK 0x55

#ifdef CONFIG_CALC_XLAW
unsigned char
#else
static inline unsigned char __init
#endif
__dahdi_lineartoalaw (short linear)
{
    int mask;
    int seg;
    int pcm_val;
    static int seg_end[8] =
    {
         0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF
    };

    pcm_val = linear;
    if (pcm_val >= 0)
    {
        /* Sign (7th) bit = 1 */
        mask = AMI_MASK | 0x80;
    }
    else
    {
        /* Sign bit = 0 */
        mask = AMI_MASK;
        pcm_val = -pcm_val;
    }

    /* Convert the scaled magnitude to segment number. */
    for (seg = 0;  seg < 8;  seg++)
    {
        if (pcm_val <= seg_end[seg])
	    break;
    }
    /* Combine the sign, segment, and quantization bits. */
    return  ((seg << 4) | ((pcm_val >> ((seg)  ?  (seg + 3)  :  4)) & 0x0F)) ^ mask;
}
/*- End of function --------------------------------------------------------*/

static inline short int __init alaw2linear (uint8_t alaw)
{
    int i;
    int seg;

    alaw ^= AMI_MASK;
    i = ((alaw & 0x0F) << 4);
    seg = (((int) alaw & 0x70) >> 4);
    if (seg)
        i = (i + 0x100) << (seg - 1);
    return (short int) ((alaw & 0x80)  ?  i  :  -i);
}
/*- End of function --------------------------------------------------------*/
static void  __init dahdi_conv_init(void)
{
	int i;

	/*
	 *  Set up mu-law conversion table
	 */
	for(i = 0;i < 256;i++)
	   {
		short mu,e,f,y;
		static short etab[]={0,132,396,924,1980,4092,8316,16764};

		mu = 255-i;
		e = (mu & 0x70)/16;
		f = mu & 0x0f;
		y = f * (1 << (e + 3));
		y += etab[e];
		if (mu & 0x80) y = -y;
	        __dahdi_mulaw[i] = y;
		__dahdi_alaw[i] = alaw2linear(i);
		/* Default (0.0 db) gain table */
		defgain[i] = i;
	   }
#ifndef CONFIG_CALC_XLAW
	  /* set up the reverse (mu-law) conversion table */
	for(i = -32768; i < 32768; i += 4)
	   {
		__dahdi_lin2mu[((unsigned short)(short)i) >> 2] = __dahdi_lineartoulaw(i);
		__dahdi_lin2a[((unsigned short)(short)i) >> 2] = __dahdi_lineartoalaw(i);
	   }
#endif
}

static inline void __dahdi_process_getaudio_chunk(struct dahdi_chan *ss, unsigned char *txb)
{
	/* We transmit data from our master channel */
	/* Called with ss->lock held */
	struct dahdi_chan *ms = ss->master;
	/* Linear representation */
	short getlin[DAHDI_CHUNKSIZE], k[DAHDI_CHUNKSIZE];
	int x;

	/* Okay, now we've got something to transmit */
	for (x=0;x<DAHDI_CHUNKSIZE;x++)
		getlin[x] = DAHDI_XLAW(txb[x], ms);

#ifndef CONFIG_DAHDI_NO_ECHOCAN_DISABLE
	if (ms->ec_state && (ms->ec_state->status.mode == ECHO_MODE_ACTIVE) && !ms->ec_state->features.CED_tx_detect) {
		for (x = 0; x < DAHDI_CHUNKSIZE; x++) {
			if (echo_can_disable_detector_update(&ms->ec_state->txecdis, getlin[x])) {
				set_echocan_fax_mode(ms, ss->channo, "CED tx detected", 1);
				dahdi_qevent_nolock(ms, DAHDI_EVENT_TX_CED_DETECTED);
				break;
			}
		}
	}
#endif

	if ((!ms->confmute && !ms->dialing) || (is_pseudo_chan(ms))) {
		struct dahdi_chan *const conf_chan = ms->conf_chan;
		/* Handle conferencing on non-clear channel and non-HDLC channels */
		switch(ms->confmode & DAHDI_CONF_MODE_MASK) {
		case DAHDI_CONF_NORMAL:
			/* Do nuffin */
			break;
		case DAHDI_CONF_MONITOR:	/* Monitor a channel's rx mode */
			  /* if a pseudo-channel, ignore */
			if (is_pseudo_chan(ms))
				break;
			/* Add monitored channel */
			if (is_pseudo_chan(conf_chan))
				ACSS(getlin, conf_chan->getlin);
			else
				ACSS(getlin, conf_chan->putlin);

			for (x=0;x<DAHDI_CHUNKSIZE;x++)
				txb[x] = DAHDI_LIN2X(getlin[x], ms);
			break;
		case DAHDI_CONF_MONITORTX: /* Monitor a channel's tx mode */
			  /* if a pseudo-channel, ignore */
			if (is_pseudo_chan(ms))
				break;
			/* Add monitored channel */
			if (is_pseudo_chan(conf_chan))
				ACSS(getlin, conf_chan->putlin);
			else
				ACSS(getlin, conf_chan->getlin);

			for (x=0;x<DAHDI_CHUNKSIZE;x++)
				txb[x] = DAHDI_LIN2X(getlin[x], ms);
			break;
		case DAHDI_CONF_MONITORBOTH: /* monitor a channel's rx and tx mode */
			  /* if a pseudo-channel, ignore */
			if (is_pseudo_chan(ms))
				break;
			ACSS(getlin, conf_chan->putlin);
			ACSS(getlin, conf_chan->getlin);
			for (x=0;x<DAHDI_CHUNKSIZE;x++)
				txb[x] = DAHDI_LIN2X(getlin[x], ms);
			break;
		case DAHDI_CONF_MONITOR_RX_PREECHO:	/* Monitor a channel's rx mode */
			  /* if a pseudo-channel, ignore */
			if (is_pseudo_chan(ms))
				break;

			if (!conf_chan->readchunkpreec)
				break;

			/* Add monitored channel */
			ACSS(getlin, is_pseudo_chan(conf_chan) ?
			     conf_chan->readchunkpreec : conf_chan->putlin);
			for (x = 0; x < DAHDI_CHUNKSIZE; x++)
				txb[x] = DAHDI_LIN2X(getlin[x], ms);

			break;
		case DAHDI_CONF_MONITOR_TX_PREECHO: /* Monitor a channel's tx mode */
			  /* if a pseudo-channel, ignore */
			if (is_pseudo_chan(ms))
				break;

			if (!conf_chan->readchunkpreec)
				break;

			/* Add monitored channel */
			ACSS(getlin, is_pseudo_chan(conf_chan) ?
			     conf_chan->putlin : conf_chan->readchunkpreec);
			for (x = 0; x < DAHDI_CHUNKSIZE; x++)
				txb[x] = DAHDI_LIN2X(getlin[x], ms);

			break;
		case DAHDI_CONF_MONITORBOTH_PREECHO: /* monitor a channel's rx and tx mode */
			  /* if a pseudo-channel, ignore */
			if (is_pseudo_chan(ms))
				break;

			if (!conf_chan->readchunkpreec)
				break;

			ACSS(getlin, conf_chan->putlin);
			ACSS(getlin, conf_chan->readchunkpreec);

			for (x = 0; x < DAHDI_CHUNKSIZE; x++)
				txb[x] = DAHDI_LIN2X(getlin[x], ms);

			break;
		case DAHDI_CONF_REALANDPSEUDO:
			/* This strange mode takes the transmit buffer and
				puts it on the conference, minus its last sample,
				then outputs from the conference minus the
				real channel's last sample. */
			  /* if to talk on conf */
			if (ms->confmode & DAHDI_CONF_PSEUDO_TALKER) {
				/* Store temp value */
				memcpy(k, getlin, DAHDI_CHUNKSIZE * sizeof(short));
				/* Add conf value */
				ACSS(k, conf_sums_next[ms->_confn]);
				/* save last one */
				memcpy(ms->conflast2, ms->conflast1, DAHDI_CHUNKSIZE * sizeof(short));
				memcpy(ms->conflast1, k, DAHDI_CHUNKSIZE * sizeof(short));
				/*  get amount actually added */
				SCSS(ms->conflast1, conf_sums_next[ms->_confn]);
				/* Really add in new value */
				ACSS(conf_sums_next[ms->_confn], ms->conflast1);
			} else {
				memset(ms->conflast1, 0, DAHDI_CHUNKSIZE * sizeof(short));
				memset(ms->conflast2, 0, DAHDI_CHUNKSIZE * sizeof(short));
			}
			memset(getlin, 0, DAHDI_CHUNKSIZE * sizeof(short));
			txb[0] = DAHDI_LIN2X(0, ms);
			memset(txb + 1, txb[0], DAHDI_CHUNKSIZE - 1);
			/* fall through to normal conf mode */
		case DAHDI_CONF_CONF:	/* Normal conference mode */
			if (is_pseudo_chan(ms)) /* if pseudo-channel */
			   {
				  /* if to talk on conf */
				if (ms->confmode & DAHDI_CONF_TALKER) {
					/* Store temp value */
					memcpy(k, getlin, DAHDI_CHUNKSIZE * sizeof(short));
					/* Add conf value */
					ACSS(k, conf_sums[ms->_confn]);
					/*  get amount actually added */
					memcpy(ms->conflast, k, DAHDI_CHUNKSIZE * sizeof(short));
					SCSS(ms->conflast, conf_sums[ms->_confn]);
					/* Really add in new value */
					ACSS(conf_sums[ms->_confn], ms->conflast);
					memcpy(ms->getlin, getlin, DAHDI_CHUNKSIZE * sizeof(short));
				} else {
					memset(ms->conflast, 0, DAHDI_CHUNKSIZE * sizeof(short));
					memcpy(getlin, ms->getlin, DAHDI_CHUNKSIZE * sizeof(short));
				}
				txb[0] = DAHDI_LIN2X(0, ms);
				memset(txb + 1, txb[0], DAHDI_CHUNKSIZE - 1);
				break;
		 	   }
			/* fall through */
		case DAHDI_CONF_CONFMON:	/* Conference monitor mode */
			if (ms->confmode & DAHDI_CONF_LISTENER) {
				/* Subtract out last sample written to conf */
				SCSS(getlin, ms->conflast);
				/* Add in conference */
				ACSS(getlin, conf_sums[ms->_confn]);
			}
			for (x=0;x<DAHDI_CHUNKSIZE;x++)
				txb[x] = DAHDI_LIN2X(getlin[x], ms);
			break;
		case DAHDI_CONF_CONFANN:
		case DAHDI_CONF_CONFANNMON:
			/* First, add tx buffer to conf */
			ACSS(conf_sums_next[ms->_confn], getlin);
			/* Start with silence */
			memset(getlin, 0, DAHDI_CHUNKSIZE * sizeof(short));
			/* If a listener on the conf... */
			if (ms->confmode & DAHDI_CONF_LISTENER) {
				/* Subtract last value written */
				SCSS(getlin, ms->conflast);
				/* Add in conf */
				ACSS(getlin, conf_sums[ms->_confn]);
			}
			for (x=0;x<DAHDI_CHUNKSIZE;x++)
				txb[x] = DAHDI_LIN2X(getlin[x], ms);
			break;
		case DAHDI_CONF_DIGITALMON:
			/* Real digital monitoring, but still echo cancel if
			 * desired */
			if (!conf_chan)
				break;
			if (is_pseudo_chan(conf_chan)) {
				if (ms->ec_state) {
					for (x = 0; x < DAHDI_CHUNKSIZE; x++)
						txb[x] = DAHDI_LIN2X(conf_chan->getlin[x], ms);
				} else {
					memcpy(txb, conf_chan->getraw, DAHDI_CHUNKSIZE);
				}
			} else {
				if (ms->ec_state) {
					for (x = 0; x < DAHDI_CHUNKSIZE; x++)
						txb[x] = DAHDI_LIN2X(conf_chan->putlin[x], ms);
				} else {
					memcpy(txb, conf_chan->putraw,
					       DAHDI_CHUNKSIZE);
				}
			}
			for (x = 0; x < DAHDI_CHUNKSIZE; x++)
				getlin[x] = DAHDI_XLAW(txb[x], ms);
			break;
		}
	}
	if (ms->confmute || (ms->ec_state && (ms->ec_state->status.mode) & __ECHO_MODE_MUTE)) {
		txb[0] = DAHDI_LIN2X(0, ms);
		memset(txb + 1, txb[0], DAHDI_CHUNKSIZE - 1);
		if (ms->ec_state && (ms->ec_state->status.mode == ECHO_MODE_STARTTRAINING)) {
			/* Transmit impulse now */
			txb[0] = DAHDI_LIN2X(16384, ms);
			ms->ec_state->status.mode = ECHO_MODE_AWAITINGECHO;
		}
	}
	/* save value from last chunk */
	memcpy(ms->getlin_lastchunk, ms->getlin, DAHDI_CHUNKSIZE * sizeof(short));
	/* save value from current */
	memcpy(ms->getlin, getlin, DAHDI_CHUNKSIZE * sizeof(short));
	/* save value from current */
	memcpy(ms->getraw, txb, DAHDI_CHUNKSIZE);
	/* if to make tx tone */
	if (ms->v1_1 || ms->v2_1 || ms->v3_1)
	{
		for (x=0;x<DAHDI_CHUNKSIZE;x++)
		{
			getlin[x] += dahdi_txtone_nextsample(ms);
			txb[x] = DAHDI_LIN2X(getlin[x], ms);
		}
	}
	/* This is what to send (after having applied gain) */
	for (x=0;x<DAHDI_CHUNKSIZE;x++)
		txb[x] = ms->txgain[txb[x]];
}

static void __putbuf_chunk(struct dahdi_chan *ss, unsigned char *rxb,
			   int bytes);

static inline void __dahdi_getbuf_chunk(struct dahdi_chan *ss, unsigned char *txb)
{


#ifdef CONFIG_DAHDI_MIRROR
	unsigned char *orig_txb = txb;
#endif /* CONFIG_DAHDI_MIRROR */

	/* Called with ss->lock held */
	/* We transmit data from our master channel */
	struct dahdi_chan *ms = ss->master;
	/* Buffer we're using */
	unsigned char *buf;
	/* Old buffer number */
	int oldbuf;
	/* Linear representation */
	int getlin;
	/* How many bytes we need to process */
	int bytes = DAHDI_CHUNKSIZE, left;
	bool needtxunderrun = false;
	int x;

	/* Let's pick something to transmit.  First source to
	   try is our write-out buffer.  Always check it first because
	   its our 'fast path' for whatever that's worth. */
	while(bytes) {
		if ((ms->outwritebuf > -1) && !ms->txdisable) {
			buf= ms->writebuf[ms->outwritebuf];
			left = ms->writen[ms->outwritebuf] - ms->writeidx[ms->outwritebuf];
			if (left > bytes)
				left = bytes;
			if (ms->flags & DAHDI_FLAG_HDLC) {
				/* If this is an HDLC channel we only send a byte of
				   HDLC. */
				for(x=0;x<left;x++) {
					if (fasthdlc_tx_need_data(&ms->txhdlc))
						/* Load a byte of data only if needed */
						fasthdlc_tx_load_nocheck(&ms->txhdlc, buf[ms->writeidx[ms->outwritebuf]++]);
					*(txb++) = fasthdlc_tx_run_nocheck(&ms->txhdlc);
				}
				bytes -= left;
			} else {
				memcpy(txb, buf + ms->writeidx[ms->outwritebuf], left);
				ms->writeidx[ms->outwritebuf]+=left;
				txb += left;
				bytes -= left;
			}
			/* Check buffer status */
			if (ms->writeidx[ms->outwritebuf] >= ms->writen[ms->outwritebuf]) {
				/* We've reached the end of our buffer.  Go to the next. */
				oldbuf = ms->outwritebuf;
				/* Clear out write index and such */
				ms->writeidx[oldbuf] = 0;
				ms->outwritebuf = (ms->outwritebuf + 1) % ms->numbufs;

				if (!(ms->flags & DAHDI_FLAG_MTP2)) {
					ms->writen[oldbuf] = 0;
					if (ms->outwritebuf == ms->inwritebuf) {
						/* Whoopsies, we're run out of buffers.  Mark ours
						as -1 and wait for the filler to notify us that
						there is something to write */
						ms->outwritebuf = -1;
						if (ms->iomask & (DAHDI_IOMUX_WRITE | DAHDI_IOMUX_WRITEEMPTY))
							wake_up_interruptible(&ms->waitq);
						/* If we're only supposed to start when full, disable the transmitter */
						if ((ms->txbufpolicy == DAHDI_POLICY_WHEN_FULL) ||
							(ms->txbufpolicy == DAHDI_POLICY_HALF_FULL))
							ms->txdisable = 1;
					}
				} else {
					if (ms->outwritebuf == ms->inwritebuf) {
						ms->outwritebuf = oldbuf;
						if (ms->iomask & (DAHDI_IOMUX_WRITE | DAHDI_IOMUX_WRITEEMPTY))
							wake_up_interruptible(&ms->waitq);
						/* If we're only supposed to start when full, disable the transmitter */
						if ((ms->txbufpolicy == DAHDI_POLICY_WHEN_FULL) ||
							(ms->txbufpolicy == DAHDI_POLICY_HALF_FULL))
							ms->txdisable = 1;
					}
				}
				if (ms->inwritebuf < 0) {
					/* The filler doesn't have a place to put data.  Now
					that we're done with this buffer, notify them. */
					ms->inwritebuf = oldbuf;
				}
/* In the very orignal driver, it was quite well known to me (Jim) that there
was a possibility that a channel sleeping on a write block needed to
be potentially woken up EVERY time a buffer was emptied, not just on the first
one, because if only done on the first one there is a slight timing potential
of missing the wakeup (between where it senses the (lack of) active condition
(with interrupts disabled) and where it does the sleep (interrupts enabled)
in the read or iomux call, etc). That is why the write and iomux calls start
with an infinite loop that gets broken out of upon an active condition,
otherwise keeps sleeping and looking. The part in this code got "optimized"
out in the later versions, and is put back now. */
				if (!(ms->flags & DAHDI_FLAG_PPP) ||
				    !dahdi_have_netdev(ms)) {
					wake_up_interruptible(&ms->waitq);
				}
				/* Transmit a flag if this is an HDLC channel */
				if (ms->flags & DAHDI_FLAG_HDLC)
					fasthdlc_tx_frame_nocheck(&ms->txhdlc);
#ifdef CONFIG_DAHDI_NET
				if (dahdi_have_netdev(ms))
					netif_wake_queue(chan_to_netdev(ms));
#endif
#ifdef CONFIG_DAHDI_PPP
				if (ms->flags & DAHDI_FLAG_PPP) {
					ms->do_ppp_wakeup = 1;
					tasklet_schedule(&ms->ppp_calls);
				}
#endif
			}
		} else if (ms->curtone && !is_pseudo_chan(ms)) {
			left = ms->curtone->tonesamples - ms->tonep;
			if (left > bytes)
				left = bytes;
			for (x=0;x<left;x++) {
				/* Pick our default value from the next sample of the current tone */
				getlin = dahdi_tone_nextsample(&ms->ts, ms->curtone);
				*(txb++) = DAHDI_LIN2X(getlin, ms);
			}
			ms->tonep+=left;
			bytes -= left;
			if (ms->tonep >= ms->curtone->tonesamples) {
				struct dahdi_tone *last;
				/* Go to the next sample of the tone */
				ms->tonep = 0;
				last = ms->curtone;
				ms->curtone = ms->curtone->next;
				if (!ms->curtone) {
					/* No more tones...  Is this dtmf or mf?  If so, go to the next digit */
					if (ms->dialing)
						__do_dtmf(ms);
				} else {
					if (last != ms->curtone)
						dahdi_init_tone_state(&ms->ts, ms->curtone);
				}
			}
		} else if (ms->flags & DAHDI_FLAG_LOOPED) {
			for (x = 0; x < bytes; x++)
				txb[x] = ms->readchunk[x];
			bytes = 0;
		} else if (ms->flags & DAHDI_FLAG_HDLC) {
			for (x=0;x<bytes;x++) {
				/* Okay, if we're HDLC, then transmit a flag by default */
				if (fasthdlc_tx_need_data(&ms->txhdlc))
					fasthdlc_tx_frame_nocheck(&ms->txhdlc);
				*(txb++) = fasthdlc_tx_run_nocheck(&ms->txhdlc);
			}
			bytes = 0;
		} else if (ms->flags & DAHDI_FLAG_CLEAR) {
			/* Clear channels that are idle in audio mode need
			   to send silence; in non-audio mode, always send 0xff
			   so stupid switches won't consider the channel active
			*/
			if (ms->flags & DAHDI_FLAG_AUDIO) {
				memset(txb, DAHDI_LIN2X(0, ms), bytes);
			} else {
				memset(txb, 0xFF, bytes);
			}
			needtxunderrun += bytes;
			bytes = 0;
		} else {
			memset(txb, DAHDI_LIN2X(0, ms), bytes);	/* Lastly we use silence on telephony channels */
			needtxunderrun += bytes;
			bytes = 0;
		}
	}

	if (needtxunderrun) {
		if (!test_bit(DAHDI_FLAGBIT_TXUNDERRUN, &ms->flags)) {
			if (test_bit(DAHDI_FLAGBIT_BUFEVENTS, &ms->flags))
				__qevent(ms, DAHDI_EVENT_WRITE_UNDERRUN);
			set_bit(DAHDI_FLAGBIT_TXUNDERRUN, &ms->flags);
		}
	} else {
		clear_bit(DAHDI_FLAGBIT_TXUNDERRUN, &ms->flags);
	}

#ifdef CONFIG_DAHDI_MIRROR
	if (ss->txmirror) {
		spin_lock(&ss->txmirror->lock);
		__putbuf_chunk(ss->txmirror, orig_txb, DAHDI_CHUNKSIZE);
		spin_unlock(&ss->txmirror->lock);
	}
#endif /* CONFIG_DAHDI_MIRROR */
}

static inline void rbs_itimer_expire(struct dahdi_chan *chan)
{
	/* the only way this could have gotten here, is if a channel
	    went onf hook longer then the wink or flash detect timeout */
	/* Called with chan->lock held */
	switch(chan->sig)
	{
	    case DAHDI_SIG_FXOLS:  /* if FXO, its definitely on hook */
	    case DAHDI_SIG_FXOGS:
	    case DAHDI_SIG_FXOKS:
		__qevent(chan,DAHDI_EVENT_ONHOOK);
		chan->gotgs = 0;
		break;
#if defined(EMFLASH) || defined(EMPULSE)
	    case DAHDI_SIG_EM:
	    case DAHDI_SIG_EM_E1:
		if (chan->rxhooksig == DAHDI_RXSIG_ONHOOK) {
			__qevent(chan,DAHDI_EVENT_ONHOOK);
			break;
		}
		__qevent(chan,DAHDI_EVENT_RINGOFFHOOK);
		break;
#endif
#ifdef	FXSFLASH
	    case DAHDI_SIG_FXSKS:
		if (chan->rxhooksig == DAHDI_RXSIG_ONHOOK) {
			__qevent(chan, DAHDI_EVENT_ONHOOK);
			break;
		}
#endif
		/* fall thru intentionally */
	    default:  /* otherwise, its definitely off hook */
		__qevent(chan,DAHDI_EVENT_RINGOFFHOOK);
		break;
	}
}

static inline void __rbs_otimer_expire(struct dahdi_chan *chan)
{
	int len = 0;
	/* Called with chan->lock held */

	chan->otimer = 0;
	/* Move to the next timer state */
	switch(chan->txstate) {
	case DAHDI_TXSTATE_RINGOFF:
		/* Turn on the ringer now that the silent time has passed */
		++chan->cadencepos;
		if (chan->cadencepos >= DAHDI_MAX_CADENCE)
			chan->cadencepos = chan->firstcadencepos;
		len = chan->ringcadence[chan->cadencepos];

		if (!len) {
			chan->cadencepos = chan->firstcadencepos;
			len = chan->ringcadence[chan->cadencepos];
		}

		dahdi_rbs_sethook(chan, DAHDI_TXSIG_START, DAHDI_TXSTATE_RINGON, len);
		__qevent(chan, DAHDI_EVENT_RINGERON);
		break;

	case DAHDI_TXSTATE_RINGON:
		/* Turn off the ringer now that the loud time has passed */
		++chan->cadencepos;
		if (chan->cadencepos >= DAHDI_MAX_CADENCE)
			chan->cadencepos = 0;
		len = chan->ringcadence[chan->cadencepos];

		if (!len) {
			chan->cadencepos = 0;
			len = chan->curzone->ringcadence[chan->cadencepos];
		}

		dahdi_rbs_sethook(chan, DAHDI_TXSIG_OFFHOOK, DAHDI_TXSTATE_RINGOFF, len);
		__qevent(chan, DAHDI_EVENT_RINGEROFF);
		break;

	case DAHDI_TXSTATE_START:
		/* If we were starting, go off hook now ready to debounce */
		dahdi_rbs_sethook(chan, DAHDI_TXSIG_OFFHOOK, DAHDI_TXSTATE_AFTERSTART, DAHDI_AFTERSTART_TIME);
		wake_up_interruptible(&chan->waitq);
		break;

	case DAHDI_TXSTATE_PREWINK:
		/* Actually wink */
		dahdi_rbs_sethook(chan, DAHDI_TXSIG_OFFHOOK, DAHDI_TXSTATE_WINK, chan->winktime);
		break;

	case DAHDI_TXSTATE_WINK:
		/* Wink complete, go on hook and stabalize */
		dahdi_rbs_sethook(chan, DAHDI_TXSIG_ONHOOK, DAHDI_TXSTATE_ONHOOK, 0);
		if (chan->file && (chan->file->f_flags & O_NONBLOCK))
			__qevent(chan, DAHDI_EVENT_HOOKCOMPLETE);
		wake_up_interruptible(&chan->waitq);
		break;

	case DAHDI_TXSTATE_PREFLASH:
		/* Actually flash */
		dahdi_rbs_sethook(chan, DAHDI_TXSIG_ONHOOK, DAHDI_TXSTATE_FLASH, chan->flashtime);
		break;

	case DAHDI_TXSTATE_FLASH:
		dahdi_rbs_sethook(chan, DAHDI_TXSIG_OFFHOOK, DAHDI_TXSTATE_OFFHOOK, 0);
		if (chan->file && (chan->file->f_flags & O_NONBLOCK))
			__qevent(chan, DAHDI_EVENT_HOOKCOMPLETE);
		wake_up_interruptible(&chan->waitq);
		break;

	case DAHDI_TXSTATE_DEBOUNCE:
		dahdi_rbs_sethook(chan, DAHDI_TXSIG_OFFHOOK, DAHDI_TXSTATE_OFFHOOK, 0);
		/* See if we've gone back on hook */
		if ((chan->rxhooksig == DAHDI_RXSIG_ONHOOK) && (chan->rxflashtime > 2))
			chan->itimerset = chan->itimer = chan->rxflashtime * DAHDI_CHUNKSIZE;
		wake_up_interruptible(&chan->waitq);
		break;

	case DAHDI_TXSTATE_AFTERSTART:
		dahdi_rbs_sethook(chan, DAHDI_TXSIG_OFFHOOK, DAHDI_TXSTATE_OFFHOOK, 0);
		if (chan->file && (chan->file->f_flags & O_NONBLOCK))
			__qevent(chan, DAHDI_EVENT_HOOKCOMPLETE);
		wake_up_interruptible(&chan->waitq);
		break;

	case DAHDI_TXSTATE_KEWL:
		dahdi_rbs_sethook(chan, DAHDI_TXSIG_ONHOOK, DAHDI_TXSTATE_AFTERKEWL, DAHDI_AFTERKEWLTIME);
		if (chan->file && (chan->file->f_flags & O_NONBLOCK))
			__qevent(chan, DAHDI_EVENT_HOOKCOMPLETE);
		wake_up_interruptible(&chan->waitq);
		break;

	case DAHDI_TXSTATE_AFTERKEWL:
		if (chan->kewlonhook)  {
			__qevent(chan,DAHDI_EVENT_ONHOOK);
		}
		chan->txstate = DAHDI_TXSTATE_ONHOOK;
		chan->gotgs = 0;
		break;

	case DAHDI_TXSTATE_PULSEBREAK:
		dahdi_rbs_sethook(chan, DAHDI_TXSIG_OFFHOOK, DAHDI_TXSTATE_PULSEMAKE,
			chan->pulsemaketime);
		wake_up_interruptible(&chan->waitq);
		break;

	case DAHDI_TXSTATE_PULSEMAKE:
		if (chan->pdialcount)
			chan->pdialcount--;
		if (chan->pdialcount)
		{
			dahdi_rbs_sethook(chan, DAHDI_TXSIG_ONHOOK,
				DAHDI_TXSTATE_PULSEBREAK, chan->pulsebreaktime);
			break;
		}
		chan->txstate = DAHDI_TXSTATE_PULSEAFTER;
		chan->otimer = chan->pulseaftertime * DAHDI_CHUNKSIZE;
		wake_up_interruptible(&chan->waitq);
		break;

	case DAHDI_TXSTATE_PULSEAFTER:
		chan->txstate = DAHDI_TXSTATE_OFFHOOK;
		__do_dtmf(chan);
		wake_up_interruptible(&chan->waitq);
		break;

	default:
		break;
	}
}

static void __dahdi_hooksig_pvt(struct dahdi_chan *chan, enum dahdi_rxsig rxsig)
{

	/* State machines for receive hookstate transitions
		called with chan->lock held */

	if ((chan->rxhooksig) == rxsig) return;

	if ((chan->flags & DAHDI_FLAG_SIGFREEZE)) return;

	chan->rxhooksig = rxsig;
#ifdef	RINGBEGIN
	if ((chan->sig & __DAHDI_SIG_FXS) && (rxsig == DAHDI_RXSIG_RING) &&
	    (!chan->ringdebtimer))
		__qevent(chan,DAHDI_EVENT_RINGBEGIN);
#endif
	switch(chan->sig) {
	    case DAHDI_SIG_EM:  /* E and M */
	    case DAHDI_SIG_EM_E1:
		switch(rxsig) {
		    case DAHDI_RXSIG_OFFHOOK: /* went off hook */
			/* The interface is going off hook */
#ifdef	EMFLASH
			if (chan->itimer)
			{
				__qevent(chan,DAHDI_EVENT_WINKFLASH);
				chan->itimerset = chan->itimer = 0;
				break;
			}
#endif
#ifdef EMPULSE
			if (chan->itimer) /* if timer still running */
			{
			    int plen = chan->itimerset - chan->itimer;
			    if (plen <= DAHDI_MAXPULSETIME)
			    {
					if (plen >= DAHDI_MINPULSETIME)
					{
						chan->pulsecount++;

						chan->pulsetimer = DAHDI_PULSETIMEOUT;
                                                chan->itimerset = chan->itimer = 0;
						if (chan->pulsecount == 1)
							__qevent(chan,DAHDI_EVENT_PULSE_START);
					}
			    }
			    break;
			}
#endif
			/* set wink timer */
			chan->itimerset = chan->itimer = chan->rxwinktime * DAHDI_CHUNKSIZE;
			break;
		    case DAHDI_RXSIG_ONHOOK: /* went on hook */
			/* This interface is now going on hook.
			   Check for WINK, etc */
			if (chan->itimer)
				__qevent(chan,DAHDI_EVENT_WINKFLASH);
#if defined(EMFLASH) || defined(EMPULSE)
			else {
#ifdef EMFLASH
				chan->itimerset = chan->itimer = chan->rxflashtime * DAHDI_CHUNKSIZE;

#else /* EMFLASH */
				chan->itimerset = chan->itimer = chan->rxwinktime * DAHDI_CHUNKSIZE;

#endif /* EMFLASH */
				chan->gotgs = 0;
				break;
			}
#else /* EMFLASH || EMPULSE */
			else {
				__qevent(chan,DAHDI_EVENT_ONHOOK);
				chan->gotgs = 0;
			}
#endif
			chan->itimerset = chan->itimer = 0;
			break;
		    default:
			break;
		}
		break;
	   case DAHDI_SIG_FXSKS:  /* FXS Kewlstart */
		  /* ignore a bit error if loop not closed and stable */
		if (chan->txstate != DAHDI_TXSTATE_OFFHOOK) break;
#ifdef	FXSFLASH
		if (rxsig == DAHDI_RXSIG_ONHOOK) {
			chan->itimer = DAHDI_FXSFLASHMAXTIME * DAHDI_CHUNKSIZE;
			break;
		} else 	if (rxsig == DAHDI_RXSIG_OFFHOOK) {
			if (chan->itimer) {
				/* did the offhook occur in the window? if not, ignore both events */
				if (chan->itimer <= ((DAHDI_FXSFLASHMAXTIME - DAHDI_FXSFLASHMINTIME) * DAHDI_CHUNKSIZE))
					__qevent(chan, DAHDI_EVENT_WINKFLASH);
			}
			chan->itimer = 0;
			break;
		}
#endif
		/* fall through intentionally */
	   case DAHDI_SIG_FXSGS:  /* FXS Groundstart */
		if (rxsig == DAHDI_RXSIG_ONHOOK) {
			chan->ringdebtimer = RING_DEBOUNCE_TIME;
			chan->ringtrailer = 0;
			if (chan->txstate != DAHDI_TXSTATE_DEBOUNCE) {
				chan->gotgs = 0;
				__qevent(chan,DAHDI_EVENT_ONHOOK);
			}
		}
		break;
	   case DAHDI_SIG_FXOGS: /* FXO Groundstart */
		if (rxsig == DAHDI_RXSIG_START) {
			  /* if havent got gs, report it */
			if (!chan->gotgs) {
				__qevent(chan,DAHDI_EVENT_RINGOFFHOOK);
				chan->gotgs = 1;
			}
		}
		/* fall through intentionally */
	   case DAHDI_SIG_FXOLS: /* FXO Loopstart */
	   case DAHDI_SIG_FXOKS: /* FXO Kewlstart */
		switch(rxsig) {
		    case DAHDI_RXSIG_OFFHOOK: /* went off hook */
			  /* if asserti ng ring, stop it */
			if (chan->txstate == DAHDI_TXSTATE_START) {
				dahdi_rbs_sethook(chan,DAHDI_TXSIG_OFFHOOK, DAHDI_TXSTATE_AFTERSTART, DAHDI_AFTERSTART_TIME);
			}
			chan->kewlonhook = 0;
#ifdef CONFIG_DAHDI_DEBUG
			module_printk(KERN_NOTICE, "Off hook on channel %d, itimer = %d, gotgs = %d\n", chan->channo, chan->itimer, chan->gotgs);
#endif
			if (chan->itimer) /* if timer still running */
			{
			    int plen = chan->itimerset - chan->itimer;
			    if (plen <= DAHDI_MAXPULSETIME)
			    {
					if (plen >= DAHDI_MINPULSETIME)
					{
						chan->pulsecount++;
						chan->pulsetimer = DAHDI_PULSETIMEOUT;
						chan->itimer = chan->itimerset;
						if (chan->pulsecount == 1)
							__qevent(chan,DAHDI_EVENT_PULSE_START);
					}
			    } else
					__qevent(chan,DAHDI_EVENT_WINKFLASH);
			} else {
				  /* if havent got GS detect */
				if (!chan->gotgs) {
					__qevent(chan,DAHDI_EVENT_RINGOFFHOOK);
					chan->gotgs = 1;
					chan->itimerset = chan->itimer = 0;
				}
			}
			chan->itimerset = chan->itimer = 0;
			break;
		    case DAHDI_RXSIG_ONHOOK: /* went on hook */
			  /* if not during offhook debounce time */
			if ((chan->txstate != DAHDI_TXSTATE_DEBOUNCE) &&
			    (chan->txstate != DAHDI_TXSTATE_KEWL) &&
			    (chan->txstate != DAHDI_TXSTATE_AFTERKEWL)) {
				chan->itimerset = chan->itimer = chan->rxflashtime * DAHDI_CHUNKSIZE;
			}
			if (chan->txstate == DAHDI_TXSTATE_KEWL)
				chan->kewlonhook = 1;
			break;
		    default:
			break;
		}
	    default:
		break;
	}
}

/**
 * dahdi_hooksig() - send a signal on a channel to userspace
 * @chan:	the DAHDI channel
 * @rxsig:	signal (number) to send
 *
 * Called from a channel driver to send a DAHDI signal to userspace.
 * The signal will be queued for delivery to userspace.
 *
 * If the signal is the same as previous one sent, it won't be re-sent.
 */
void dahdi_hooksig(struct dahdi_chan *chan, enum dahdi_rxsig rxsig)
{
	  /* skip if no change */
	unsigned long flags;
	spin_lock_irqsave(&chan->lock, flags);
	__dahdi_hooksig_pvt(chan,rxsig);
	spin_unlock_irqrestore(&chan->lock, flags);
}


/**
 * dahdi_rbsbits() - set Rx RBS bits on the channel
 * @chan:	the DAHDI channel
 * @cursig:	the bits to set
 *
 * Set the channel's rxsig (received: from device to userspace) and act
 * accordingly.
 */
void dahdi_rbsbits(struct dahdi_chan *chan, int cursig)
{
	unsigned long flags;
	if (cursig == chan->rxsig)
		return;

	if ((chan->flags & DAHDI_FLAG_SIGFREEZE)) return;

	spin_lock_irqsave(&chan->lock, flags);
	switch(chan->sig) {
	    case DAHDI_SIG_FXOGS: /* FXO Groundstart */
		/* B-bit only matters for FXO GS */
		if (!(cursig & DAHDI_BBIT)) {
			__dahdi_hooksig_pvt(chan, DAHDI_RXSIG_START);
			break;
		}
		/* Fall through */
	    case DAHDI_SIG_EM:  /* E and M */
	    case DAHDI_SIG_EM_E1:
	    case DAHDI_SIG_FXOLS: /* FXO Loopstart */
	    case DAHDI_SIG_FXOKS: /* FXO Kewlstart */
		if (cursig & DAHDI_ABIT)  /* off hook */
			__dahdi_hooksig_pvt(chan,DAHDI_RXSIG_OFFHOOK);
		else /* on hook */
			__dahdi_hooksig_pvt(chan,DAHDI_RXSIG_ONHOOK);
		break;

	   case DAHDI_SIG_FXSKS:  /* FXS Kewlstart */
	   case DAHDI_SIG_FXSGS:  /* FXS Groundstart */
		/* Fall through */
	   case DAHDI_SIG_FXSLS:
		if (!(cursig & DAHDI_BBIT)) {
			/* Check for ringing first */
			__dahdi_hooksig_pvt(chan, DAHDI_RXSIG_RING);
			break;
		}
		if ((chan->sig != DAHDI_SIG_FXSLS) && (cursig & DAHDI_ABIT)) {
			    /* if went on hook */
			__dahdi_hooksig_pvt(chan, DAHDI_RXSIG_ONHOOK);
		} else {
			__dahdi_hooksig_pvt(chan, DAHDI_RXSIG_OFFHOOK);
		}
		break;
	   case DAHDI_SIG_CAS:
		/* send event that something changed */
		__qevent(chan, DAHDI_EVENT_BITSCHANGED);
		break;

	   default:
		break;
	}
	/* Keep track of signalling for next time */
	chan->rxsig = cursig;
	spin_unlock_irqrestore(&chan->lock, flags);

	if ((debug & DEBUG_RBS) && printk_ratelimit()) {
		chan_notice(chan, "Detected sigbits change to %04x\n", cursig);
	}
}

static void process_echocan_events(struct dahdi_chan *chan)
{
	union dahdi_echocan_events events = chan->ec_state->events;

	if (events.bit.CED_tx_detected) {
		dahdi_qevent_nolock(chan, DAHDI_EVENT_TX_CED_DETECTED);
		if (chan->ec_state) {
			if (chan->ec_state->status.mode == ECHO_MODE_ACTIVE)
				set_echocan_fax_mode(chan, chan->channo, "CED tx detected", 1);
			else
				module_printk(KERN_NOTICE, "Detected CED tone (tx) on channel %d\n", chan->channo);
		}
	}

	if (events.bit.CED_rx_detected) {
		dahdi_qevent_nolock(chan, DAHDI_EVENT_RX_CED_DETECTED);
		if (chan->ec_state) {
			if (chan->ec_state->status.mode == ECHO_MODE_ACTIVE)
				set_echocan_fax_mode(chan, chan->channo, "CED rx detected", 1);
			else
				module_printk(KERN_NOTICE, "Detected CED tone (rx) on channel %d\n", chan->channo);
		}
	}

	if (events.bit.CNG_tx_detected)
		dahdi_qevent_nolock(chan, DAHDI_EVENT_TX_CNG_DETECTED);

	if (events.bit.CNG_rx_detected)
		dahdi_qevent_nolock(chan, DAHDI_EVENT_RX_CNG_DETECTED);

	if (events.bit.NLP_auto_disabled) {
		dahdi_qevent_nolock(chan, DAHDI_EVENT_EC_NLP_DISABLED);
		chan->ec_state->status.mode = ECHO_MODE_FAX;
	}

	if (events.bit.NLP_auto_enabled) {
		dahdi_qevent_nolock(chan, DAHDI_EVENT_EC_NLP_ENABLED);
		chan->ec_state->status.mode = ECHO_MODE_ACTIVE;
	}
}

static void
__dahdi_ec_chunk(struct dahdi_chan *ss, u8 *rxchunk, const u8 *txchunk)
{
	short rxlin, txlin;
	int x;

	if (ss->readchunkpreec) {
		/* Save a copy of the audio before the echo can has its way with it */
		for (x = 0; x < DAHDI_CHUNKSIZE; x++)
			/* We only ever really need to deal with signed linear - let's just convert it now */
			ss->readchunkpreec[x] = DAHDI_XLAW(rxchunk[x], ss);
	}

	/* Perform echo cancellation on a chunk if necessary */
	if (ss->ec_state) {
#if defined(CONFIG_DAHDI_MMX) || defined(ECHO_CAN_FP)
		dahdi_kernel_fpu_begin();
#endif
		if (ss->ec_state->status.mode & __ECHO_MODE_MUTE) {
			/* Special stuff for training the echo can */
			for (x=0;x<DAHDI_CHUNKSIZE;x++) {
				rxlin = DAHDI_XLAW(rxchunk[x], ss);
				txlin = DAHDI_XLAW(txchunk[x], ss);
				if (ss->ec_state->status.mode == ECHO_MODE_PRETRAINING) {
					if (--ss->ec_state->status.pretrain_timer <= 0) {
						ss->ec_state->status.pretrain_timer = 0;
						ss->ec_state->status.mode = ECHO_MODE_STARTTRAINING;
					}
				}
				if (ss->ec_state->status.mode == ECHO_MODE_AWAITINGECHO) {
					ss->ec_state->status.last_train_tap = 0;
					ss->ec_state->status.mode = ECHO_MODE_TRAINING;
				}
				if ((ss->ec_state->status.mode == ECHO_MODE_TRAINING) &&
				    (ss->ec_state->ops->echocan_traintap)) {
					if (ss->ec_state->ops->echocan_traintap(ss->ec_state, ss->ec_state->status.last_train_tap++, rxlin)) {
						ss->ec_state->status.mode = ECHO_MODE_ACTIVE;
					}
				}
				rxlin = 0;
				rxchunk[x] = DAHDI_LIN2X((int)rxlin, ss);
			}
		} else if (ss->ec_state->status.mode != ECHO_MODE_IDLE) {
			ss->ec_state->events.all = 0;

			if (ss->ec_state->ops->echocan_process) {
				short rxlins[DAHDI_CHUNKSIZE], txlins[DAHDI_CHUNKSIZE];

				for (x = 0; x < DAHDI_CHUNKSIZE; x++) {
					rxlins[x] = DAHDI_XLAW(rxchunk[x], ss);
					txlins[x] = DAHDI_XLAW(txchunk[x], ss);
				}
				ss->ec_state->ops->echocan_process(ss->ec_state, rxlins, txlins, DAHDI_CHUNKSIZE);

				for (x = 0; x < DAHDI_CHUNKSIZE; x++)
					rxchunk[x] = DAHDI_LIN2X((int) rxlins[x], ss);
			} else if (ss->ec_state->ops->echocan_events)
				ss->ec_state->ops->echocan_events(ss->ec_state);

			if (ss->ec_state->events.all)
				process_echocan_events(ss);

		}
#if defined(CONFIG_DAHDI_MMX) || defined(ECHO_CAN_FP)
		dahdi_kernel_fpu_end();
#endif
	}
}

/**
 * _dahdi_ec_chunk() - process echo for a single channel
 * @ss:		DAHDI channel
 * @rxchunk:	chunk of audio on which to cancel echo
 * @txchunk:	reference chunk from the other direction
 *
 * The echo canceller function fixes received (from device to userspace)
 * audio. In order to fix it it uses the transmitted audio as a
 * reference. This call updates the echo canceller for a single chunk (8
 * bytes).
 *
 * Call with local interrupts disabled.
 */
void _dahdi_ec_chunk(struct dahdi_chan *ss, u8 *rxchunk, const u8 *txchunk)
{
	spin_lock(&ss->lock);
	__dahdi_ec_chunk(ss, rxchunk, txchunk);
	spin_unlock(&ss->lock);
}
EXPORT_SYMBOL(_dahdi_ec_chunk);

/**
 * dahdi_ec_span() - process echo for all channels in a span.
 * @span:	DAHDI span
 *
 * Similar to calling dahdi_ec_chunk() for each of the channels in the
 * span. Uses dahdi_chunk.write_chunk for the rxchunk (the chunk to fix)
 * and dahdi_chan.readchunk as the txchunk (the reference chunk).
 */
void _dahdi_ec_span(struct dahdi_span *span)
{
	int x;
	for (x = 0; x < span->channels; x++) {
		if (span->chans[x]->ec_current) {
			spin_lock(&span->chans[x]->lock);
			__dahdi_ec_chunk(span->chans[x], span->chans[x]->readchunk, span->chans[x]->writechunk);
			spin_unlock(&span->chans[x]->lock);
		}
	}
}
EXPORT_SYMBOL(_dahdi_ec_span);

/* return 0 if nothing detected, 1 if lack of tone, 2 if presence of tone */
/* modifies buffer pointed to by 'amp' with notched-out values */
static inline int sf_detect(struct sf_detect_state *s,
                 short *amp,
                 int samples,long p1, long p2, long p3)
{
int     i,rv = 0;
long x,y;

#define	SF_DETECT_SAMPLES (DAHDI_CHUNKSIZE * 5)
#define	SF_DETECT_MIN_ENERGY 500
#define	NB 14  /* number of bits to shift left */

        /* determine energy level before filtering */
        for(i = 0; i < samples; i++)
        {
                if (amp[i] < 0) s->e1 -= amp[i];
                else s->e1 += amp[i];
        }
	/* do 2nd order IIR notch filter at given freq. and calculate
	    energy */
        for(i = 0; i < samples; i++)
        {
                x = amp[i] << NB;
                y = s->x2 + (p1 * (s->x1 >> NB)) + x;
                y += (p2 * (s->y2 >> NB)) +
			(p3 * (s->y1 >> NB));
                s->x2 = s->x1;
                s->x1 = x;
                s->y2 = s->y1;
                s->y1 = y;
                amp[i] = y >> NB;
                if (amp[i] < 0) s->e2 -= amp[i];
                else s->e2 += amp[i];
        }
	s->samps += i;
	/* if time to do determination */
	if ((s->samps) >= SF_DETECT_SAMPLES)
	{
		rv = 1; /* default to no tone */
		/* if enough energy, it is determined to be a tone */
		if (((s->e1 - s->e2) / s->samps) > SF_DETECT_MIN_ENERGY) rv = 2;
		/* reset energy processing variables */
		s->samps = 0;
		s->e1 = s->e2 = 0;
	}
	return(rv);
}

static inline void __dahdi_process_putaudio_chunk(struct dahdi_chan *ss, unsigned char *rxb)
{
	/* We transmit data from our master channel */
	/* Called with ss->lock held */
	struct dahdi_chan *ms = ss->master;
	/* Linear version of received data */
	short putlin[DAHDI_CHUNKSIZE],k[DAHDI_CHUNKSIZE];
	int x,r;

	if (ms->dialing) ms->afterdialingtimer = 50;
	else if (ms->afterdialingtimer) ms->afterdialingtimer--;
	if (ms->afterdialingtimer && !is_pseudo_chan(ms)) {
		/* Be careful since memset is likely a macro */
		rxb[0] = DAHDI_LIN2X(0, ms);
		memset(&rxb[1], rxb[0], DAHDI_CHUNKSIZE - 1);  /* receive as silence if dialing */
	}
	for (x=0;x<DAHDI_CHUNKSIZE;x++) {
		rxb[x] = ms->rxgain[rxb[x]];
		putlin[x] = DAHDI_XLAW(rxb[x], ms);
	}

#ifndef CONFIG_DAHDI_NO_ECHOCAN_DISABLE
	if (ms->ec_state && (ms->ec_state->status.mode == ECHO_MODE_ACTIVE) && !ms->ec_state->features.CED_rx_detect) {
		for (x = 0; x < DAHDI_CHUNKSIZE; x++) {
			if (echo_can_disable_detector_update(&ms->ec_state->rxecdis, putlin[x])) {
				set_echocan_fax_mode(ms, ss->channo, "CED rx detected", 1);
				dahdi_qevent_nolock(ms, DAHDI_EVENT_RX_CED_DETECTED);
				break;
			}
		}
	}
#endif

	/* if doing rx tone decoding */
	if (ms->rxp1 && ms->rxp2 && ms->rxp3)
	{
		r = sf_detect(&ms->rd,putlin,DAHDI_CHUNKSIZE,ms->rxp1,
			ms->rxp2,ms->rxp3);
		/* Convert back */
		for(x=0;x<DAHDI_CHUNKSIZE;x++)
			rxb[x] = DAHDI_LIN2X(putlin[x], ms);
		if (r) /* if something happened */
		{
			if (r != ms->rd.lastdetect)
			{
				if (((r == 2) && !(ms->toneflags & DAHDI_REVERSE_RXTONE)) ||
				    ((r == 1) && (ms->toneflags & DAHDI_REVERSE_RXTONE)))
				{
					__qevent(ms,DAHDI_EVENT_RINGOFFHOOK);
				}
				else
				{
					__qevent(ms,DAHDI_EVENT_ONHOOK);
				}
				ms->rd.lastdetect = r;
			}
		}
	}

	if (!is_pseudo_chan(ms)) {
		memcpy(ms->putlin, putlin, DAHDI_CHUNKSIZE * sizeof(short));
		memcpy(ms->putraw, rxb, DAHDI_CHUNKSIZE);
	}

	/* Take the rxc, twiddle it for conferencing if appropriate and put it
	   back */
	if ((!ms->confmute && !ms->afterdialingtimer) || is_pseudo_chan(ms)) {
		struct dahdi_chan *const conf_chan = ms->conf_chan;
		switch(ms->confmode & DAHDI_CONF_MODE_MASK) {
		case DAHDI_CONF_NORMAL:		/* Normal mode */
			/* Do nothing.  rx goes output */
			break;
		case DAHDI_CONF_MONITOR:		/* Monitor a channel's rx mode */
			  /* if not a pseudo-channel, ignore */
			if (!is_pseudo_chan(ms))
				break;
			/* Add monitored channel */
			if (is_pseudo_chan(conf_chan))
				ACSS(putlin, conf_chan->getlin);
			else
				ACSS(putlin, conf_chan->putlin);
			/* Convert back */
			for(x=0;x<DAHDI_CHUNKSIZE;x++)
				rxb[x] = DAHDI_LIN2X(putlin[x], ms);
			break;
		case DAHDI_CONF_MONITORTX:	/* Monitor a channel's tx mode */
			  /* if not a pseudo-channel, ignore */
			if (!is_pseudo_chan(ms))
				break;
			/* Add monitored channel */
			if (is_pseudo_chan(conf_chan))
				ACSS(putlin, conf_chan->putlin);
			else
				ACSS(putlin, conf_chan->getlin);
			/* Convert back */
			for(x=0;x<DAHDI_CHUNKSIZE;x++)
				rxb[x] = DAHDI_LIN2X(putlin[x], ms);
			break;
		case DAHDI_CONF_MONITORBOTH:	/* Monitor a channel's tx and rx mode */
			  /* if not a pseudo-channel, ignore */
			if (!is_pseudo_chan(ms))
				break;
			/* Note: Technically, saturation should be done at
			   the end of the whole addition, but for performance
			   reasons, we don't do that.  Besides, it only matters
			   when you're so loud you're clipping anyway */
			ACSS(putlin, conf_chan->getlin);
			ACSS(putlin, conf_chan->putlin);
			/* Convert back */
			for(x=0;x<DAHDI_CHUNKSIZE;x++)
				rxb[x] = DAHDI_LIN2X(putlin[x], ms);
			break;
		case DAHDI_CONF_MONITOR_RX_PREECHO:		/* Monitor a channel's rx mode */
			  /* if not a pseudo-channel, ignore */
			if (!is_pseudo_chan(ms))
				break;

			if (!conf_chan->readchunkpreec)
				break;

			/* Add monitored channel */
			ACSS(putlin, is_pseudo_chan(conf_chan) ?
			     conf_chan->getlin : conf_chan->readchunkpreec);
			for (x = 0; x < DAHDI_CHUNKSIZE; x++)
				rxb[x] = DAHDI_LIN2X(putlin[x], ms);

			break;
		case DAHDI_CONF_MONITOR_TX_PREECHO:	/* Monitor a channel's tx mode */
			  /* if not a pseudo-channel, ignore */
			if (!is_pseudo_chan(ms))
				break;

			if (!conf_chan->readchunkpreec)
				break;

			/* Add monitored channel */
			ACSS(putlin, is_pseudo_chan(conf_chan) ?
			     conf_chan->readchunkpreec : conf_chan->getlin);
			for (x = 0; x < DAHDI_CHUNKSIZE; x++)
				rxb[x] = DAHDI_LIN2X(putlin[x], ms);

			break;
		case DAHDI_CONF_MONITORBOTH_PREECHO:	/* Monitor a channel's tx and rx mode */
			  /* if not a pseudo-channel, ignore */
			if (!is_pseudo_chan(ms))
				break;

			if (!conf_chan->readchunkpreec)
				break;

			/* Note: Technically, saturation should be done at
			   the end of the whole addition, but for performance
			   reasons, we don't do that.  Besides, it only matters
			   when you're so loud you're clipping anyway */
			ACSS(putlin, conf_chan->getlin);
			ACSS(putlin, conf_chan->readchunkpreec);
			for (x = 0; x < DAHDI_CHUNKSIZE; x++)
				rxb[x] = DAHDI_LIN2X(putlin[x], ms);

			break;
		case DAHDI_CONF_REALANDPSEUDO:
			  /* do normal conf mode processing */
			if (ms->confmode & DAHDI_CONF_TALKER) {
				/* Store temp value */
				memcpy(k, putlin, DAHDI_CHUNKSIZE * sizeof(short));
				/* Add conf value */
				ACSS(k, conf_sums_next[ms->_confn]);
				/*  get amount actually added */
				memcpy(ms->conflast, k, DAHDI_CHUNKSIZE * sizeof(short));
				SCSS(ms->conflast, conf_sums_next[ms->_confn]);
				/* Really add in new value */
				ACSS(conf_sums_next[ms->_confn], ms->conflast);
			} else memset(ms->conflast, 0, DAHDI_CHUNKSIZE * sizeof(short));
			  /* do the pseudo-channel part processing */
			memset(putlin, 0, DAHDI_CHUNKSIZE * sizeof(short));
			if (ms->confmode & DAHDI_CONF_PSEUDO_LISTENER) {
				/* Subtract out previous last sample written to conf */
				SCSS(putlin, ms->conflast2);
				/* Add in conference */
				ACSS(putlin, conf_sums[ms->_confn]);
			}
			/* Convert back */
			for(x=0;x<DAHDI_CHUNKSIZE;x++)
				rxb[x] = DAHDI_LIN2X(putlin[x], ms);
			break;
		case DAHDI_CONF_CONF:	/* Normal conference mode */
			if (is_pseudo_chan(ms)) /* if a pseudo-channel */
			   {
				if (ms->confmode & DAHDI_CONF_LISTENER) {
					/* Subtract out last sample written to conf */
					SCSS(putlin, ms->conflast);
					/* Add in conference */
					ACSS(putlin, conf_sums[ms->_confn]);
				}
				/* Convert back */
				for(x=0;x<DAHDI_CHUNKSIZE;x++)
					rxb[x] = DAHDI_LIN2X(putlin[x], ms);
				memcpy(ss->putlin, putlin, DAHDI_CHUNKSIZE * sizeof(short));
				break;
			   }
			/* fall through */
		case DAHDI_CONF_CONFANN:  /* Conference with announce */
			if (ms->confmode & DAHDI_CONF_TALKER) {
				/* Store temp value */
				memcpy(k, putlin, DAHDI_CHUNKSIZE * sizeof(short));
				/* Add conf value */
				ACSS(k, conf_sums_next[ms->_confn]);
				/*  get amount actually added */
				memcpy(ms->conflast, k, DAHDI_CHUNKSIZE * sizeof(short));
				SCSS(ms->conflast, conf_sums_next[ms->_confn]);
				/* Really add in new value */
				ACSS(conf_sums_next[ms->_confn], ms->conflast);
			} else
				memset(ms->conflast, 0, DAHDI_CHUNKSIZE * sizeof(short));
			  /* rxc unmodified */
			break;
		case DAHDI_CONF_CONFMON:
		case DAHDI_CONF_CONFANNMON:
			if (ms->confmode & DAHDI_CONF_TALKER) {
				/* Store temp value */
				memcpy(k, putlin, DAHDI_CHUNKSIZE * sizeof(short));
				/* Subtract last value */
				SCSS(conf_sums[ms->_confn], ms->conflast);
				/* Add conf value */
				ACSS(k, conf_sums[ms->_confn]);
				/*  get amount actually added */
				memcpy(ms->conflast, k, DAHDI_CHUNKSIZE * sizeof(short));
				SCSS(ms->conflast, conf_sums[ms->_confn]);
				/* Really add in new value */
				ACSS(conf_sums[ms->_confn], ms->conflast);
			} else
				memset(ms->conflast, 0, DAHDI_CHUNKSIZE * sizeof(short));
			for (x=0;x<DAHDI_CHUNKSIZE;x++)
				rxb[x] = DAHDI_LIN2X((int)conf_sums_prev[ms->_confn][x], ms);
			break;
		case DAHDI_CONF_DIGITALMON:
			  /* if not a pseudo-channel, ignore */
			if (!is_pseudo_chan(ms))
				break;
			/* Add monitored channel */
			if (is_pseudo_chan(conf_chan))
				memcpy(rxb, conf_chan->getraw, DAHDI_CHUNKSIZE);
			else
				memcpy(rxb, conf_chan->putraw, DAHDI_CHUNKSIZE);
			break;
		}
	}
}

/* HDLC (or other) receiver buffer functions for read side */
static void __putbuf_chunk(struct dahdi_chan *ss, unsigned char *rxb, int bytes)
{
	/* We transmit data from our master channel */
	/* Called with ss->lock held */
	struct dahdi_chan *ms = ss->master;
	/* Our receive buffer */
	unsigned char *buf;
#if defined(CONFIG_DAHDI_NET)  || defined(CONFIG_DAHDI_PPP)
	/* SKB for receiving network stuff */
	struct sk_buff *skb=NULL;
#endif
	int oldbuf;
	int eof=0;
	int abort=0;
	int res;
	int left, x;

	while(bytes) {
#if defined(CONFIG_DAHDI_NET)  || defined(CONFIG_DAHDI_PPP)
		skb = NULL;
#endif
		abort = 0;
		eof = 0;
		/* Next, figure out if we've got a buffer to receive into */
		if (ms->inreadbuf > -1) {
			/* Read into the current buffer */
			buf = ms->readbuf[ms->inreadbuf];
			left = ms->blocksize - ms->readidx[ms->inreadbuf];
			if (left > bytes)
				left = bytes;
			if (ms->flags & DAHDI_FLAG_HDLC) {
				for (x=0;x<left;x++) {
					/* Handle HDLC deframing */
					fasthdlc_rx_load_nocheck(&ms->rxhdlc, *(rxb++));
					bytes--;
					res = fasthdlc_rx_run(&ms->rxhdlc);
					/* If there is nothing there, continue */
					if (res & RETURN_EMPTY_FLAG)
						continue;
					else if (res & RETURN_COMPLETE_FLAG) {
						/* Only count this if it's a non-empty frame */
						if (ms->readidx[ms->inreadbuf]) {
							if ((ms->flags & DAHDI_FLAG_FCS) && (ms->infcs != PPP_GOODFCS)) {
								abort = DAHDI_EVENT_BADFCS;
							} else
								eof=1;
							break;
						}
						continue;
					} else if (res & RETURN_DISCARD_FLAG) {
						/* This could be someone idling with
						  "idle" instead of "flag" */
						if (!ms->readidx[ms->inreadbuf])
							continue;
						abort = DAHDI_EVENT_ABORT;
						break;
					} else {
						unsigned char rxc;
						rxc = res;
						ms->infcs = PPP_FCS(ms->infcs, rxc);
						buf[ms->readidx[ms->inreadbuf]++] = rxc;
						/* Pay attention to the possibility of an overrun */
						if (ms->readidx[ms->inreadbuf] >= ms->blocksize) {
							if (!ss->span->alarms)
								module_printk(KERN_WARNING, "HDLC Receiver overrun on channel %s (master=%s)\n", ss->name, ss->master->name);
							abort=DAHDI_EVENT_OVERRUN;
							/* Force the HDLC state back to frame-search mode */
							ms->rxhdlc.state = 0;
							ms->rxhdlc.bits = 0;
							ms->readidx[ms->inreadbuf]=0;
							break;
						}
					}
				}
			} else {
				/* Not HDLC */
				memcpy(buf + ms->readidx[ms->inreadbuf], rxb, left);
				rxb += left;
				ms->readidx[ms->inreadbuf] += left;
				bytes -= left;
				/* End of frame is decided by block size of 'N' */
				eof = (ms->readidx[ms->inreadbuf] >= ms->blocksize);
				if (eof && (ss->flags & DAHDI_FLAG_NOSTDTXRX)) {
					eof = 0;
					abort = DAHDI_EVENT_OVERRUN;
				}
			}
			if (eof)  {
				/* Finished with this buffer, try another. */
				oldbuf = ms->inreadbuf;
				ms->infcs = PPP_INITFCS;
				ms->readn[ms->inreadbuf] = ms->readidx[ms->inreadbuf];
#ifdef CONFIG_DAHDI_DEBUG
				module_printk(KERN_NOTICE, "EOF, len is %d\n", ms->readn[ms->inreadbuf]);
#endif
#if defined(CONFIG_DAHDI_NET) || defined(CONFIG_DAHDI_PPP)
				if ((ms->flags & DAHDI_FLAG_PPP) ||
				    dahdi_have_netdev(ms)) {
#ifdef CONFIG_DAHDI_NET
#endif /* CONFIG_DAHDI_NET */
					/* Our network receiver logic is MUCH
					  different.  We actually only use a single
					  buffer */
					if (ms->readn[ms->inreadbuf] > 1) {
						/* Drop the FCS */
						ms->readn[ms->inreadbuf] -= 2;
						/* Allocate an SKB */
#ifdef CONFIG_DAHDI_PPP
						if (!ms->do_ppp_error)
#endif
							skb = dev_alloc_skb(ms->readn[ms->inreadbuf] + 2);
						if (skb) {
							unsigned char cisco_addr = *(ms->readbuf[ms->inreadbuf]);
							if (cisco_addr != 0x0f && cisco_addr != 0x8f)
								skb_reserve(skb, 2);
							/* XXX Get rid of this memcpy XXX */
							memcpy(skb->data, ms->readbuf[ms->inreadbuf], ms->readn[ms->inreadbuf]);
							skb_put(skb, ms->readn[ms->inreadbuf]);
#ifdef CONFIG_DAHDI_NET
							if (dahdi_have_netdev(ms)) {
								struct net_device_stats *stats = hdlc_stats(ms->hdlcnetdev->netdev);
								stats->rx_packets++;
								stats->rx_bytes += ms->readn[ms->inreadbuf];
							}
#endif

						} else {
#ifdef CONFIG_DAHDI_NET
							if (dahdi_have_netdev(ms)) {
								struct net_device_stats *stats = hdlc_stats(ms->hdlcnetdev->netdev);
								stats->rx_dropped++;
							}
#endif
#ifdef CONFIG_DAHDI_PPP
							if (ms->flags & DAHDI_FLAG_PPP) {
								abort = DAHDI_EVENT_OVERRUN;
							}
#endif
#if 1
#ifdef CONFIG_DAHDI_PPP
							if (!ms->do_ppp_error)
#endif
								module_printk(KERN_NOTICE, "Memory squeeze, dropped one\n");
#endif
						}
					}
					/* We don't cycle through buffers, just
					reuse the same one */
					ms->readn[ms->inreadbuf] = 0;
					ms->readidx[ms->inreadbuf] = 0;
				} else
#endif
				{
					/* This logic might confuse and astound.  Basically we need to find
					 * the previous buffer index.  It should be safe because, regardless
					 * of whether or not it has been copied to user space, nothing should
					 * have messed around with it since then */

					int comparemessage;
					/* Shut compiler up */
					int myres = 0;

					if (ms->flags & DAHDI_FLAG_MTP2) {
						comparemessage = (ms->inreadbuf - 1) & (ms->numbufs - 1);

						myres = memcmp(ms->readbuf[comparemessage], ms->readbuf[ms->inreadbuf], ms->readn[ms->inreadbuf]);
					}

					if ((ms->flags & DAHDI_FLAG_MTP2) && !myres) {
						/* Our messages are the same, so discard -
						 * 	Don't advance buffers, reset indexes and buffer sizes. */
						ms->readn[ms->inreadbuf] = 0;
						ms->readidx[ms->inreadbuf] = 0;
					} else {
						ms->inreadbuf = (ms->inreadbuf + 1) % ms->numbufs;
						if (ms->inreadbuf == ms->outreadbuf) {
							/* Whoops, we're full, and have no where else
							   to store into at the moment.  We'll drop it
							   until there's a buffer available */
#ifdef BUFFER_DEBUG
							module_printk(KERN_NOTICE, "Out of storage space\n");
#endif
							ms->inreadbuf = -1;
							/* Enable the receiver in case they've got POLICY_WHEN_FULL */
							ms->rxdisable = 0;
						}
						if (ms->outreadbuf < 0) { /* start out buffer if not already */
							ms->outreadbuf = oldbuf;
							/* if there are processes waiting in poll() on this channel,
							   wake them up */
							if (!ms->rxdisable) {
								wake_up_interruptible(&ms->waitq);
							}
						}
/* In the very orignal driver, it was quite well known to me (Jim) that there
was a possibility that a channel sleeping on a receive block needed to
be potentially woken up EVERY time a buffer was filled, not just on the first
one, because if only done on the first one there is a slight timing potential
of missing the wakeup (between where it senses the (lack of) active condition
(with interrupts disabled) and where it does the sleep (interrupts enabled)
in the read or iomux call, etc). That is why the read and iomux calls start
with an infinite loop that gets broken out of upon an active condition,
otherwise keeps sleeping and looking. The part in this code got "optimized"
out in the later versions, and is put back now. Note that this is *NOT*
needed for poll() waiters, because the poll_wait() function that is used there
is atomic enough for this purpose; it will not go to sleep before ensuring
that the waitqueue is empty. */
						if (!ms->rxdisable) { /* if receiver enabled */
							/* Notify a blocked reader that there is data available
							to be read, unless we're waiting for it to be full */
#ifdef CONFIG_DAHDI_DEBUG
							module_printk(KERN_NOTICE, "Notifying reader data in block %d\n", oldbuf);
#endif
							wake_up_interruptible(&ms->waitq);
						}
					}
				}
			}
			if (abort) {
				/* Start over reading frame */
				ms->readidx[ms->inreadbuf] = 0;
				ms->infcs = PPP_INITFCS;

#ifdef CONFIG_DAHDI_NET
				if (dahdi_have_netdev(ms)) {
					struct net_device_stats *stats = hdlc_stats(ms->hdlcnetdev->netdev);
					stats->rx_errors++;
					if (abort == DAHDI_EVENT_OVERRUN)
						stats->rx_over_errors++;
					if (abort == DAHDI_EVENT_BADFCS)
						stats->rx_crc_errors++;
					if (abort == DAHDI_EVENT_ABORT)
						stats->rx_frame_errors++;
				} else
#endif
#ifdef CONFIG_DAHDI_PPP
				if (ms->flags & DAHDI_FLAG_PPP) {
					ms->do_ppp_error = 1;
					tasklet_schedule(&ms->ppp_calls);
				} else
#endif
					if (test_bit(DAHDI_FLAGBIT_OPEN, &ms->flags) && !ss->span->alarms) {
						/* Notify the receiver... */
						__qevent(ss->master, abort);
					}
			}
		} else /* No place to receive -- drop on the floor */
			break;
#ifdef CONFIG_DAHDI_NET
		if (skb && dahdi_have_netdev(ms))
		{
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,22)
			skb->mac.raw = skb->data;
#else
			skb_reset_mac_header(skb);
#endif
			skb->dev = chan_to_netdev(ms);
#ifdef DAHDI_HDLC_TYPE_TRANS
			skb->protocol = hdlc_type_trans(skb,
							chan_to_netdev(ms));
#else
			skb->protocol = htons (ETH_P_HDLC);
#endif
			netif_rx(skb);
		}
#endif
#ifdef CONFIG_DAHDI_PPP
		if (skb && (ms->flags & DAHDI_FLAG_PPP)) {
			unsigned char *tmp;
			tmp = skb->data;
			skb_pull(skb, 2);
			/* Make sure that it's addressed to ALL STATIONS and UNNUMBERED */
			if (!tmp || (tmp[0] != 0xff) || (tmp[1] != 0x03)) {
				/* Invalid SKB -- drop */
				if (tmp)
					module_printk(KERN_NOTICE, "Received invalid SKB (%02x, %02x)\n", tmp[0], tmp[1]);
				dev_kfree_skb_irq(skb);
			} else {
				skb_queue_tail(&ms->ppp_rq, skb);
				tasklet_schedule(&ms->ppp_calls);
			}
		}
#endif
	}

	if (bytes) {
		if (!test_bit(DAHDI_FLAGBIT_RXOVERRUN, &ms->flags)) {
			if (test_bit(DAHDI_FLAGBIT_BUFEVENTS, &ms->flags))
				__qevent(ms, DAHDI_EVENT_READ_OVERRUN);
			set_bit(DAHDI_FLAGBIT_RXOVERRUN, &ms->flags);
		}
	} else {
		clear_bit(DAHDI_FLAGBIT_RXOVERRUN, &ms->flags);
	}
}

static inline void __dahdi_putbuf_chunk(struct dahdi_chan *ss, unsigned char *rxb)
{
	__putbuf_chunk(ss, rxb, DAHDI_CHUNKSIZE);

#ifdef CONFIG_DAHDI_MIRROR
	if (ss->rxmirror) {
		spin_lock(&ss->rxmirror->lock);
		__putbuf_chunk(ss->rxmirror, rxb, DAHDI_CHUNKSIZE);
		spin_unlock(&ss->rxmirror->lock);
	}
#endif /* CONFIG_DAHDI_MIRROR */
}

static void __dahdi_hdlc_abort(struct dahdi_chan *ss, int event)
{
	if (ss->inreadbuf >= 0)
		ss->readidx[ss->inreadbuf] = 0;
	if (test_bit(DAHDI_FLAGBIT_OPEN, &ss->flags) && !ss->span->alarms)
		__qevent(ss->master, event);
}

void dahdi_hdlc_abort(struct dahdi_chan *ss, int event)
{
	unsigned long flags;
	spin_lock_irqsave(&ss->lock, flags);
	__dahdi_hdlc_abort(ss, event);
	spin_unlock_irqrestore(&ss->lock, flags);
}

void dahdi_hdlc_putbuf(struct dahdi_chan *ss, unsigned char *rxb, int bytes)
{
	unsigned long flags;
	int res;
	int left;

	spin_lock_irqsave(&ss->lock, flags);
	if (ss->inreadbuf < 0) {
#ifdef CONFIG_DAHDI_DEBUG
		module_printk(KERN_NOTICE, "No place to receive HDLC frame\n");
#endif
		spin_unlock_irqrestore(&ss->lock, flags);
		return;
	}
	/* Read into the current buffer */
	left = ss->blocksize - ss->readidx[ss->inreadbuf];
	if (left > bytes)
		left = bytes;
	if (left > 0) {
		memcpy(ss->readbuf[ss->inreadbuf] + ss->readidx[ss->inreadbuf], rxb, left);
		rxb += left;
		ss->readidx[ss->inreadbuf] += left;
		bytes -= left;
	}
	/* Something isn't fit into buffer */
	if (bytes) {
#ifdef CONFIG_DAHDI_DEBUG
		module_printk(KERN_NOTICE, "HDLC frame isn't fit into buffer space\n");
#endif
		__dahdi_hdlc_abort(ss, DAHDI_EVENT_OVERRUN);
	}
	res = left;
	spin_unlock_irqrestore(&ss->lock, flags);
}

void dahdi_hdlc_finish(struct dahdi_chan *ss)
{
	int oldreadbuf;
	unsigned long flags;

	spin_lock_irqsave(&ss->lock, flags);

	if ((oldreadbuf = ss->inreadbuf) < 0) {
#ifdef CONFIG_DAHDI_DEBUG
		module_printk(KERN_NOTICE, "No buffers to finish\n");
#endif
		spin_unlock_irqrestore(&ss->lock, flags);
		return;
	}

	if (!ss->readidx[ss->inreadbuf]) {
#ifdef CONFIG_DAHDI_DEBUG
		module_printk(KERN_NOTICE, "Empty HDLC frame received\n");
#endif
		spin_unlock_irqrestore(&ss->lock, flags);
		return;
	}

	ss->readn[ss->inreadbuf] = ss->readidx[ss->inreadbuf];
	ss->inreadbuf = (ss->inreadbuf + 1) % ss->numbufs;
	if (ss->inreadbuf == ss->outreadbuf) {
		ss->inreadbuf = -1;
#ifdef CONFIG_DAHDI_DEBUG
		module_printk(KERN_NOTICE, "Notifying reader data in block %d\n", oldreadbuf);
#endif
		ss->rxdisable = 0;
	}
	if (ss->outreadbuf < 0) {
		ss->outreadbuf = oldreadbuf;
	}

	if (!ss->rxdisable)
		wake_up_interruptible(&ss->waitq);
	spin_unlock_irqrestore(&ss->lock, flags);
}

/* Returns 1 if EOF, 0 if data is still in frame, -1 if EOF and no buffers left */
int dahdi_hdlc_getbuf(struct dahdi_chan *ss, unsigned char *bufptr, unsigned int *size)
{
	unsigned char *buf;
	unsigned long flags;
	int left = 0;
	int res;
	int oldbuf;

	spin_lock_irqsave(&ss->lock, flags);
	if (ss->outwritebuf > -1) {
		buf = ss->writebuf[ss->outwritebuf];
		left = ss->writen[ss->outwritebuf] - ss->writeidx[ss->outwritebuf];
		/* Strip off the empty HDLC CRC end */
		left -= 2;
		if (left <= *size) {
			*size = left;
			res = 1;
		} else
			res = 0;

		memcpy(bufptr, &buf[ss->writeidx[ss->outwritebuf]], *size);
		ss->writeidx[ss->outwritebuf] += *size;

		if (res) {
			/* Rotate buffers */
			oldbuf = ss->outwritebuf;
			ss->writeidx[oldbuf] = 0;
			ss->writen[oldbuf] = 0;
			ss->outwritebuf = (ss->outwritebuf + 1) % ss->numbufs;
			if (ss->outwritebuf == ss->inwritebuf) {
				ss->outwritebuf = -1;
				if (ss->iomask & (DAHDI_IOMUX_WRITE | DAHDI_IOMUX_WRITEEMPTY))
					wake_up_interruptible(&ss->waitq);
				/* If we're only supposed to start when full, disable the transmitter */
				if ((ss->txbufpolicy == DAHDI_POLICY_WHEN_FULL) || (ss->txbufpolicy == DAHDI_POLICY_HALF_FULL))
					ss->txdisable = 1;
				res = -1;
			}

			if (ss->inwritebuf < 0)
				ss->inwritebuf = oldbuf;

			if (!(ss->flags & DAHDI_FLAG_PPP) ||
			    !dahdi_have_netdev(ss)) {
				wake_up_interruptible(&ss->waitq);
			}
		}
	} else {
		res = -1;
		*size = 0;
	}
	spin_unlock_irqrestore(&ss->lock, flags);

	return res;
}


static void process_timers(void)
{
	struct dahdi_timer_rate *cur_rate;
	struct dahdi_timer *cur_timer;

	if (list_empty(&dahdi_timer_rates))
		return;

	spin_lock(&dahdi_timer_lock);
	list_for_each_entry(cur_rate, &dahdi_timer_rates, node) {
		if (!cur_rate->rate_samples)
			continue;

		cur_rate->cur_samples -= DAHDI_CHUNKSIZE;
		if (cur_rate->cur_samples > 0)
			continue;

		list_for_each_entry(cur_timer, &cur_rate->timers, node)
			atomic_inc(&cur_timer->tripped);

		cur_rate->cur_samples = cur_rate->rate_samples;
		wake_up_interruptible(&cur_rate->sel);
	}
	spin_unlock(&dahdi_timer_lock);
}

static unsigned int dahdi_timer_poll(struct file *file, struct poll_table_struct *wait_table)
{
	struct dahdi_timer *timer = file->private_data;
	struct dahdi_timer_rate *rate = timer->rate;

	if (!rate || !timer)
		return -EINVAL;

	poll_wait(file, &rate->sel, wait_table);
	if (atomic_read(&timer->tripped) || atomic_read(&timer->ping))
		return POLLPRI;

	return 0;
}

/* device poll routine */
static unsigned int
dahdi_chan_poll(struct file *file, struct poll_table_struct *wait_table)
{
	struct dahdi_chan *const c = file->private_data;
	int ret = 0;
	unsigned long flags;

	if (unlikely(!c))
		return -EINVAL;

	poll_wait(file, &c->waitq, wait_table);

	spin_lock_irqsave(&c->lock, flags);
	ret |= (c->inwritebuf > -1) ? POLLOUT|POLLWRNORM : 0;
	ret |= ((c->outreadbuf > -1) && !c->rxdisable) ?  POLLIN|POLLRDNORM : 0;
	ret |= (c->eventoutidx != c->eventinidx) ? POLLPRI : 0;
	spin_unlock_irqrestore(&c->lock, flags);

	return ret;
}

static unsigned int dahdi_poll(struct file *file, struct poll_table_struct *wait_table)
{
	const int unit = UNIT(file);

	if (likely(unit == DAHDI_TIMER))
		return dahdi_timer_poll(file, wait_table);

	/* transcoders and channels should have updated their file_operations
	 * before poll is ever called. */
	return -EINVAL;
}

static void __dahdi_transmit_chunk(struct dahdi_chan *chan, unsigned char *buf)
{
	unsigned char silly[DAHDI_CHUNKSIZE];
	/* Called with chan->lock locked */
#ifdef	OPTIMIZE_CHANMUTE
	if(likely(chan->chanmute))
		return;
#endif
	if (!buf)
		buf = silly;
	__dahdi_getbuf_chunk(chan, buf);

	if ((chan->flags & DAHDI_FLAG_AUDIO) || (chan->confmode)) {
#ifdef CONFIG_DAHDI_MMX
		dahdi_kernel_fpu_begin();
#endif
		__dahdi_process_getaudio_chunk(chan, buf);
#ifdef CONFIG_DAHDI_MMX
		dahdi_kernel_fpu_end();
#endif
	}
}

static inline void __dahdi_real_transmit(struct dahdi_chan *chan)
{
	/* Called with chan->lock held */
#ifdef	OPTIMIZE_CHANMUTE
	if(likely(chan->chanmute))
		return;
#endif
	if (chan->confmode) {
		/* Pull queued data off the conference */
		__buf_pull(&chan->confout, chan->writechunk, chan);
	} else {
		__dahdi_transmit_chunk(chan, chan->writechunk);
	}
}

static void __dahdi_getempty(struct dahdi_chan *ms, unsigned char *buf)
{
	int bytes = DAHDI_CHUNKSIZE;
	int left;
	unsigned char *txb = buf;
	int x;
	short getlin;
	/* Called with ms->lock held */

	while(bytes) {
		/* Receive silence, or tone */
		if (ms->curtone) {
			left = ms->curtone->tonesamples - ms->tonep;
			if (left > bytes)
				left = bytes;
			for (x=0;x<left;x++) {
				/* Pick our default value from the next sample of the current tone */
				getlin = dahdi_tone_nextsample(&ms->ts, ms->curtone);
				*(txb++) = DAHDI_LIN2X(getlin, ms);
			}
			ms->tonep+=left;
			bytes -= left;
			if (ms->tonep >= ms->curtone->tonesamples) {
				struct dahdi_tone *last;
				/* Go to the next sample of the tone */
				ms->tonep = 0;
				last = ms->curtone;
				ms->curtone = ms->curtone->next;
				if (!ms->curtone) {
					/* No more tones...  Is this dtmf or mf?  If so, go to the next digit */
					if (ms->dialing)
						__do_dtmf(ms);
				} else {
					if (last != ms->curtone)
						dahdi_init_tone_state(&ms->ts, ms->curtone);
				}
			}
		} else {
			/* Use silence */
			memset(txb, DAHDI_LIN2X(0, ms), bytes);
			bytes = 0;
		}
	}

}

static void __dahdi_receive_chunk(struct dahdi_chan *chan, unsigned char *buf)
{
	/* Receive chunk of audio -- called with chan->lock held */
	unsigned char waste[DAHDI_CHUNKSIZE];

#ifdef	OPTIMIZE_CHANMUTE
	if(likely(chan->chanmute))
		return;
#endif
	if (!buf) {
		memset(waste, DAHDI_LIN2X(0, chan), sizeof(waste));
		buf = waste;
	}
	if ((chan->flags & DAHDI_FLAG_AUDIO) || (chan->confmode)) {
#ifdef CONFIG_DAHDI_MMX
		dahdi_kernel_fpu_begin();
#endif
		__dahdi_process_putaudio_chunk(chan, buf);
#ifdef CONFIG_DAHDI_MMX
		dahdi_kernel_fpu_end();
#endif
	}
	__dahdi_putbuf_chunk(chan, buf);
}

static inline void __dahdi_real_receive(struct dahdi_chan *chan)
{
	/* Called with chan->lock held */
#ifdef	OPTIMIZE_CHANMUTE
	if(likely(chan->chanmute))
		return;
#endif
	if (chan->confmode) {
		/* Load into queue if we have space */
		__buf_push(&chan->confin, chan->readchunk);
	} else {
		__dahdi_receive_chunk(chan, chan->readchunk);
	}
}

/**
 * __transmit_to_slaves() - Distribute the tx data to all the slave channels.
 *
 */
static void __transmit_to_slaves(struct dahdi_chan *const chan)
{
	u_char data[DAHDI_CHUNKSIZE];
	int i;
	int pos = DAHDI_CHUNKSIZE;
	struct dahdi_chan *slave;
	for (i = 0; i < DAHDI_CHUNKSIZE; i++) {
		for (slave = chan; (NULL != slave); slave = slave->nextslave) {
			if (pos == DAHDI_CHUNKSIZE) {
				__dahdi_transmit_chunk(chan, data);
				pos = 0;
			}
			slave->writechunk[i] = data[pos++];
		}
	}
}

int _dahdi_transmit(struct dahdi_span *span)
{
	unsigned int x;

	for (x=0;x<span->channels;x++) {
		struct dahdi_chan *const chan = span->chans[x];
		spin_lock(&chan->lock);
		if (unlikely(chan->flags & DAHDI_FLAG_NOSTDTXRX)) {
			spin_unlock(&chan->lock);
			continue;
		}
		if (chan == chan->master) {
			if (is_chan_dacsed(chan)) {
				struct dahdi_chan *const src = chan->dacs_chan;
				memcpy(chan->writechunk, src->readchunk,
				       DAHDI_CHUNKSIZE);
				if (chan->sig == DAHDI_SIG_DACS_RBS) {
					/* Just set bits for our destination */
					if (chan->txsig != src->rxsig) {
						chan->txsig = src->rxsig;
						span->ops->rbsbits(chan, src->rxsig);
					}
				}
				/* there is no further processing to do for
				 * DACS channels, so jump to the next channel
				 * in the span */
				spin_unlock(&chan->lock);
				continue;
			} else if (chan->nextslave) {
				__transmit_to_slaves(chan);
			} else {
				/* Process a normal channel */
				__dahdi_real_transmit(chan);
			}
			if (chan->otimer) {
				chan->otimer -= DAHDI_CHUNKSIZE;
				if (chan->otimer <= 0)
					__rbs_otimer_expire(chan);
			}
		}
		spin_unlock(&chan->lock);
	}

	if (span->mainttimer) {
		span->mainttimer -= DAHDI_CHUNKSIZE;
		if (span->mainttimer <= 0) {
			span->mainttimer = 0;
			span->maintstat = 0;
		}
	}
	return 0;
}
EXPORT_SYMBOL(_dahdi_transmit);

static inline void __pseudo_rx_audio(struct dahdi_chan *chan)
{
	unsigned char tmp[DAHDI_CHUNKSIZE];
	spin_lock(&chan->lock);
	__dahdi_getempty(chan, tmp);
	__dahdi_receive_chunk(chan, tmp);
	spin_unlock(&chan->lock);
}

#ifdef CONFIG_DAHDI_MIRROR
static inline void pseudo_rx_audio(struct dahdi_chan *chan)
{
	if (!chan->srcmirror)
		__pseudo_rx_audio(chan);
}
#else
static inline void pseudo_rx_audio(struct dahdi_chan *chan)
{
	__pseudo_rx_audio(chan);
}
#endif /* CONFIG_DAHDI_MIRROR */

#ifdef DAHDI_SYNC_TICK
static inline void dahdi_sync_tick(struct dahdi_span *const s)
{
	if (s->ops->sync_tick)
		s->ops->sync_tick(s, s == master);
}
#else
#define dahdi_sync_tick(x) do { ; } while (0)
#endif

/**
 * _process_masterspan - Handle conferencing and timers.
 *
 * There are three sets of conference sum accumulators. One for the current
 * sample chunk (conf_sums), one for the next sample chunk (conf_sums_next), and
 * one for the previous sample chunk (conf_sums_prev). The following routine
 * (rotate_sums) "rotates" the pointers to these accululator arrays as part
 * of the events of sample chink processing as follows:
 *
 * 1. All (real span) receive chunks are processed (with putbuf). The last one
 * to be processed is the master span. The data received is loaded into the
 * accumulators for the next chunk (conf_sums_next), to be in alignment with
 * current data after rotate_sums() is called (which immediately follows).
 * Keep in mind that putbuf is *also* a transmit routine for the pseudo parts
 * of channels that are in the REALANDPSEUDO conference mode. These channels
 * are processed from data in the current sample chunk (conf_sums), being
 * that this is a "transmit" function (for the pseudo part).
 *
 * 2. rotate_sums() is called.
 *
 * 3. All pseudo channel receive chunks are processed. This data is loaded into
 * the current sample chunk accumulators (conf_sums).
 *
 * 4. All conference links are processed (being that all receive data for this
 * chunk has already been processed by now).
 *
 * 5. All pseudo channel transmit chunks are processed. This data is loaded from
 * the current sample chunk accumulators (conf_sums).
 *
 * 6. All (real span) transmit chunks are processed (with getbuf).  This data is
 * loaded from the current sample chunk accumulators (conf_sums). Keep in mind
 * that getbuf is *also* a receive routine for the pseudo part of channels that
 * are in the REALANDPSEUDO conference mode. These samples are loaded into
 * the next sample chunk accumulators (conf_sums_next) to be processed as part
 * of the next sample chunk's data (next time around the world).
 *
 */
static void _process_masterspan(void)
{
	int x;
	struct pseudo_chan *pseudo;
	struct dahdi_span *s;
	u_char *data;

#ifdef CONFIG_DAHDI_CORE_TIMER
	/* We increment the calls since start here, so that if we switch over
	 * to the core timer, we know how many times we need to call
	 * process_masterspan in order to catch up since this function needs
	 * to be called (1000 / (DAHDI_CHUNKSIZE / 8)) times per second. */
	atomic_inc(&core_timer.count);
#endif
	/* Hold the chan_lock for the duration of major
	   activities which touch all sorts of channels */
	spin_lock(&chan_lock);

	/* Process any timers */
	process_timers();

	list_for_each_entry(s, &span_list, spans_node) {
		for (x = 0; x < s->channels; ++x) {
			struct dahdi_chan *const chan = s->chans[x];
			if (!chan->confmode)
				continue;
			spin_lock(&chan->lock);
			data = __buf_peek(&chan->confin);
			__dahdi_receive_chunk(chan, data);
			if (data)
				__buf_pull(&chan->confin, NULL, chan);
			spin_unlock(&chan->lock);
		}
	}

	/* This is the master channel, so make things switch over */
	rotate_sums();

	/* do all the pseudo and/or conferenced channel receives (getbuf's) */
	list_for_each_entry(pseudo, &pseudo_chans, node) {
		spin_lock(&pseudo->chan.lock);
		__dahdi_transmit_chunk(&pseudo->chan, NULL);
		spin_unlock(&pseudo->chan.lock);
	}

	/* do all the pseudo/conferenced channel transmits (putbuf's) */
	list_for_each_entry(pseudo, &pseudo_chans, node) {
		pseudo_rx_audio(&pseudo->chan);
	}

	list_for_each_entry(s, &span_list, spans_node) {
		for (x = 0; x < s->channels; x++) {
			struct dahdi_chan *const chan = s->chans[x];
			if (!chan->confmode)
				continue;
			spin_lock(&chan->lock);
			data = __buf_pushpeek(&chan->confout);
			__dahdi_transmit_chunk(chan, data);
			if (data)
				__buf_push(&chan->confout, NULL);
			spin_unlock(&chan->lock);
		}

		dahdi_sync_tick(s);
	}
	spin_unlock(&chan_lock);
}

#ifndef CONFIG_DAHDI_CORE_TIMER

static void coretimer_init(void)
{
	return;
}

static void coretimer_cleanup(void)
{
	return;
}

#else

static unsigned long core_diff_ms(struct timespec *t0, struct timespec *t1)
{
	long nanosec, sec;
	unsigned long ms;
	sec = (t1->tv_sec - t0->tv_sec);
	nanosec = (t1->tv_nsec - t0->tv_nsec);
	while (nanosec >= NSEC_PER_SEC) {
		nanosec -= NSEC_PER_SEC;
		++sec;
	}
	while (nanosec < 0) {
		nanosec += NSEC_PER_SEC;
		--sec;
	}
	ms = (sec * 1000) + (nanosec / 1000000L);
	return ms;
}

static inline unsigned long msecs_processed(const struct core_timer *const ct)
{
	return atomic_read(&ct->count) * DAHDI_MSECS_PER_CHUNK;
}

static void coretimer_func(unsigned long param)
{
	unsigned long flags;
	unsigned long ms_since_start;
	struct timespec now;
	const unsigned long MAX_INTERVAL = 100000L;
	const unsigned long ONESEC_INTERVAL = HZ;
	const long MS_LIMIT = 3000;
	long difference;

	now = current_kernel_time();

	if (atomic_read(&core_timer.count) ==
	    atomic_read(&core_timer.last_count)) {

		/* This is the code path if a board driver is not calling
		 * dahdi_receive, and therefore the core of dahdi needs to
		 * perform the master span processing itself. */

		if (!atomic_read(&core_timer.shutdown)) {
			mod_timer(&core_timer.timer, jiffies +
				  core_timer.interval);
		}

		ms_since_start = core_diff_ms(&core_timer.start_interval, &now);

		/*
		 * If the system time has changed, it is possible for us to be
		 * far behind.  If we are more than MS_LIMIT milliseconds
		 * behind (or ahead in time), just reset our time base and
		 * continue so that we do not hang the system here.
		 *
		 */
		difference = ms_since_start - msecs_processed(&core_timer);
		if (unlikely((difference >  MS_LIMIT) || (difference < 0))) {
			if (printk_ratelimit()) {
				module_printk(KERN_INFO,
					      "Detected time shift.\n");
			}
			atomic_set(&core_timer.count, 0);
			atomic_set(&core_timer.last_count, 0);
			core_timer.start_interval = now;
			return;
		}

		local_irq_save(flags);
		while (ms_since_start > msecs_processed(&core_timer))
			_process_masterspan();
		local_irq_restore(flags);

		if (ms_since_start > MAX_INTERVAL) {
			atomic_set(&core_timer.count, 0);
			atomic_set(&core_timer.last_count, 0);
			core_timer.start_interval = now;
		} else {
			atomic_set(&core_timer.last_count,
				   atomic_read(&core_timer.count));
		}

	} else {

		/* It looks like a board driver is calling dahdi_receive. We
		 * will just check again in a second. */
		atomic_set(&core_timer.count, 0);
		atomic_set(&core_timer.last_count, 0);
		core_timer.start_interval = now;
		if (!atomic_read(&core_timer.shutdown))
			mod_timer(&core_timer.timer, jiffies + ONESEC_INTERVAL);
	}
}

static void coretimer_init(void)
{
	init_timer(&core_timer.timer);
	core_timer.timer.function = coretimer_func;
	core_timer.start_interval = current_kernel_time();
	core_timer.timer.expires = jiffies + HZ;
	atomic_set(&core_timer.count, 0);
	atomic_set(&core_timer.shutdown, 0);
	core_timer.interval = max(msecs_to_jiffies(DAHDI_MSECS_PER_CHUNK), 1UL);
	if (core_timer.interval < (HZ/250))
		core_timer.interval = (HZ/250);
	add_timer(&core_timer.timer);
}

static void coretimer_cleanup(void)
{
	atomic_set(&core_timer.shutdown, 1);
	del_timer_sync(&core_timer.timer);
}

#endif /* CONFIG_DAHDI_CORE_TIMER */

/**
 * __receive_from_slaves() - Collect the rx data from all the slave channels.
 *
 */
static void __receive_from_slaves(struct dahdi_chan *const chan)
{
	u_char data[DAHDI_CHUNKSIZE];
	int i;
	int pos = 0;
	struct dahdi_chan *slave;

	for (i = 0; i < DAHDI_CHUNKSIZE; ++i) {
		for (slave = chan; (NULL != slave); slave = slave->nextslave) {
			data[pos++] = slave->readchunk[i];
			if (pos == DAHDI_CHUNKSIZE) {
				__dahdi_receive_chunk(chan, data);
				pos = 0;
			}
		}
	}
}

static inline bool should_skip_receive(const struct dahdi_chan *const chan)
{
	return (unlikely(chan->flags & DAHDI_FLAG_NOSTDTXRX) ||
		(chan->master != chan) ||
		is_chan_dacsed(chan));
}

int _dahdi_receive(struct dahdi_span *span)
{
	unsigned int x;

#ifdef CONFIG_DAHDI_WATCHDOG
	span->watchcounter--;
#endif
	for (x = 0; x < span->channels; x++) {
		struct dahdi_chan *const chan = span->chans[x];
		spin_lock(&chan->lock);
		if (should_skip_receive(chan)) {
			spin_unlock(&chan->lock);
			continue;
		}

		if (chan->nextslave) {
			__receive_from_slaves(chan);
		} else {
			/* Process a normal channel */
			__dahdi_real_receive(chan);
		}
		if (chan->itimer) {
			chan->itimer -= DAHDI_CHUNKSIZE;
			if (chan->itimer <= 0)
				rbs_itimer_expire(chan);
		}
		if (chan->ringdebtimer)
			chan->ringdebtimer--;
		if (chan->sig & __DAHDI_SIG_FXS) {
			if (chan->rxhooksig == DAHDI_RXSIG_RING)
				chan->ringtrailer = DAHDI_RINGTRAILER;
			else if (chan->ringtrailer) {
				chan->ringtrailer -= DAHDI_CHUNKSIZE;
				/* See if RING trailer is expired */
				if (!chan->ringtrailer && !chan->ringdebtimer)
					__qevent(chan, DAHDI_EVENT_RINGOFFHOOK);
			}
		}
		if (chan->pulsetimer) {
			chan->pulsetimer--;
			if (chan->pulsetimer <= 0) {
				if (chan->pulsecount) {
					if (chan->pulsecount > 12) {

						module_printk(KERN_NOTICE, "Got pulse digit %d on %s???\n",
					    chan->pulsecount,
						chan->name);
					} else if (chan->pulsecount > 11) {
						__qevent(chan, DAHDI_EVENT_PULSEDIGIT | '#');
					} else if (chan->pulsecount > 10) {
						__qevent(chan, DAHDI_EVENT_PULSEDIGIT | '*');
					} else if (chan->pulsecount > 9) {
						__qevent(chan, DAHDI_EVENT_PULSEDIGIT | '0');
					} else {
						__qevent(chan, DAHDI_EVENT_PULSEDIGIT | ('0' +
							chan->pulsecount));
					}
					chan->pulsecount = 0;
				}
			}
		}
#ifdef BUFFER_DEBUG
		chan->statcount -= DAHDI_CHUNKSIZE;
#endif
		spin_unlock(&chan->lock);
	}

	if (span == master)
		_process_masterspan();

	return 0;
}
EXPORT_SYMBOL(_dahdi_receive);

MODULE_AUTHOR("Mark Spencer <markster@digium.com>");
MODULE_DESCRIPTION("DAHDI Telephony Interface");
MODULE_LICENSE("GPL v2");
/* DAHDI now provides timing. If anybody wants dahdi_dummy it's probably
 * for that. So make dahdi provide it for now. This alias may be removed
 * in the future, and users are encouraged not to rely on it. */
MODULE_ALIAS("dahdi_dummy");

module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Sets debugging verbosity as a bitfield, to see"\
		" general debugging set this to 1. To see RBS debugging set"\
		" this to 32");
module_param(deftaps, int, 0644);

module_param(max_pseudo_channels, int, 0644);
MODULE_PARM_DESC(max_pseudo_channels, "Maximum number of pseudo channels.");

module_param(auto_register_spans, int, 0644);
MODULE_PARM_DESC(auto_register_spans,
		 "If 1 spans will automatically have their children span and "
		 "channel numbers assigned by the driver. If 0, user space "
		 "will need to register them via /sys/bus/dahdi_devices.");

static const struct file_operations dahdi_fops = {
	.owner   = THIS_MODULE,
	.open    = dahdi_open,
	.release = dahdi_release,
#ifdef HAVE_UNLOCKED_IOCTL
	.unlocked_ioctl  = dahdi_unlocked_ioctl,
#ifdef HAVE_COMPAT_IOCTL
	.compat_ioctl = dahdi_ioctl_compat,
#endif
#else
	.ioctl   = dahdi_ioctl,
#endif
	.poll    = dahdi_poll,
};

static const struct file_operations dahdi_chan_fops = {
	.owner   = THIS_MODULE,
	.open    = dahdi_open,
	.release = dahdi_release,
#ifdef HAVE_UNLOCKED_IOCTL
	.unlocked_ioctl  = dahdi_unlocked_ioctl,
#ifdef HAVE_COMPAT_IOCTL
	.compat_ioctl = dahdi_ioctl_compat,
#endif
#else
	.ioctl   = dahdi_ioctl,
#endif
	.read    = dahdi_chan_read,
	.write   = dahdi_chan_write,
	.poll    = dahdi_chan_poll,
};

#ifdef CONFIG_DAHDI_WATCHDOG
static struct timer_list watchdogtimer;

static void watchdog_check(unsigned long ignored)
{
	unsigned long flags;
	static int wdcheck=0;
	struct dahdi_span *s;

	spin_lock_irqsave(&span_list_lock, flags);
	list_for_each_entry(s, &span_list, spans_node) {
		if (s->flags & DAHDI_FLAG_RUNNING) {
			if (s->watchcounter == DAHDI_WATCHDOG_INIT) {
				/* Whoops, dead card */
				if ((s->watchstate == DAHDI_WATCHSTATE_OK) ||
					(s->watchstate == DAHDI_WATCHSTATE_UNKNOWN)) {
					s->watchstate = DAHDI_WATCHSTATE_RECOVERING;
					if (s->watchdog) {
						module_printk(KERN_NOTICE, "Kicking span %s\n", s->name);
						s->watchdog(spans[x], DAHDI_WATCHDOG_NOINTS);
					} else {
						module_printk(KERN_NOTICE, "Span %s is dead with no revival\n", s->name);
						s->watchstate = DAHDI_WATCHSTATE_FAILED;
					}
				}
			} else {
				if ((s->watchstate != DAHDI_WATCHSTATE_OK) &&
					(s->watchstate != DAHDI_WATCHSTATE_UNKNOWN))
						module_printk(KERN_NOTICE, "Span %s is alive!\n", s->name);
				s->watchstate = DAHDI_WATCHSTATE_OK;
			}
			s->watchcounter = DAHDI_WATCHDOG_INIT;
		}
	}
	spin_unlock_irqrestore(&span_list_lock, flags);
	if (!wdcheck) {
		module_printk(KERN_NOTICE, "watchdog on duty!\n");
		wdcheck=1;
	}
	mod_timer(&watchdogtimer, jiffies + 2);
}

static int __init watchdog_init(void)
{
	init_timer(&watchdogtimer);
	watchdogtimer.expires = 0;
	watchdogtimer.data =0;
	watchdogtimer.function = watchdog_check;
	/* Run every couple of jiffy or so */
	mod_timer(&watchdogtimer, jiffies + 2);
	return 0;
}

static void __exit watchdog_cleanup(void)
{
	del_timer(&watchdogtimer);
}

#endif

static const char *hwec_def_name = "HWEC";
static const char *hwec_get_name(const struct dahdi_chan *chan)
{
	if (chan && chan->span && chan->span->ops->echocan_name)
		return chan->span->ops->echocan_name(chan);
	else
		return hwec_def_name;
}

static int hwec_echocan_create(struct dahdi_chan *chan,
	struct dahdi_echocanparams *ecp, struct dahdi_echocanparam *p,
	struct dahdi_echocan_state **ec)
{
	if (chan->span && chan->span->ops->echocan_create)
		return chan->span->ops->echocan_create(chan, ecp, p, ec);
	else
		return -ENODEV;
}

static const struct dahdi_echocan_factory hwec_factory = {
	.get_name = hwec_get_name,
	.owner = THIS_MODULE,
	.echocan_create = hwec_echocan_create,
};

static int __init dahdi_init(void)
{
	int res = 0;

#ifdef CONFIG_PROC_FS
	root_proc_entry = proc_mkdir("dahdi", NULL);
	if (!root_proc_entry) {
		dahdi_err("dahdi init: Failed creating /proc/dahdi\n");
		return -EEXIST;
	}
#endif
	res = dahdi_sysfs_init(&dahdi_fops);
	if (res)
		goto failed_driver_init;

	dahdi_conv_init();
	fasthdlc_precalc();
	rotate_sums();
#ifdef CONFIG_DAHDI_WATCHDOG
	watchdog_init();
#endif
	coretimer_init();

	res = dahdi_register_echocan_factory(&hwec_factory);
	if (res) {
		WARN_ON(1);
		goto failed_register_ec_factory;
	}

	return 0;

failed_register_ec_factory:
	coretimer_cleanup();
	dahdi_sysfs_exit();
failed_driver_init:
	if (root_proc_entry) {
		remove_proc_entry("dahdi", NULL);
		root_proc_entry = NULL;
	}
	return res;
}

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 22)
static inline void flush_find_master_work(void)
{
	flush_scheduled_work();
}
#else
static inline void flush_find_master_work(void)
{
	cancel_work_sync(&find_master_work);
}
#endif

static void __exit dahdi_cleanup(void)
{
	struct dahdi_zone *z;

	dahdi_unregister_echocan_factory(&hwec_factory);
	coretimer_cleanup();
	dahdi_sysfs_exit();

#ifdef CONFIG_PROC_FS
	if (root_proc_entry) {
		remove_proc_entry("dahdi", NULL);
		root_proc_entry = NULL;
	}
#endif

	module_printk(KERN_INFO, "Telephony Interface Unloaded\n");

	spin_lock(&zone_lock);
	while (!list_empty(&tone_zones)) {
		z = list_entry(tone_zones.next, struct dahdi_zone, node);
		list_del(&z->node);
		if (!tone_zone_put(z)) {
			module_printk(KERN_WARNING,
				      "Potential memory leak detected in %s\n",
				      __func__);
		}
	}
	spin_unlock(&zone_lock);

#ifdef CONFIG_DAHDI_WATCHDOG
	watchdog_cleanup();
#endif
	flush_find_master_work();
}

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 12)
char *dahdi_kasprintf(gfp_t gfp, const char *fmt, ...)
{
	va_list ap;
	char *p;
	char *temp;
	unsigned int len;

	temp = kmalloc(PAGE_SIZE, GFP_KERNEL);
	if (!temp)
		return NULL;

	va_start(ap, fmt);
	len = vsnprintf(temp, PAGE_SIZE, fmt, ap);
	va_end(ap);

	p = kzalloc(len + 1, gfp);
	if (!p) {
		kfree(temp);
		return NULL;
	}

	memcpy(p, temp, len + 1);
	kfree(temp);
	return p;
}
EXPORT_SYMBOL(dahdi_kasprintf);
#endif

module_init(dahdi_init);
module_exit(dahdi_cleanup);