File: q921.c

package info (click to toggle)
libpri 1.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 2,696 kB
  • sloc: ansic: 39,045; makefile: 159; sh: 66
file content (3174 lines) | stat: -rw-r--r-- 77,743 bytes parent folder | download
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
/*
 * libpri: An implementation of Primary Rate ISDN
 *
 * Written by Mark Spencer <markster@digium.com>
 *
 * Copyright (C) 2001-2005, 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.
 *
 * In addition, when this program is distributed with Asterisk in
 * any form that would qualify as a 'combined work' or as a
 * 'derivative work' (but not mere aggregation), you can redistribute
 * and/or modify the combination under the terms of the license
 * provided with that copy of Asterisk, instead of the license
 * terms granted here.
 */

#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include "compat.h"
#include "libpri.h"
#include "pri_internal.h"
#include "pri_q921.h" 
#include "pri_q931.h"

/*
 * Define RANDOM_DROPS To randomly drop packets in order to simulate loss for testing
 * retransmission functionality
 */
//#define RANDOM_DROPS	1

#define Q921_INIT(fr, l_sapi, l_tei) \
	do { \
		(fr)->h.sapi = l_sapi; \
		(fr)->h.ea1 = 0; \
		(fr)->h.ea2 = 1; \
		(fr)->h.tei = l_tei; \
	} while (0)

#define Q921_CLEAR_INIT(fr, l_sapi, l_tei) \
	do { \
		memset((fr), 0, sizeof(*(fr))); \
		Q921_INIT((fr), (l_sapi), (l_tei)); \
	} while (0)

static void q921_dump_pri(struct q921_link *link, char direction_tag);
static void q921_establish_data_link(struct q921_link *link);
static void q921_mdl_error(struct q921_link *link, char error);
static void q921_mdl_remove(struct q921_link *link);
static void q921_mdl_destroy(struct q921_link *link);

/*!
 * \internal
 * \brief Convert Q.921 TEI management message type to a string.
 *
 * \param message Q.921 TEI management message type to convert.
 *
 * \return TEI management message type name string
 */
static const char *q921_tei_mgmt2str(enum q921_tei_identity message)
{
	switch (message) {
	case Q921_TEI_IDENTITY_REQUEST:
		return "TEI Identity Request";
	case Q921_TEI_IDENTITY_ASSIGNED:
		return "TEI Identity Assigned";
	case Q921_TEI_IDENTITY_CHECK_REQUEST:
		return "TEI Identity Check Request";
	case Q921_TEI_IDENTITY_REMOVE:
		return "TEI Identity Remove";
	case Q921_TEI_IDENTITY_DENIED:
		return "TEI Identity Denied";
	case Q921_TEI_IDENTITY_CHECK_RESPONSE:
		return "TEI Identity Check Response";
	case Q921_TEI_IDENTITY_VERIFY:
		return "TEI Identity Verify";
	}

	return "Unknown";
}

/*!
 * \internal
 * \brief Convert Q.921 state to a string.
 *
 * \param state Q.921 state to convert.
 *
 * \return State name string
 */
static const char *q921_state2str(enum q921_state state)
{
	switch (state) {
	case Q921_TEI_UNASSIGNED:
		return "TEI unassigned";
	case Q921_ASSIGN_AWAITING_TEI:
		return "Assign awaiting TEI";
	case Q921_ESTABLISH_AWAITING_TEI:
		return "Establish awaiting TEI";
	case Q921_TEI_ASSIGNED:
		return "TEI assigned";
	case Q921_AWAITING_ESTABLISHMENT:
		return "Awaiting establishment";
	case Q921_AWAITING_RELEASE:
		return "Awaiting release";
	case Q921_MULTI_FRAME_ESTABLISHED:
		return "Multi-frame established";
	case Q921_TIMER_RECOVERY:
		return "Timer recovery";
	}

	return "Unknown state";
}

static void q921_setstate(struct q921_link *link, int newstate)
{
	struct pri *ctrl;

	ctrl = link->ctrl;
	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		/*
		 * Suppress displaying these state transitions:
		 * Q921_MULTI_FRAME_ESTABLISHED <--> Q921_TIMER_RECOVERY
		 *
		 * Q921 keeps flipping back and forth between these two states
		 * when it has nothing better to do.
		 */
		switch (link->state) {
		case Q921_MULTI_FRAME_ESTABLISHED:
		case Q921_TIMER_RECOVERY:
			switch (newstate) {
			case Q921_MULTI_FRAME_ESTABLISHED:
			case Q921_TIMER_RECOVERY:
				/* Suppress displaying this state transition. */
				link->state = newstate;
				return;
			default:
				break;
			}
			break;
		default:
			break;
		}
		if (link->state != newstate) {
			pri_message(ctrl, "Changing from state %d(%s) to %d(%s)\n",
				link->state, q921_state2str(link->state),
				newstate, q921_state2str(newstate));
		}
	}
	link->state = newstate;
}

static void q921_discard_iqueue(struct q921_link *link)
{
	struct q921_frame *f, *p;

	f = link->tx_queue;
	while (f) {
		p = f;
		f = f->next;
		/* Free frame */
		free(p);
	}
	link->tx_queue = NULL;
}

static int q921_transmit(struct pri *ctrl, q921_h *h, int len) 
{
	int res;

#ifdef RANDOM_DROPS
	if (!(random() % 3)) {
		pri_message(ctrl, " === Dropping Packet ===\n");
		return 0;
	}
#endif
	ctrl->q921_txcount++;
	/* Just send it raw */
	if (ctrl->debug & (PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW))
		q921_dump(ctrl, h, len, ctrl->debug, 1);
	/* Write an extra two bytes for the FCS */
	res = ctrl->write_func ? ctrl->write_func(ctrl, h, len + 2) : 0;
	if (res != (len + 2)) {
		pri_error(ctrl, "Short write: %d/%d (%s)\n", res, len + 2, strerror(errno));
		return -1;
	}
	return 0;
}

static void q921_mdl_send(struct pri *ctrl, enum q921_tei_identity message, int ri, int ai, int iscommand)
{
	q921_u *f;

	if (!(f = calloc(1, sizeof(*f) + 5)))
		return;

	Q921_INIT(f, Q921_SAPI_LAYER2_MANAGEMENT, Q921_TEI_GROUP);
	f->h.c_r = (ctrl->localtype == PRI_NETWORK) ? iscommand : !iscommand;
	f->ft = Q921_FRAMETYPE_U;
	f->data[0] = 0x0f;	/* Management entity */
	f->data[1] = (ri >> 8) & 0xff;
	f->data[2] = ri & 0xff;
	f->data[3] = message;
	f->data[4] = (ai << 1) | 1;
	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl,
			"Sending MDL message: %d(%s), TEI=%d\n",
			message, q921_tei_mgmt2str(message), ai);
	}
	q921_transmit(ctrl, (q921_h *)f, 8);
	free(f);
}

static void t202_expire(void *vlink)
{
	struct q921_link *link = vlink;
	struct pri *ctrl;

	ctrl = link->ctrl;

	/* Start the TEI request timer. */
	pri_schedule_del(ctrl, link->t202_timer);
	link->t202_timer =
		pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T202], t202_expire, link);

	if (ctrl->l2_persistence != PRI_L2_PERSISTENCE_KEEP_UP) {
		/* Only try to get a TEI for N202 times if layer 2 is not persistent. */
		++link->n202_counter;
	}
	if (!link->t202_timer || link->n202_counter > ctrl->timers[PRI_TIMER_N202]) {
		if (!link->t202_timer) {
			pri_error(ctrl, "Could not start T202 timer.");
		} else {
			pri_schedule_del(ctrl, link->t202_timer);
			link->t202_timer = 0;
		}
		pri_error(ctrl, "Unable to receive TEI from network in state %d(%s)!\n",
			link->state, q921_state2str(link->state));
		switch (link->state) {
		case Q921_ASSIGN_AWAITING_TEI:
			break;
		case Q921_ESTABLISH_AWAITING_TEI:
			q921_discard_iqueue(link);
			/* DL-RELEASE indication */
			q931_dl_event(link, Q931_DL_EVENT_DL_RELEASE_IND);
			break;
		default:
			break;
		}
		q921_setstate(link, Q921_TEI_UNASSIGNED);
		return;
	}

	/* Send TEI request */
	link->ri = random() % 65535;
	q921_mdl_send(ctrl, Q921_TEI_IDENTITY_REQUEST, link->ri, Q921_TEI_GROUP, 1);
}

static void q921_tei_request(struct q921_link *link)
{
	link->n202_counter = 0;
	t202_expire(link);
}

static void q921_tei_remove(struct pri *ctrl, int tei)
{
	/*
	 * Q.921 Section 5.3.2 says we should send the remove message
	 * twice, in case of message loss.
	 */
	q921_mdl_send(ctrl, Q921_TEI_IDENTITY_REMOVE, 0, tei, 1);
	q921_mdl_send(ctrl, Q921_TEI_IDENTITY_REMOVE, 0, tei, 1);
}

static void q921_send_dm(struct q921_link *link, int fbit)
{
	q921_h h;
	struct pri *ctrl;

	ctrl = link->ctrl;

	Q921_CLEAR_INIT(&h, link->sapi, link->tei);
	h.u.m3 = 0;	/* M3 = 0 */
	h.u.m2 = 3;	/* M2 = 3 */
	h.u.p_f = fbit;	/* Final set appropriately */
	h.u.ft = Q921_FRAMETYPE_U;
	switch (ctrl->localtype) {
	case PRI_NETWORK:
		h.h.c_r = 0;
		break;
	case PRI_CPE:
		h.h.c_r = 1;
		break;
	default:
		pri_error(ctrl, "Don't know how to DM on a type %d node\n", ctrl->localtype);
		return;
	}
	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Sending DM\n", link->tei);
	}
	q921_transmit(ctrl, &h, 3);
}

static void q921_send_disc(struct q921_link *link, int pbit)
{
	q921_h h;
	struct pri *ctrl;

	ctrl = link->ctrl;

	Q921_CLEAR_INIT(&h, link->sapi, link->tei);
	h.u.m3 = 2;	/* M3 = 2 */
	h.u.m2 = 0;	/* M2 = 0 */
	h.u.p_f = pbit;	/* Poll set appropriately */
	h.u.ft = Q921_FRAMETYPE_U;
	switch (ctrl->localtype) {
	case PRI_NETWORK:
		h.h.c_r = 0;
		break;
	case PRI_CPE:
		h.h.c_r = 1;
		break;
	default:
		pri_error(ctrl, "Don't know how to DISC on a type %d node\n", ctrl->localtype);
		return;
	}
	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Sending DISC\n", link->tei);
	}
	q921_transmit(ctrl, &h, 3);
}

static void q921_send_ua(struct q921_link *link, int fbit)
{
	q921_h h;
	struct pri *ctrl;

	ctrl = link->ctrl;

	Q921_CLEAR_INIT(&h, link->sapi, link->tei);
	h.u.m3 = 3;		/* M3 = 3 */
	h.u.m2 = 0;		/* M2 = 0 */
	h.u.p_f = fbit;	/* Final set appropriately */
	h.u.ft = Q921_FRAMETYPE_U;
	switch (ctrl->localtype) {
	case PRI_NETWORK:
		h.h.c_r = 0;
		break;
	case PRI_CPE:
		h.h.c_r = 1;
		break;
	default:
		pri_error(ctrl, "Don't know how to UA on a type %d node\n", ctrl->localtype);
		return;
	}
	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Sending UA\n", link->tei);
	}
	q921_transmit(ctrl, &h, 3);
}

static void q921_send_sabme(struct q921_link *link)
{
	q921_h h;
	struct pri *ctrl;

	ctrl = link->ctrl;

	Q921_CLEAR_INIT(&h, link->sapi, link->tei);
	h.u.m3 = 3;	/* M3 = 3 */
	h.u.m2 = 3;	/* M2 = 3 */
	h.u.p_f = 1;	/* Poll bit set */
	h.u.ft = Q921_FRAMETYPE_U;
	switch (ctrl->localtype) {
	case PRI_NETWORK:
		h.h.c_r = 1;
		break;
	case PRI_CPE:
		h.h.c_r = 0;
		break;
	default:
		pri_error(ctrl, "Don't know how to SABME on a type %d node\n", ctrl->localtype);
		return;
	}
	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Sending SABME\n", link->tei);
	}
	q921_transmit(ctrl, &h, 3);
}

static int q921_ack_packet(struct q921_link *link, int num)
{
	struct q921_frame *f;
	struct q921_frame *prev;
	struct pri *ctrl;

	ctrl = link->ctrl;

	for (prev = NULL, f = link->tx_queue; f; prev = f, f = f->next) {
		if (f->status != Q921_TX_FRAME_SENT) {
			break;
		}
		if (f->h.n_s == num) {
			/* Cancel each packet as necessary */
			/* That's our packet */
			if (prev)
				prev->next = f->next;
			else
				link->tx_queue = f->next;
			if (ctrl->debug & PRI_DEBUG_Q921_DUMP) {
				pri_message(ctrl,
					"-- ACKing N(S)=%d, tx_queue head is N(S)=%d (-1 is empty, -2 is not transmitted)\n",
					f->h.n_s,
					link->tx_queue
						? link->tx_queue->status == Q921_TX_FRAME_SENT
							? link->tx_queue->h.n_s
							: -2
						: -1);
			}
			/* Update v_a */
			free(f);
			return 1;
		}
	}
	return 0;
}

static void t203_expire(void *vlink);
static void t200_expire(void *vlink);

#define restart_t200(link) reschedule_t200(link)
static void reschedule_t200(struct q921_link *link)
{
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (ctrl->debug & PRI_DEBUG_Q921_DUMP)
		pri_message(ctrl, "-- Restarting T200 timer\n");
	pri_schedule_del(ctrl, link->t200_timer);
	link->t200_timer = pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T200], t200_expire, link);
}

#if 0
static void reschedule_t203(struct q921_link *link)
{
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (ctrl->debug & PRI_DEBUG_Q921_DUMP)
		pri_message(ctrl, "-- Restarting T203 timer\n");
	pri_schedule_del(ctrl, link->t203_timer);
	link->t203_timer = pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T203], t203_expire, link);
}
#endif

static void start_t203(struct q921_link *link)
{
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (link->t203_timer) {
		if (ctrl->debug & PRI_DEBUG_Q921_DUMP)
			pri_message(ctrl, "T203 requested to start without stopping first\n");
		pri_schedule_del(ctrl, link->t203_timer);
	}
	if (ctrl->debug & PRI_DEBUG_Q921_DUMP)
		pri_message(ctrl, "-- Starting T203 timer\n");
	link->t203_timer = pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T203], t203_expire, link);
}

static void stop_t203(struct q921_link *link)
{
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (link->t203_timer) {
		if (ctrl->debug & PRI_DEBUG_Q921_DUMP)
			pri_message(ctrl, "-- Stopping T203 timer\n");
		pri_schedule_del(ctrl, link->t203_timer);
		link->t203_timer = 0;
	} else {
		if (ctrl->debug & PRI_DEBUG_Q921_DUMP)
			pri_message(ctrl, "-- T203 requested to stop when not started\n");
	}
}

static void start_t200(struct q921_link *link)
{
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (link->t200_timer) {
		if (ctrl->debug & PRI_DEBUG_Q921_DUMP)
			pri_message(ctrl, "T200 requested to start without stopping first\n");
		pri_schedule_del(ctrl, link->t200_timer);
	}
	if (ctrl->debug & PRI_DEBUG_Q921_DUMP)
		pri_message(ctrl, "-- Starting T200 timer\n");
	link->t200_timer = pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T200], t200_expire, link);
}

static void stop_t200(struct q921_link *link)
{
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (link->t200_timer) {
		if (ctrl->debug & PRI_DEBUG_Q921_DUMP)
			pri_message(ctrl, "-- Stopping T200 timer\n");
		pri_schedule_del(ctrl, link->t200_timer);
		link->t200_timer = 0;
	} else {
		if (ctrl->debug & PRI_DEBUG_Q921_DUMP)
			pri_message(ctrl, "-- T200 requested to stop when not started\n");
	}
}

/*!
 * \internal
 * \brief Initiate bringing up layer 2 link.
 *
 * \param link Layer 2 link to bring up.
 *
 * \return Nothing
 */
static void kick_start_link(struct q921_link *link)
{
	struct pri *ctrl;

	ctrl = link->ctrl;

	switch (link->state) {
	case Q921_TEI_UNASSIGNED:
		if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
			pri_message(ctrl, "Kick starting link from no TEI.\n");
		}
		q921_setstate(link, Q921_ESTABLISH_AWAITING_TEI);
		q921_tei_request(link);
		break;
	case Q921_ASSIGN_AWAITING_TEI:
		if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
			pri_message(ctrl, "Kick starting link when awaiting TEI.\n");
		}
		q921_setstate(link, Q921_ESTABLISH_AWAITING_TEI);
		break;
	case Q921_TEI_ASSIGNED:
		if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
			pri_message(ctrl, "SAPI/TEI=%d/%d Kick starting link\n", link->sapi,
				link->tei);
		}
		q921_discard_iqueue(link);
		q921_establish_data_link(link);
		link->l3_initiated = 1;
		q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
		break;
	default:
		break;
	}
}

static void restart_timer_expire(void *vlink)
{
	struct q921_link *link = vlink;
	struct pri *ctrl;

	ctrl = link->ctrl;

	link->restart_timer = 0;

	switch (link->state) {
	case Q921_TEI_UNASSIGNED:
	case Q921_ASSIGN_AWAITING_TEI:
	case Q921_TEI_ASSIGNED:
		/* Try to bring layer 2 up. */
		kick_start_link(link);
		break;
	default:
		/* Looks like someone forgot to stop the restart timer. */
		pri_error(ctrl, "SAPI/TEI=%d/%d Link restart delay timer expired in state %d(%s)\n",
			link->sapi, link->tei, link->state, q921_state2str(link->state));
		break;
	}
}

static void restart_timer_stop(struct q921_link *link)
{
	struct pri *ctrl;

	ctrl = link->ctrl;
	pri_schedule_del(ctrl, link->restart_timer);
	link->restart_timer = 0;
}

/*! \note Only call on the transition to state Q921_TEI_ASSIGNED or already there. */
static void restart_timer_start(struct q921_link *link)
{
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (ctrl->debug & PRI_DEBUG_Q921_DUMP) {
		pri_message(ctrl, "SAPI/TEI=%d/%d Starting link restart delay timer\n",
			link->sapi, link->tei);
	}
	pri_schedule_del(ctrl, link->restart_timer);
	link->restart_timer =
		pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T200], restart_timer_expire, link);
}

/*! \note Only call on the transition to state Q921_TEI_ASSIGNED or already there. */
static pri_event *q921_check_delay_restart(struct q921_link *link)
{
	pri_event *ev;
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (ctrl->l2_persistence == PRI_L2_PERSISTENCE_KEEP_UP) {
		/*
		 * For PTP links:
		 * This is where we act a bit like L3 instead of L2, since we've
		 * got an L3 that depends on us keeping L2 automatically alive
		 * and happy.
		 *
		 * For PTMP links:
		 * We can optionally keep L2 automatically alive and happy.
		 */
		restart_timer_start(link);
	}
	if (PTP_MODE(ctrl)) {
		switch (link->state) {
		case Q921_MULTI_FRAME_ESTABLISHED:
		case Q921_TIMER_RECOVERY:
			/* Notify the upper layer that layer 2 went down. */
			ctrl->schedev = 1;
			ctrl->ev.gen.e = PRI_EVENT_DCHAN_DOWN;
			ev = &ctrl->ev;
			break;
		default:
			ev = NULL;
			break;
		}
	} else {
		ev = NULL;
	}
	return ev;
}

/*!
 * \brief Bring all layer 2 links up.
 *
 * \param ctrl D channel controller.
 *
 * \return Nothing
 */
void q921_bring_layer2_up(struct pri *ctrl)
{
	struct q921_link *link;

	if (PTMP_MODE(ctrl)) {
		/* Don't start with the broadcast link. */
		link = ctrl->link.next;
	} else {
		link = &ctrl->link;
	}
	for (; link; link = link->next) {
		if (!link->restart_timer) {
			/* A restart on the link is not already in the works. */
			kick_start_link(link);
		}
	}
}

/* This is the equivalent of the I-Frame queued up path in Figure B.7 in MULTI_FRAME_ESTABLISHED */
static int q921_send_queued_iframes(struct q921_link *link)
{
	struct pri *ctrl;
	struct q921_frame *f;
	int frames_txd = 0;

	ctrl = link->ctrl;

	for (f = link->tx_queue; f; f = f->next) {
		if (f->status != Q921_TX_FRAME_SENT) {
			/* This frame needs to be sent. */
			break;
		}
	}
	if (!f) {
		/* The Tx queue has no pending frames. */
		return 0;
	}

	if (link->peer_rx_busy) {
		/* Don't flood debug trace if not really looking at Q.921 layer. */
		if (ctrl->debug & (/* PRI_DEBUG_Q921_STATE | */ PRI_DEBUG_Q921_DUMP)) {
			pri_message(ctrl,
				"TEI=%d Couldn't transmit I-frame at this time due to peer busy condition\n",
				link->tei);
		}
		return 0;
	}
	if (link->v_s == Q921_ADD(link->v_a, ctrl->timers[PRI_TIMER_K])) {
		/* Don't flood debug trace if not really looking at Q.921 layer. */
		if (ctrl->debug & (/* PRI_DEBUG_Q921_STATE | */ PRI_DEBUG_Q921_DUMP)) {
			pri_message(ctrl,
				"TEI=%d Couldn't transmit I-frame at this time due to window shut\n",
				link->tei);
		}
		return 0;
	}

	/* Send all pending frames that fit in the window. */
	for (; f; f = f->next) {
		if (link->v_s == Q921_ADD(link->v_a, ctrl->timers[PRI_TIMER_K])) {
			/* The window is no longer open. */
			break;
		}

		/* Send it now... */
		switch (f->status) {
		case Q921_TX_FRAME_NEVER_SENT:
			if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
				pri_message(ctrl,
					"TEI=%d Transmitting N(S)=%d, window is open V(A)=%d K=%d\n",
					link->tei, link->v_s, link->v_a, ctrl->timers[PRI_TIMER_K]);
			}
			break;
		case Q921_TX_FRAME_PUSHED_BACK:
			if (f->h.n_s != link->v_s) {
				/* Should never happen. */
				pri_error(ctrl,
					"TEI=%d Retransmitting frame with old N(S)=%d as N(S)=%d!\n",
					link->tei, f->h.n_s, link->v_s);
			} else if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
				pri_message(ctrl, "TEI=%d Retransmitting frame N(S)=%d now!\n",
					link->tei, link->v_s);
			}
			break;
		default:
			/* Should never happen. */
			pri_error(ctrl, "Unexpected Tx Q frame status: %d", f->status);
			break;
		}

		/*
		 * Send the frame out on the assigned TEI.
		 * Done now because the frame may have been queued before we
		 * had an assigned TEI.
		 */
		f->h.h.tei = link->tei;

		f->h.n_s = link->v_s;
		f->h.n_r = link->v_r;
		f->h.ft = 0;
		f->h.p_f = 0;
		q921_transmit(ctrl, (q921_h *) (&f->h), f->len);
		Q921_INC(link->v_s);
		++frames_txd;

		if ((ctrl->debug & PRI_DEBUG_Q931_DUMP)
			&& f->status == Q921_TX_FRAME_NEVER_SENT) {
			/*
			 * The transmit operation might dump the Q.921 header, so logging
			 * the Q.931 message body after the transmit puts the sections of
			 * the message in the right order in the log.
			 *
			 * Also dump the Q.931 part only once instead of for every
			 * retransmission.
			 */
			q931_dump(ctrl, link->tei, (q931_h *) f->h.data, f->len - 4, 1);
		}
		f->status = Q921_TX_FRAME_SENT;
	}

	if (frames_txd) {
		link->acknowledge_pending = 0;
		if (!link->t200_timer) {
			stop_t203(link);
			start_t200(link);
		}
	}

	return frames_txd;
}

static void q921_reject(struct q921_link *link, int pf)
{
	q921_h h;
	struct pri *ctrl;

	ctrl = link->ctrl;

	Q921_CLEAR_INIT(&h, link->sapi, link->tei);
	h.s.x0 = 0;	/* Always 0 */
	h.s.ss = 2;	/* Reject */
	h.s.ft = 1;	/* Frametype (01) */
	h.s.n_r = link->v_r;	/* Where to start retransmission N(R) */
	h.s.p_f = pf;	
	switch (ctrl->localtype) {
	case PRI_NETWORK:
		h.h.c_r = 0;
		break;
	case PRI_CPE:
		h.h.c_r = 1;
		break;
	default:
		pri_error(ctrl, "Don't know how to REJ on a type %d node\n", ctrl->localtype);
		return;
	}
	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Sending REJ N(R)=%d\n", link->tei, link->v_r);
	}
	q921_transmit(ctrl, &h, 4);
}

static void q921_rr(struct q921_link *link, int pbit, int cmd)
{
	q921_h h;
	struct pri *ctrl;

	ctrl = link->ctrl;

	Q921_CLEAR_INIT(&h, link->sapi, link->tei);
	h.s.x0 = 0;	/* Always 0 */
	h.s.ss = 0; /* Receive Ready */
	h.s.ft = 1;	/* Frametype (01) */
	h.s.n_r = link->v_r;	/* N(R) */
	h.s.p_f = pbit;		/* Poll/Final set appropriately */
	switch (ctrl->localtype) {
	case PRI_NETWORK:
		if (cmd)
			h.h.c_r = 1;
		else
			h.h.c_r = 0;
		break;
	case PRI_CPE:
		if (cmd)
			h.h.c_r = 0;
		else
			h.h.c_r = 1;
		break;
	default:
		pri_error(ctrl, "Don't know how to RR on a type %d node\n", ctrl->localtype);
		return;
	}
#if 0	/* Don't flood debug trace with RR if not really looking at Q.921 layer. */
	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Sending RR N(R)=%d\n", link->tei, link->v_r);
	}
#endif
	q921_transmit(ctrl, &h, 4);
}

static void transmit_enquiry(struct q921_link *link)
{
	if (!link->own_rx_busy) {
		q921_rr(link, 1, 1);
		link->acknowledge_pending = 0;
		start_t200(link);
	} else {
		/* XXX: Implement me... */
	}
}

static void t200_expire(void *vlink)
{
	struct q921_link *link = vlink;
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (ctrl->debug & PRI_DEBUG_Q921_DUMP) {
		pri_message(ctrl, "%s\n", __FUNCTION__);
		q921_dump_pri(link, ' ');
	}

	link->t200_timer = 0;

	switch (link->state) {
	case Q921_MULTI_FRAME_ESTABLISHED:
		link->RC = 0;
		transmit_enquiry(link);
		link->RC++;
		q921_setstate(link, Q921_TIMER_RECOVERY);
		break;
	case Q921_TIMER_RECOVERY:
		/* SDL Flow Figure B.8/Q.921 Page 81 */
		if (link->RC != ctrl->timers[PRI_TIMER_N200]) {
#if 0
			if (link->v_s == link->v_a) {
				transmit_enquiry(link);
			}
#else
			/* We are chosing to enquiry by default (to reduce risk of T200 timer errors at the other
			 * side, instead of retransmission of the last I-frame we sent */
			transmit_enquiry(link);
#endif
			link->RC++;
		} else {
			q921_mdl_error(link, 'I');
			q921_establish_data_link(link);
			link->l3_initiated = 0;
			q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
			if (PTP_MODE(ctrl)) {
				ctrl->schedev = 1;
				ctrl->ev.gen.e = PRI_EVENT_DCHAN_DOWN;
			}
		}
		break;
	case Q921_AWAITING_ESTABLISHMENT:
		if (link->RC != ctrl->timers[PRI_TIMER_N200]) {
			link->RC++;
			q921_send_sabme(link);
			start_t200(link);
		} else {
			q921_check_delay_restart(link);
			q921_discard_iqueue(link);
			q921_mdl_error(link, 'G');
			q921_setstate(link, Q921_TEI_ASSIGNED);
			/* DL-RELEASE indication */
			q931_dl_event(link, Q931_DL_EVENT_DL_RELEASE_IND);
		}
		break;
	case Q921_AWAITING_RELEASE:
		if (link->RC != ctrl->timers[PRI_TIMER_N200]) {
			++link->RC;
			q921_send_disc(link, 1);
			start_t200(link);
		} else {
			q921_check_delay_restart(link);
			q921_mdl_error(link, 'H');
			/* DL-RELEASE confirm */
			q931_dl_event(link, Q931_DL_EVENT_DL_RELEASE_CONFIRM);
			q921_setstate(link, Q921_TEI_ASSIGNED);
		}
		break;
	default:
		/* Looks like someone forgot to stop the T200 timer. */
		pri_error(ctrl, "T200 expired in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		break;
	}
}

/* This is sending a DL-UNIT-DATA request */
int q921_transmit_uiframe(struct q921_link *link, void *buf, int len)
{
	uint8_t ubuf[512];
	q921_h *h = (void *)&ubuf[0];
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (len >= 512) {
		pri_error(ctrl, "Requested to send UI-frame larger than 512 bytes!\n");
		return -1;
	}

	memset(ubuf, 0, sizeof(ubuf));
	h->h.sapi = 0;
	h->h.ea1 = 0;
	h->h.ea2 = 1;
	h->h.tei = link->tei;
	h->u.m3 = 0;
	h->u.m2 = 0;
	h->u.p_f = 0;	/* Poll bit set */
	h->u.ft = Q921_FRAMETYPE_U;

	switch (ctrl->localtype) {
	case PRI_NETWORK:
		h->h.c_r = 1;
		break;
	case PRI_CPE:
		h->h.c_r = 0;
		break;
	default:
		pri_error(ctrl, "Don't know how to UI-frame on a type %d node\n", ctrl->localtype);
		return -1;
	}

	memcpy(h->u.data, buf, len);

	q921_transmit(ctrl, h, len + 3);

	return 0;
}

static struct q921_link *pri_find_tei(struct pri *ctrl, int sapi, int tei)
{
	struct q921_link *link;

	for (link = &ctrl->link; link; link = link->next) {
		if (link->tei == tei && link->sapi == sapi)
			return link;
	}

	return NULL;
}

/* This is the equivalent of a DL-DATA request, as well as the I-frame queued up outcome */
int q921_transmit_iframe(struct q921_link *link, void *buf, int len, int cr)
{
	struct q921_frame *f, *prev=NULL;
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (PTMP_MODE(ctrl)) {
		if (link->tei == Q921_TEI_GROUP) {
			pri_error(ctrl, "Huh?! For PTMP, we shouldn't be sending I-frames out the group TEI\n");
			return 0;
		}
		if (BRI_TE_PTMP(ctrl)) {
			switch (link->state) {
			case Q921_TEI_UNASSIGNED:
				q921_setstate(link, Q921_ESTABLISH_AWAITING_TEI);
				q921_tei_request(link);
				break;
			case Q921_ASSIGN_AWAITING_TEI:
				q921_setstate(link, Q921_ESTABLISH_AWAITING_TEI);
				break;
			default:
				break;
			}
		}
	} else {
		/* PTP modes, which shouldn't have subs */
	}

	/* Figure B.7/Q.921 Page 70 */
	switch (link->state) {
	case Q921_TEI_ASSIGNED:
		/* If we aren't in a state compatiable with DL-DATA requests, start getting us there here */
		restart_timer_stop(link);
		q921_establish_data_link(link);
		link->l3_initiated = 1;
		q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
		/* For all rest, we've done the work to get us up prior to this and fall through */
	case Q921_ESTABLISH_AWAITING_TEI:
	case Q921_TIMER_RECOVERY:
	case Q921_AWAITING_ESTABLISHMENT:
	case Q921_MULTI_FRAME_ESTABLISHED:
		/* Find queue tail. */
		for (f = link->tx_queue; f; f = f->next) {
			prev = f;
		}

		f = calloc(1, sizeof(struct q921_frame) + len + 2);
		if (f) {
			Q921_INIT(&f->h, link->sapi, link->tei);
			switch (ctrl->localtype) {
			case PRI_NETWORK:
				if (cr)
					f->h.h.c_r = 1;
				else
					f->h.h.c_r = 0;
				break;
			case PRI_CPE:
				if (cr)
					f->h.h.c_r = 0;
				else
					f->h.h.c_r = 1;
				break;
			}

			/* Put new frame on queue tail. */
			f->next = NULL;
			f->status = Q921_TX_FRAME_NEVER_SENT;
			f->len = len + 4;
			memcpy(f->h.data, buf, len);
			if (prev)
				prev->next = f;
			else
				link->tx_queue = f;

			if (link->state != Q921_MULTI_FRAME_ESTABLISHED) {
				if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
					pri_message(ctrl,
						"TEI=%d Just queued I-frame since in state %d(%s)\n",
						link->tei,
						link->state, q921_state2str(link->state));
				}
				break;
			}
			if (link->peer_rx_busy) {
				if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
					pri_message(ctrl,
						"TEI=%d Just queued I-frame due to peer busy condition\n",
						link->tei);
				}
				break;
			}

			if (!q921_send_queued_iframes(link)) {
				/*
				 * No frames sent even though we just put a frame on the queue.
				 *
				 * Special debug message/test here because we want to say what
				 * happened to the Q.931 message just queued but we don't want
				 * to flood the debug trace if we are not really looking at the
				 * Q.921 layer.
				 */
				if ((ctrl->debug & (PRI_DEBUG_Q921_STATE | PRI_DEBUG_Q921_DUMP))
					== PRI_DEBUG_Q921_STATE) {
					pri_message(ctrl, "TEI=%d Just queued I-frame due to window shut\n",
						link->tei);
				}
			}
		} else {
			pri_error(ctrl, "!! Out of memory for Q.921 transmit\n");
			return -1;
		}
		break;
	case Q921_TEI_UNASSIGNED:
	case Q921_ASSIGN_AWAITING_TEI:
	case Q921_AWAITING_RELEASE:
	default:
		pri_error(ctrl, "Cannot transmit frames in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		break;
	}
	return 0;
}

static void t203_expire(void *vlink)
{
	struct q921_link *link = vlink;
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (ctrl->debug & PRI_DEBUG_Q921_DUMP)
		pri_message(ctrl, "%s\n", __FUNCTION__);

	link->t203_timer = 0;

	switch (link->state) {
	case Q921_MULTI_FRAME_ESTABLISHED:
		transmit_enquiry(link);
		link->RC = 0;
		q921_setstate(link, Q921_TIMER_RECOVERY);
		break;
	default:
		/* Looks like someone forgot to stop the T203 timer. */
		pri_error(ctrl, "T203 expired in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		break;
	}
}

static void q921_dump_iqueue_info(struct q921_link *link)
{
	struct pri *ctrl;
	struct q921_frame *f;
	int pending = 0;
	int unacked = 0;

	ctrl = link->ctrl;

	for (f = link->tx_queue; f; f = f->next) {
		if (f->status == Q921_TX_FRAME_SENT) {
			unacked++;
		} else {
			pending++;
		}
	}

	pri_error(ctrl, "Number of pending packets %d, sent but unacked %d\n", pending, unacked);
}

static void q921_dump_pri_by_h(struct pri *ctrl, char direction_tag, q921_h *h);

void q921_dump(struct pri *ctrl, q921_h *h, int len, int debugflags, int txrx)
{
	int x;
	const char *type;
	char direction_tag;
	
	direction_tag = txrx ? '>' : '<';

	pri_message(ctrl, "\n");
	if (debugflags & PRI_DEBUG_Q921_DUMP) {
		q921_dump_pri_by_h(ctrl, direction_tag, h);
	}

	if (debugflags & PRI_DEBUG_Q921_RAW) {
		char *buf = malloc(len * 3 + 1);
		int buflen = 0;
		if (buf) {
			for (x=0;x<len;x++) 
				buflen += sprintf(buf + buflen, "%02x ", h->raw[x]);
			pri_message(ctrl, "%c [ %s]\n", direction_tag, buf);
			free(buf);
		}
	}

	if (debugflags & PRI_DEBUG_Q921_DUMP) {
		switch (h->h.data[0] & Q921_FRAMETYPE_MASK) {
		case 0:
		case 2:
			pri_message(ctrl, "%c Informational frame:\n", direction_tag);
			break;
		case 1:
			pri_message(ctrl, "%c Supervisory frame:\n", direction_tag);
			break;
		case 3:
			pri_message(ctrl, "%c Unnumbered frame:\n", direction_tag);
			break;
		}
		
		pri_message(ctrl, "%c SAPI: %02d  C/R: %d EA: %d\n",
			direction_tag,
			h->h.sapi, 
			h->h.c_r,
			h->h.ea1);
		pri_message(ctrl, "%c  TEI: %03d        EA: %d\n", 
			direction_tag,
			h->h.tei,
			h->h.ea2);
	
		switch (h->h.data[0] & Q921_FRAMETYPE_MASK) {
		case 0:
		case 2:
			/* Informational frame */
			pri_message(ctrl, "%c N(S): %03d   0: %d\n",
				direction_tag,
				h->i.n_s,
				h->i.ft);
			pri_message(ctrl, "%c N(R): %03d   P: %d\n",
				direction_tag,
				h->i.n_r,
				h->i.p_f);
			pri_message(ctrl, "%c %d bytes of data\n",
				direction_tag,
				len - 4);
			break;
		case 1:
			/* Supervisory frame */
			type = "???";
			switch (h->s.ss) {
			case 0:
				type = "RR (receive ready)";
				break;
			case 1:
				type = "RNR (receive not ready)";
				break;
			case 2:
				type = "REJ (reject)";
				break;
			}
			pri_message(ctrl, "%c Zero: %d     S: %d 01: %d  [ %s ]\n",
				direction_tag,
				h->s.x0,
				h->s.ss,
				h->s.ft,
				type);
			pri_message(ctrl, "%c N(R): %03d P/F: %d\n",
				direction_tag,
				h->s.n_r,
				h->s.p_f);
			pri_message(ctrl, "%c %d bytes of data\n",
				direction_tag,
				len - 4);
			break;
		case 3:		
			/* Unnumbered frame */
			type = "???";
			if (h->u.ft == 3) {
				switch (h->u.m3) {
				case 0:
					if (h->u.m2 == 3)
						type = "DM (disconnect mode)";
					else if (h->u.m2 == 0)
						type = "UI (unnumbered information)";
					break;
				case 2:
					if (h->u.m2 == 0)
						type = "DISC (disconnect)";
					break;
				case 3:
					if (h->u.m2 == 3)
						type = "SABME (set asynchronous balanced mode extended)";
					else if (h->u.m2 == 0)
						type = "UA (unnumbered acknowledgement)";
					break;
				case 4:
					if (h->u.m2 == 1)
						type = "FRMR (frame reject)";
					break;
				case 5:
					if (h->u.m2 == 3)
						type = "XID (exchange identification note)";
					break;
				default:
					break;
				}
			}
			pri_message(ctrl, "%c   M3: %d   P/F: %d M2: %d 11: %d  [ %s ]\n",
				direction_tag,
				h->u.m3,
				h->u.p_f,
				h->u.m2,
				h->u.ft,
				type);
			pri_message(ctrl, "%c %d bytes of data\n",
				direction_tag,
				len - 3);
			break;
		}
	
		if ((h->u.ft == 3) && (h->u.m3 == 0) && (h->u.m2 == 0) && (h->u.data[0] == 0x0f)) {
			int ri;
			u_int8_t *action;
	
			/* TEI management related */
			type = q921_tei_mgmt2str(h->u.data[3]);
			pri_message(ctrl, "%c MDL Message: %d(%s)\n", direction_tag, h->u.data[3], type);
			ri = (h->u.data[1] << 8) | h->u.data[2];
			pri_message(ctrl, "%c Ri: %d\n", direction_tag, ri);
			action = &h->u.data[4];
			for (x = len - (action - (u_int8_t *) h); 0 < x; --x, ++action) {
				pri_message(ctrl, "%c Ai: %d E:%d\n",
					direction_tag, (*action >> 1) & 0x7f, *action & 0x01);
			}
		}
	}
}

static void q921_dump_pri(struct q921_link *link, char direction_tag)
{
	struct pri *ctrl;

	ctrl = link->ctrl;

	pri_message(ctrl, "%c TEI: %d State %d(%s)\n",
		direction_tag, link->tei, link->state, q921_state2str(link->state));
	pri_message(ctrl, "%c V(A)=%d, V(S)=%d, V(R)=%d\n",
		direction_tag, link->v_a, link->v_s, link->v_r);
	pri_message(ctrl, "%c K=%d, RC=%d, l3_initiated=%d, reject_except=%d, ack_pend=%d\n",
		direction_tag, ctrl->timers[PRI_TIMER_K], link->RC, link->l3_initiated,
		link->reject_exception, link->acknowledge_pending);
	pri_message(ctrl, "%c T200_id=%d, N200=%d, T203_id=%d\n",
		direction_tag, link->t200_timer, ctrl->timers[PRI_TIMER_N200], link->t203_timer);
}

static void q921_dump_pri_by_h(struct pri *ctrl, char direction_tag, q921_h *h)
{
	struct q921_link *link;

	if (!ctrl) {
		return;
	}

	if (BRI_NT_PTMP(ctrl)) {
		link = pri_find_tei(ctrl, h->h.sapi, h->h.tei);
	} else if (BRI_TE_PTMP(ctrl)) {
		/* We're operating on the specific TEI link */
		link = ctrl->link.next;
	} else {
		link = &ctrl->link;
	}

	if (link) {
		q921_dump_pri(link, direction_tag);
	} else {
		pri_message(ctrl, "%c Link not found for this frame.\n", direction_tag);
	}
}

#define Q921_TEI_CHECK_MAX_POLLS	2

static void t201_expire(void *vctrl)
{
	struct pri *ctrl;
	struct q921_link *link;
	struct q921_link *link_next;

	ctrl = vctrl;

	/* Start the TEI check timer. */
	ctrl->t201_timer =
		pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T201], t201_expire, ctrl);

	++ctrl->t201_expirycnt;
	if (Q921_TEI_CHECK_MAX_POLLS < ctrl->t201_expirycnt) {
		pri_schedule_del(ctrl, ctrl->t201_timer);
		ctrl->t201_timer = 0;

		/* Reclaim any dead TEI links. */
		for (link = ctrl->link.next; link; link = link_next) {
			link_next = link->next;

			switch (link->tei_check) {
			case Q921_TEI_CHECK_DEAD:
				link->tei_check = Q921_TEI_CHECK_NONE;
				q921_tei_remove(ctrl, link->tei);
				q921_mdl_destroy(link);
				break;
			default:
				link->tei_check = Q921_TEI_CHECK_NONE;
				break;
			}
		}
		return;
	}

	if (!ctrl->t201_timer) {
		pri_error(ctrl, "Could not start T201 timer.");

		/* Abort the remaining TEI check. */
		for (link = ctrl->link.next; link; link = link->next) {
			link->tei_check = Q921_TEI_CHECK_NONE;
		}
		return;
	}

	if (ctrl->t201_expirycnt == 1) {
		/* First poll.  Setup TEI check state. */
		for (link = ctrl->link.next; link; link = link->next) {
			if (link->state < Q921_TEI_ASSIGNED) {
				/* We do not have a TEI. */
				link->tei_check = Q921_TEI_CHECK_NONE;
			} else {
				/* Mark TEI as dead until proved otherwise. */
				link->tei_check = Q921_TEI_CHECK_DEAD;
			}
		}
	} else {
		/* Subsequent polls.  Setup for new TEI check poll. */
		for (link = ctrl->link.next; link; link = link->next) {
			switch (link->tei_check) {
			case Q921_TEI_CHECK_REPLY:
				link->tei_check = Q921_TEI_CHECK_DEAD_REPLY;
				break;
			default:
				break;
			}
		}
	}
	q921_mdl_send(ctrl, Q921_TEI_IDENTITY_CHECK_REQUEST, 0, Q921_TEI_GROUP, 1);
}

static void q921_tei_check(struct pri *ctrl)
{
	if (ctrl->t201_timer) {
		/* TEI check procedure already in progress.  Do not disturb it. */
		return;
	}
	ctrl->t201_expirycnt = 0;
	t201_expire(ctrl);
}

static void q921_mdl_ignore(struct pri *ctrl, q921_u *h, const char *reason)
{
	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		/*
		 * Send out this message in debug modes since it is possible the
		 * user has misconfigured their link for the wrong mode.
		 */
		pri_message(ctrl, "Ignoring MDL message: %d(%s)  %s\n",
			h->data[3], q921_tei_mgmt2str(h->data[3]), reason);
	}
}

static pri_event *q921_mdl_receive(struct pri *ctrl, q921_u *h, int len)
{
	int ri;
	struct q921_link *sub;
	struct q921_link *link;
	pri_event *res = NULL;
	u_int8_t *action;
	int count;
	int tei;

	if (len <= &h->data[0] - (u_int8_t *) h) {
		pri_error(ctrl, "Received short MDL frame\n");
		return NULL;
	}
	if (h->data[0] != 0x0f) {
		pri_error(ctrl, "Received MDL with unsupported management entity %02x\n",
			h->data[0]);
		return NULL;
	}
	if (len <= &h->data[4] - (u_int8_t *) h) {
		pri_error(ctrl, "Received short MDL message\n");
		return NULL;
	}
	if (h->data[3] != Q921_TEI_IDENTITY_CHECK_RESPONSE
		&& !(h->data[4] & 0x01)) {
		pri_error(ctrl, "Received MDL message: %d(%s) with Ai E bit not set.\n",
			h->data[3], q921_tei_mgmt2str(h->data[3]));
		return NULL;
	}
	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "Received MDL message: %d(%s)\n",
			h->data[3], q921_tei_mgmt2str(h->data[3]));
	}
	if (PTP_MODE(ctrl) && NT_MODE(ctrl)) {
		/*
		 * We are not managing automatic TEI's in this mode so we can
		 * ignore MDL messages from the CPE.
		 */
		q921_mdl_ignore(ctrl, h, "We are in NT-PTP mode.");
		return NULL;
	}
	ri = (h->data[1] << 8) | h->data[2];
	tei = (h->data[4] >> 1);

	switch (h->data[3]) {
	case Q921_TEI_IDENTITY_REQUEST:
		if (!BRI_NT_PTMP(ctrl)) {
			q921_mdl_ignore(ctrl, h, "We are not in NT-PTMP mode.");
			return NULL;
		}

		if (tei != Q921_TEI_GROUP) {
			pri_error(ctrl, "Received %s with invalid TEI %d\n",
				q921_tei_mgmt2str(Q921_TEI_IDENTITY_REQUEST), tei);
			q921_mdl_send(ctrl, Q921_TEI_IDENTITY_DENIED, ri, tei, 1);
			return NULL;
		}

		/* Find a TEI that is not allocated. */
		tei = Q921_TEI_AUTO_FIRST;
		do {
			for (sub = &ctrl->link; sub->next; sub = sub->next) {
				if (sub->next->tei == tei) {
					/* This TEI is already assigned, try next one. */
					++tei;
					if (tei <= Q921_TEI_AUTO_LAST) {
						break;
					}
					pri_error(ctrl, "TEI pool exhausted.  Reclaiming dead TEIs.\n");
					q921_mdl_send(ctrl, Q921_TEI_IDENTITY_DENIED, ri, Q921_TEI_GROUP, 1);
					q921_tei_check(ctrl);
					return NULL;
				}
			}
		} while (sub->next);

		if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
			pri_message(ctrl, "Allocating new TEI %d\n", tei);
		}
		link = pri_link_new(ctrl, Q921_SAPI_CALL_CTRL, tei);
		if (!link) {
			pri_error(ctrl, "Unable to allocate layer 2 link for new TEI %d\n", tei);
			return NULL;
		}
		sub->next = link;
		q921_setstate(link, Q921_TEI_ASSIGNED);
		q921_mdl_send(ctrl, Q921_TEI_IDENTITY_ASSIGNED, ri, tei, 1);

		count = 0;
		for (sub = ctrl->link.next; sub; sub = sub->next) {
			++count;
		}
		if (Q921_TEI_AUTO_LAST - Q921_TEI_AUTO_FIRST + 1 <= count) {
			/*
			 * We just allocated the last TEI.  Try to reclaim dead TEIs
			 * before another is requested.
			 */
			if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
				pri_message(ctrl, "Allocated last TEI.  Reclaiming dead TEIs.\n");
			}
			q921_tei_check(ctrl);
		}

		if (ctrl->l2_persistence == PRI_L2_PERSISTENCE_KEEP_UP) {
			/*
			 * Layer 2 is persistent so give the peer some time to setup
			 * it's new TEI and bring the link up itself before we bring the
			 * link up.
			 */
			restart_timer_start(link);
		}
		break;
	case Q921_TEI_IDENTITY_CHECK_RESPONSE:
		if (!BRI_NT_PTMP(ctrl)) {
			/* Silently ignore the message since we never asked for the check. */
			return NULL;
		}

		/* For each TEI listed in the message */
		action = &h->data[4];
		len -= (action - (u_int8_t *) h);
		for (; len; --len, ++action) {
			if (*action & 0x01) {
				/* This is the last TEI in the list because the Ai E bit is set. */
				len = 1;
			}
			tei = (*action >> 1);

			if (tei == Q921_TEI_GROUP) {
				pri_error(ctrl, "Received %s with invalid TEI %d\n",
					q921_tei_mgmt2str(Q921_TEI_IDENTITY_CHECK_RESPONSE), tei);
				continue;
			}

			for (sub = ctrl->link.next; sub; sub = sub->next) {
				if (sub->tei == tei) {
					/* Found the TEI. */
					switch (sub->tei_check) {
					case Q921_TEI_CHECK_NONE:
						break;
					case Q921_TEI_CHECK_DEAD:
					case Q921_TEI_CHECK_DEAD_REPLY:
						sub->tei_check = Q921_TEI_CHECK_REPLY;
						break;
					case Q921_TEI_CHECK_REPLY:
						/* Duplicate TEI detected. */
						sub->tei_check = Q921_TEI_CHECK_NONE;
						q921_tei_remove(ctrl, tei);
						q921_mdl_destroy(sub);
						break;
					}
					break;
				}
			}
			if (!sub) {
				/* TEI not found. */
				q921_tei_remove(ctrl, tei);
			}
		}
		break;
	case Q921_TEI_IDENTITY_VERIFY:
		if (!BRI_NT_PTMP(ctrl)) {
			q921_mdl_ignore(ctrl, h, "We are not in NT-PTMP mode.");
			return NULL;
		}
		if (tei == Q921_TEI_GROUP) {
			pri_error(ctrl, "Received %s with invalid TEI %d\n",
				q921_tei_mgmt2str(Q921_TEI_IDENTITY_VERIFY), tei);
			return NULL;
		}
		q921_tei_check(ctrl);
		break;
	case Q921_TEI_IDENTITY_ASSIGNED:
		if (NT_MODE(ctrl)) {
			/* We should not be receiving this message. */
			q921_mdl_ignore(ctrl, h, "We are the network.");
			return NULL;
		}
		if (!BRI_TE_PTMP(ctrl)) {
			/*
			 * Silently ignore the message.  It must not be for us
			 * since we will never ask for one.
			 */
			return NULL;
		}

		/* We're operating on the specific TEI link here */
		link = ctrl->link.next;
		
		switch (link->state) {
		case Q921_TEI_UNASSIGNED:
			/*
			 * We do not have a TEI and we are not currently asking for one.
			 * Start asking for one.
			 */
			q921_setstate(link, Q921_ASSIGN_AWAITING_TEI);
			q921_tei_request(link);
			return NULL;
		case Q921_ASSIGN_AWAITING_TEI:
		case Q921_ESTABLISH_AWAITING_TEI:
			/* We do not have a TEI and we want one. */
			break;
		default:
			/* We already have a TEI. */
			if (tei == link->tei) {
				/*
				 * The TEI assignment conflicts with ours.  Our TEI is the
				 * duplicate so we should remove it.  Q.921 Section 5.3.4.2
				 * condition c.
				 */
				pri_error(ctrl, "TEI=%d Conflicting TEI assignment.  Removing our TEI.\n",
					tei);
				q921_mdl_remove(link);
				q921_start(link);
			}
			return NULL;
		}

		if (ri != link->ri) {
			if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
				pri_message(ctrl,
					"TEI assignment received for another Ri %02x (ours is %02x)\n",
					ri, link->ri);
			}
			return NULL;
		}

		pri_schedule_del(ctrl, link->t202_timer);
		link->t202_timer = 0;

		link->tei = tei;
		if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
			pri_message(ctrl, "Got assigned TEI %d\n", tei);
		}

		switch (link->state) {
		case Q921_ASSIGN_AWAITING_TEI:
			q921_setstate(link, Q921_TEI_ASSIGNED);
			if (ctrl->l2_persistence != PRI_L2_PERSISTENCE_KEEP_UP) {
				ctrl->ev.gen.e = PRI_EVENT_DCHAN_UP;
				res = &ctrl->ev;
				break;
			}
			/* Fall through: Layer 2 is persistent so bring it up. */
		case Q921_ESTABLISH_AWAITING_TEI:
			q921_establish_data_link(link);
			link->l3_initiated = 1;
			q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
			ctrl->ev.gen.e = PRI_EVENT_DCHAN_UP;
			res = &ctrl->ev;
			break;
		default:
			break;
		}
		break;
	case Q921_TEI_IDENTITY_CHECK_REQUEST:
		if (NT_MODE(ctrl)) {
			/* We should not be receiving this message. */
			q921_mdl_ignore(ctrl, h, "We are the network.");
			return NULL;
		}

		if (PTP_MODE(ctrl)) {
			/*
			 * Some telco switches/devices get very unhappy if we don't
			 * respond to the TEI check request with our permanently
			 * assigned TEI.
			 */
			link = &ctrl->link;
		} else if (BRI_TE_PTMP(ctrl)) {
			/* We're operating on the specific TEI link here */
			link = ctrl->link.next;

			if (link->state < Q921_TEI_ASSIGNED) {
				/* We do not have a TEI. */
				return NULL;
			}
		} else {
			/* Should never get here. */
			return NULL;
		}

		/* If it's addressed to the group TEI or to our TEI specifically, we respond */
		if (tei == Q921_TEI_GROUP || tei == link->tei) {
			q921_mdl_send(ctrl, Q921_TEI_IDENTITY_CHECK_RESPONSE, random() % 65535, link->tei, 1);
		}
		break;
	case Q921_TEI_IDENTITY_REMOVE:
		if (NT_MODE(ctrl)) {
			/* We should not be receiving this message. */
			q921_mdl_ignore(ctrl, h, "We are the network.");
			return NULL;
		}
		if (!BRI_TE_PTMP(ctrl)) {
			/*
			 * Silently ignore the message.  If we are TE-PTP our
			 * TEI is permanently assigned and cannot be removed.
			 */
			return NULL;
		}

		/* We're operating on the specific TEI link here */
		link = ctrl->link.next;

		if (link->state < Q921_TEI_ASSIGNED) {
			/* We do not have a TEI. */
			return NULL;
		}

		/* If it's addressed to the group TEI or to our TEI specifically, we respond */
		if (tei == Q921_TEI_GROUP || tei == link->tei) {
			q921_mdl_remove(link);
			q921_start(link);
		}
		break;
	}
	return res;	/* Do we need to return something??? */
}

static int is_command(struct pri *ctrl, q921_h *h)
{
	int command = 0;
	int c_r = h->s.h.c_r;

	if ((ctrl->localtype == PRI_NETWORK && c_r == 0) ||
		(ctrl->localtype == PRI_CPE && c_r == 1))
		command = 1;

	return command;
}

static void q921_clear_exception_conditions(struct q921_link *link)
{
	link->own_rx_busy = 0;
	link->peer_rx_busy = 0;
	link->reject_exception = 0;
	link->acknowledge_pending = 0;
}

static pri_event *q921_sabme_rx(struct q921_link *link, q921_h *h)
{
	pri_event *res = NULL;
	struct pri *ctrl;
	enum Q931_DL_EVENT delay_q931_dl_event;

	ctrl = link->ctrl;

	switch (link->state) {
	case Q921_TIMER_RECOVERY:
		/* Timer recovery state handling is same as multiframe established */
	case Q921_MULTI_FRAME_ESTABLISHED:
		/* Send Unnumbered Acknowledgement */
		q921_send_ua(link, h->u.p_f);
		q921_clear_exception_conditions(link);
		q921_mdl_error(link, 'F');
		if (link->v_s != link->v_a) {
			q921_discard_iqueue(link);
			/* DL-ESTABLISH indication */
			delay_q931_dl_event = Q931_DL_EVENT_DL_ESTABLISH_IND;
		} else {
			delay_q931_dl_event = Q931_DL_EVENT_NONE;
		}
		stop_t200(link);
		start_t203(link);
		link->v_s = link->v_a = link->v_r = 0;
		q921_setstate(link, Q921_MULTI_FRAME_ESTABLISHED);
		if (delay_q931_dl_event != Q931_DL_EVENT_NONE) {
			/* Delayed because Q.931 could send STATUS messages. */
			q931_dl_event(link, delay_q931_dl_event);
		}
		break;
	case Q921_TEI_ASSIGNED:
		restart_timer_stop(link);
		q921_send_ua(link, h->u.p_f);
		q921_clear_exception_conditions(link);
		link->v_s = link->v_a = link->v_r = 0;
		/* DL-ESTABLISH indication */
		delay_q931_dl_event = Q931_DL_EVENT_DL_ESTABLISH_IND;
		if (PTP_MODE(ctrl)) {
			ctrl->ev.gen.e = PRI_EVENT_DCHAN_UP;
			res = &ctrl->ev;
		}
		start_t203(link);
		q921_setstate(link, Q921_MULTI_FRAME_ESTABLISHED);
		if (delay_q931_dl_event != Q931_DL_EVENT_NONE) {
			/* Delayed because Q.931 could send STATUS messages. */
			q931_dl_event(link, delay_q931_dl_event);
		}
		break;
	case Q921_AWAITING_ESTABLISHMENT:
		q921_send_ua(link, h->u.p_f);
		break;
	case Q921_AWAITING_RELEASE:
		q921_send_dm(link, h->u.p_f);
		break;
	default:
		pri_error(ctrl, "Cannot handle SABME in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		break;
	}

	return res;
}

static pri_event *q921_disc_rx(struct q921_link *link, q921_h *h)
{
	pri_event *res = NULL;
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Got DISC\n", link->tei);
	}

	switch (link->state) {
	case Q921_TEI_ASSIGNED:
	case Q921_AWAITING_ESTABLISHMENT:
		q921_send_dm(link, h->u.p_f);
		break;
	case Q921_AWAITING_RELEASE:
		q921_send_ua(link, h->u.p_f);
		break;
	case Q921_MULTI_FRAME_ESTABLISHED:
	case Q921_TIMER_RECOVERY:
		res = q921_check_delay_restart(link);
		q921_discard_iqueue(link);
		q921_send_ua(link, h->u.p_f);
		/* DL-RELEASE indication */
		q931_dl_event(link, Q931_DL_EVENT_DL_RELEASE_IND);
		stop_t200(link);
		if (link->state == Q921_MULTI_FRAME_ESTABLISHED)
			stop_t203(link);
		q921_setstate(link, Q921_TEI_ASSIGNED);
		break;
	default:
		pri_error(ctrl, "Don't know what to do with DISC in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		break;
	}

	return res;
}

static void q921_mdl_remove(struct q921_link *link)
{
	int mdl_free_me;
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "MDL-REMOVE: Removing TEI %d\n", link->tei);
	}
	if (BRI_NT_PTMP(ctrl)) {
		if (link == &ctrl->link) {
			pri_error(ctrl, "Bad bad bad!  Cannot MDL-REMOVE master\n");
			return;
		}
		mdl_free_me = 1;
	} else {
		mdl_free_me = 0;
	}

	switch (link->state) {
	case Q921_TEI_ASSIGNED:
		if (mdl_free_me) {
			restart_timer_stop(link);
		}
		/* XXX: deviation! Since we don't have a UI queue, we just discard our I-queue */
		q921_discard_iqueue(link);
		q921_setstate(link, Q921_TEI_UNASSIGNED);
		break;
	case Q921_AWAITING_ESTABLISHMENT:
		q921_discard_iqueue(link);
		/* DL-RELEASE indication */
		q931_dl_event(link, Q931_DL_EVENT_DL_RELEASE_IND);
		stop_t200(link);
		q921_setstate(link, Q921_TEI_UNASSIGNED);
		break;
	case Q921_AWAITING_RELEASE:
		q921_discard_iqueue(link);
		/* DL-RELEASE confirm */
		q931_dl_event(link, Q931_DL_EVENT_DL_RELEASE_CONFIRM);
		stop_t200(link);
		q921_setstate(link, Q921_TEI_UNASSIGNED);
		break;
	case Q921_MULTI_FRAME_ESTABLISHED:
		q921_discard_iqueue(link);
		/* DL-RELEASE indication */
		q931_dl_event(link, Q931_DL_EVENT_DL_RELEASE_IND);
		stop_t200(link);
		stop_t203(link);
		q921_setstate(link, Q921_TEI_UNASSIGNED);
		break;
	case Q921_TIMER_RECOVERY:
		q921_discard_iqueue(link);
		/* DL-RELEASE indication */
		q931_dl_event(link, Q931_DL_EVENT_DL_RELEASE_IND);
		stop_t200(link);
		q921_setstate(link, Q921_TEI_UNASSIGNED);
		break;
	default:
		pri_error(ctrl, "MDL-REMOVE when in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		return;
	}

	q931_dl_event(link, Q931_DL_EVENT_TEI_REMOVAL);

	/*
	 * Negate the TEI value so debug messages will display a
	 * negated TEI when it is actually unassigned.
	 */
	link->tei = -link->tei;

	link->mdl_free_me = mdl_free_me;
}

static void q921_mdl_link_destroy(struct q921_link *link)
{
	struct pri *ctrl;
	struct q921_link *freep;
	struct q921_link *prev;

	ctrl = link->ctrl;

	freep = NULL;
	for (prev = &ctrl->link; prev->next; prev = prev->next) {
		if (prev->next == link) {
			prev->next = link->next;
			freep = link;
			break;
		}
	}
	if (freep == NULL) {
		pri_error(ctrl, "Huh!? no match found in list for TEI %d\n", -link->tei);
		return;
	}

	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "Freeing TEI of %d\n", -freep->tei);
	}

	pri_link_destroy(freep);
}

static void q921_mdl_destroy(struct q921_link *link)
{
	q921_mdl_remove(link);
	if (link->mdl_free_me) {
		q921_mdl_link_destroy(link);
	}
}

static void q921_mdl_handle_network_error(struct q921_link *link, char error)
{
	struct pri *ctrl;

	switch (error) {
	case 'C':
	case 'D':
	case 'G':
	case 'H':
		q921_mdl_remove(link);
		break;
	case 'A':
	case 'B':
	case 'E':
	case 'F':
	case 'I':
	case 'J':
	case 'K':
		break;
	default:
		ctrl = link->ctrl;
		pri_error(ctrl, "Network MDL can't handle error of type %c\n", error);
		break;
	}
}

static void q921_mdl_handle_cpe_error(struct q921_link *link, char error)
{
	struct pri *ctrl;

	switch (error) {
	case 'C':
	case 'D':
	case 'G':
	case 'H':
		q921_mdl_remove(link);
		break;
	case 'A':
	case 'B':
	case 'E':
	case 'F':
	case 'I':
	case 'J':
	case 'K':
		break;
	default:
		ctrl = link->ctrl;
		pri_error(ctrl, "CPE MDL can't handle error of type %c\n", error);
		break;
	}
}

static void q921_mdl_handle_ptp_error(struct q921_link *link, char error)
{
	struct pri *ctrl;

	ctrl = link->ctrl;

	switch (error) {
	case 'J':
		/*
		 * This is for the transition to Q921_AWAITING_ESTABLISHMENT.
		 * The event is genereated here rather than where the MDL_ERROR
		 * 'J' is posted because of the potential event conflict with
		 * incoming I-frame information passed to Q.931.
		 */
		ctrl->schedev = 1;
		ctrl->ev.gen.e = PRI_EVENT_DCHAN_DOWN;
		break;
	case 'A':
	case 'B':
	case 'C':
	case 'D':
	case 'E':
	case 'F':
	case 'G':
	case 'H':
	case 'I':
	case 'K':
		break;
	default:
		pri_error(ctrl, "PTP MDL can't handle error of type %c\n", error);
		break;
	}
}

static void q921_mdl_handle_error(struct q921_link *link, char error)
{
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (PTP_MODE(ctrl)) {
		q921_mdl_handle_ptp_error(link, error);
	} else {
		if (ctrl->localtype == PRI_NETWORK) {
			q921_mdl_handle_network_error(link, error);
		} else {
			q921_mdl_handle_cpe_error(link, error);
		}
	}
}

static void q921_mdl_handle_error_callback(void *vlink)
{
	struct q921_link *link = vlink;

	q921_mdl_handle_error(link, link->mdl_error);

	link->mdl_error = 0;
	link->mdl_timer = 0;

	if (link->mdl_free_me) {
		q921_mdl_link_destroy(link);
	}
}

static void q921_mdl_error(struct q921_link *link, char error)
{
	int is_debug_q921_state;
	struct pri *ctrl;

	ctrl = link->ctrl;

	/* Log the MDL-ERROR event when detected. */
	is_debug_q921_state = (ctrl->debug & PRI_DEBUG_Q921_STATE);
	switch (error) {
	case 'A':
		pri_message(ctrl,
			"TEI=%d MDL-ERROR (A): Got supervisory frame with F=1 in state %d(%s)\n",
			link->tei, link->state, q921_state2str(link->state));
		break;
	case 'B':
	case 'E':
		pri_message(ctrl, "TEI=%d MDL-ERROR (%c): DM (F=%c) in state %d(%s)\n",
			link->tei, error, (error == 'B') ? '1' : '0',
			link->state, q921_state2str(link->state));
		break;
	case 'C':
	case 'D':
		if (is_debug_q921_state || PTP_MODE(ctrl)) {
			pri_message(ctrl, "TEI=%d MDL-ERROR (%c): UA (F=%c) in state %d(%s)\n",
				link->tei, error, (error == 'C') ? '1' : '0',
				link->state, q921_state2str(link->state));
		}
		break;
	case 'F':
		/*
		 * The peer is restarting the link.
		 * Some reasons this might happen:
		 * 1) Our link establishment requests collided.
		 * 2) They got reset.
		 * 3) They could not talk to us for some reason because
		 * their T200 timer expired N200 times.
		 * 4) They got an MDL-ERROR (J).
		 */
		if (is_debug_q921_state) {
			/*
			 * This message is rather annoying and is normal for
			 * reasons 1-3 above.
			 */
			pri_message(ctrl, "TEI=%d MDL-ERROR (F): SABME in state %d(%s)\n",
				link->tei, link->state, q921_state2str(link->state));
		}
		break;
	case 'G':
		/* We could not get a response from the peer. */
		if (is_debug_q921_state) {
			pri_message(ctrl,
				"TEI=%d MDL-ERROR (G): T200 expired N200 times sending SABME in state %d(%s)\n",
				link->tei, link->state, q921_state2str(link->state));
		}
		break;
	case 'H':
		/* We could not get a response from the peer. */
		if (is_debug_q921_state) {
			pri_message(ctrl,
				"TEI=%d MDL-ERROR (H): T200 expired N200 times sending DISC in state %d(%s)\n",
				link->tei, link->state, q921_state2str(link->state));
		}
		break;
	case 'I':
		/* We could not get a response from the peer. */
		if (is_debug_q921_state) {
			pri_message(ctrl,
				"TEI=%d MDL-ERROR (I): T200 expired N200 times sending RR/RNR in state %d(%s)\n",
				link->tei, link->state, q921_state2str(link->state));
		}
		break;
	case 'J':
		/* N(R) not within ack window. */
		pri_error(ctrl, "TEI=%d MDL-ERROR (J): N(R) error in state %d(%s)\n",
			link->tei, link->state, q921_state2str(link->state));
		break;
	case 'K':
		/*
		 * Received a frame reject frame.
		 * The other end does not like what we are doing at all for some reason.
		 */
		pri_error(ctrl, "TEI=%d MDL-ERROR (K): FRMR in state %d(%s)\n",
			link->tei, link->state, q921_state2str(link->state));
		break;
	default:
		pri_message(ctrl, "TEI=%d MDL-ERROR (%c): in state %d(%s)\n",
			link->tei, error, link->state, q921_state2str(link->state));
		break;
	}

	if (link->mdl_error) {
		/* This should not happen. */
		pri_error(ctrl,
			"Trying to queue MDL-ERROR (%c) when MDL-ERROR (%c) is already scheduled\n",
			error, link->mdl_error);
		return;
	}
	link->mdl_error = error;
	link->mdl_timer = pri_schedule_event(ctrl, 0, q921_mdl_handle_error_callback, link);
	if (!link->mdl_timer) {
		/* Timer allocation failed */
		link->mdl_error = 0;
	}
}

static pri_event *q921_ua_rx(struct q921_link *link, q921_h *h)
{
	struct pri *ctrl;
	pri_event *res = NULL;
	enum Q931_DL_EVENT delay_q931_dl_event;

	ctrl = link->ctrl;

	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Got UA\n", link->tei);
	}

	switch (link->state) {
	case Q921_TEI_ASSIGNED:
	case Q921_MULTI_FRAME_ESTABLISHED:
	case Q921_TIMER_RECOVERY:
		if (h->u.p_f) {
			q921_mdl_error(link, 'C');
		} else {
			q921_mdl_error(link, 'D');
		}
		break;
	case Q921_AWAITING_ESTABLISHMENT:
		if (!h->u.p_f) {
			q921_mdl_error(link, 'D');
			break;
		}

		delay_q931_dl_event = Q931_DL_EVENT_NONE;
		if (!link->l3_initiated) {
			if (link->v_s != link->v_a) {
				q921_discard_iqueue(link);
				/* DL-ESTABLISH indication */
				delay_q931_dl_event = Q931_DL_EVENT_DL_ESTABLISH_IND;
			}
		} else {
			link->l3_initiated = 0;
			/* DL-ESTABLISH confirm */
			delay_q931_dl_event = Q931_DL_EVENT_DL_ESTABLISH_CONFIRM;
		}

		if (PTP_MODE(ctrl)) {
			ctrl->ev.gen.e = PRI_EVENT_DCHAN_UP;
			res = &ctrl->ev;
		}

		stop_t200(link);
		start_t203(link);

		link->v_r = link->v_s = link->v_a = 0;

		q921_setstate(link, Q921_MULTI_FRAME_ESTABLISHED);
		if (delay_q931_dl_event != Q931_DL_EVENT_NONE) {
			/* Delayed because Q.931 could send STATUS messages. */
			q931_dl_event(link, delay_q931_dl_event);
		}
		break;
	case Q921_AWAITING_RELEASE:
		if (!h->u.p_f) {
			q921_mdl_error(link, 'D');
		} else {
			res = q921_check_delay_restart(link);
			/* DL-RELEASE confirm */
			q931_dl_event(link, Q931_DL_EVENT_DL_RELEASE_CONFIRM);
			stop_t200(link);
			q921_setstate(link, Q921_TEI_ASSIGNED);
		}
		break;
	default:
		pri_error(ctrl, "Don't know what to do with UA in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		break;
	}

	return res;
}

static void q921_enquiry_response(struct q921_link *link)
{
	struct pri *ctrl;

	if (link->own_rx_busy) {
		/* XXX : TODO later sometime */
		ctrl = link->ctrl;
		pri_error(ctrl, "Implement me %s: own_rx_busy\n", __FUNCTION__);
		//q921_rnr(link);
	} else {
		q921_rr(link, 1, 0);
	}

	link->acknowledge_pending = 0;
}

static void n_r_error_recovery(struct q921_link *link)
{
	q921_mdl_error(link, 'J');

	q921_establish_data_link(link);

	link->l3_initiated = 0;
}

static void update_v_a(struct q921_link *link, int n_r)
{
	int idealcnt = 0, realcnt = 0;
	int x;
	struct pri *ctrl;

	ctrl = link->ctrl;

	/* Cancel each packet as necessary */
	if (ctrl->debug & PRI_DEBUG_Q921_DUMP)
		pri_message(ctrl, "-- Got ACK for N(S)=%d to (but not including) N(S)=%d\n", link->v_a, n_r);
	for (x = link->v_a; x != n_r; Q921_INC(x)) {
		idealcnt++;
		realcnt += q921_ack_packet(link, x);	
	}
	if (idealcnt != realcnt) {
		pri_error(ctrl, "Ideally should have ack'd %d frames, but actually ack'd %d.  This is not good.\n", idealcnt, realcnt);
		q921_dump_iqueue_info(link);
	}

	link->v_a = n_r;
}

/*! \brief Is V(A) <= N(R) <= V(S) ? */
static int n_r_is_valid(struct q921_link *link, int n_r)
{
	int x;

	for (x = link->v_a; x != n_r && x != link->v_s; Q921_INC(x)) {
	}
	if (x != n_r) {
		return 0;
	} else {
		return 1;
	}
}

static int q921_invoke_retransmission(struct q921_link *link, int n_r);

static pri_event *timer_recovery_rr_rej_rx(struct q921_link *link, q921_h *h)
{
	struct pri *ctrl;

	ctrl = link->ctrl;

	/* Figure B.7/Q.921 Page 74 */
	link->peer_rx_busy = 0;

	if (is_command(ctrl, h)) {
		if (h->s.p_f) {
			/* Enquiry response */
			q921_enquiry_response(link);
		}
		if (n_r_is_valid(link, h->s.n_r)) {
			update_v_a(link, h->s.n_r);
		} else {
			goto n_r_error_out;
		}
	} else {
		if (!h->s.p_f) {
			if (n_r_is_valid(link, h->s.n_r)) {
				update_v_a(link, h->s.n_r);
			} else {
				goto n_r_error_out;
			}
		} else {
			if (n_r_is_valid(link, h->s.n_r)) {
				update_v_a(link, h->s.n_r);
				stop_t200(link);
				start_t203(link);
				q921_invoke_retransmission(link, h->s.n_r);
				q921_setstate(link, Q921_MULTI_FRAME_ESTABLISHED);
			} else {
				goto n_r_error_out;
			}
		}
	}
	return NULL;
n_r_error_out:
	n_r_error_recovery(link);
	q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
	return NULL;
}

static pri_event *q921_rr_rx(struct q921_link *link, q921_h *h)
{
	pri_event *res = NULL;
	struct pri *ctrl;

	ctrl = link->ctrl;

#if 0	/* Don't flood debug trace with RR if not really looking at Q.921 layer. */
	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Got RR N(R)=%d\n", link->tei, h->s.n_r);
	}
#endif

	switch (link->state) {
	case Q921_TIMER_RECOVERY:
		res = timer_recovery_rr_rej_rx(link, h);
		break;
	case Q921_MULTI_FRAME_ESTABLISHED:
		/* Figure B.7/Q.921 Page 74 */
		link->peer_rx_busy = 0;

		if (is_command(ctrl, h)) {
			if (h->s.p_f) {
				/* Enquiry response */
				q921_enquiry_response(link);
			}
		} else {
			if (h->s.p_f) {
				q921_mdl_error(link, 'A');
			}
		}

		if (!n_r_is_valid(link, h->s.n_r)) {
			n_r_error_recovery(link);
			q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
		} else {
			if (h->s.n_r == link->v_s) {
				update_v_a(link, h->s.n_r);
				stop_t200(link);
				start_t203(link);
			} else {
				if (h->s.n_r != link->v_a) {
					/* Need to check the validity of n_r as well.. */
					update_v_a(link, h->s.n_r);
					restart_t200(link);
				}
			}
		}
		break;
	case Q921_TEI_ASSIGNED:
	case Q921_AWAITING_ESTABLISHMENT:
	case Q921_AWAITING_RELEASE:
		/*
		 * Ignore this frame.
		 * We likely got reset and the other end has not realized it yet.
		 */
		break;
	default:
		pri_error(ctrl, "Don't know what to do with RR in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		break;
	}

	return res;
}

static int q921_invoke_retransmission(struct q921_link *link, int n_r)
{
	struct q921_frame *f;
	struct pri *ctrl;

	ctrl = link->ctrl;

	/*
	 * All acked frames should already have been removed from the queue.
	 * Push back all sent frames.
	 */
	for (f = link->tx_queue; f && f->status == Q921_TX_FRAME_SENT; f = f->next) {
		f->status = Q921_TX_FRAME_PUSHED_BACK;

		/* Sanity check: Is V(A) <= N(S) <= V(S)? */
		if (!n_r_is_valid(link, f->h.n_s)) {
			pri_error(ctrl,
				"Tx Q frame with invalid N(S)=%d.  Must be (V(A)=%d) <= N(S) <= (V(S)=%d)\n",
				f->h.n_s, link->v_a, link->v_s);
		}
	}
	link->v_s = n_r;
	return q921_send_queued_iframes(link);
}

static pri_event *q921_rej_rx(struct q921_link *link, q921_h *h)
{
	pri_event *res = NULL;
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Got REJ N(R)=%d\n", link->tei, h->s.n_r);
	}

	switch (link->state) {
	case Q921_TIMER_RECOVERY:
		res = timer_recovery_rr_rej_rx(link, h);
		break;
	case Q921_MULTI_FRAME_ESTABLISHED:
		/* Figure B.7/Q.921 Page 74 */
		link->peer_rx_busy = 0;

		if (is_command(ctrl, h)) {
			if (h->s.p_f) {
				/* Enquiry response */
				q921_enquiry_response(link);
			}
		} else {
			if (h->s.p_f) {
				q921_mdl_error(link, 'A');
			}
		}

		if (!n_r_is_valid(link, h->s.n_r)) {
			n_r_error_recovery(link);
			q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
		} else {
			update_v_a(link, h->s.n_r);
			stop_t200(link);
			start_t203(link);
			q921_invoke_retransmission(link, h->s.n_r);
		}
		break;
	case Q921_TEI_ASSIGNED:
	case Q921_AWAITING_ESTABLISHMENT:
	case Q921_AWAITING_RELEASE:
		/*
		 * Ignore this frame.
		 * We likely got reset and the other end has not realized it yet.
		 */
		break;
	default:
		pri_error(ctrl, "Don't know what to do with REJ in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		break;
	}

	return res;
}

static pri_event *q921_frmr_rx(struct q921_link *link, q921_h *h)
{
	pri_event *res = NULL;
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Got FRMR\n", link->tei);
	}

	switch (link->state) {
	case Q921_TIMER_RECOVERY:
	case Q921_MULTI_FRAME_ESTABLISHED:
		q921_mdl_error(link, 'K');
		q921_establish_data_link(link);
		link->l3_initiated = 0;
		q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
		if (PTP_MODE(ctrl)) {
			ctrl->ev.gen.e = PRI_EVENT_DCHAN_DOWN;
			res = &ctrl->ev;
		}
		break;
	case Q921_TEI_ASSIGNED:
	case Q921_AWAITING_ESTABLISHMENT:
	case Q921_AWAITING_RELEASE:
		/*
		 * Ignore this frame.
		 * We likely got reset and the other end has not realized it yet.
		 */
		if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
			pri_message(ctrl, "TEI=%d Ignoring FRMR.\n", link->tei);
		}
		break;
	default:
		pri_error(ctrl, "Don't know what to do with FRMR in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		break;
	}

	return res;
}

static pri_event *q921_iframe_rx(struct q921_link *link, q921_h *h, int len)
{
	struct pri *ctrl;
	pri_event *eres = NULL;
	int res = 0;
	int delay_q931_receive;

	ctrl = link->ctrl;

	switch (link->state) {
	case Q921_TIMER_RECOVERY:
	case Q921_MULTI_FRAME_ESTABLISHED:
		delay_q931_receive = 0;
		/* FIXME: Verify that it's a command ... */
		if (link->own_rx_busy) {
			/* DEVIATION: Handle own rx busy */
		} else if (h->i.n_s == link->v_r) {
			Q921_INC(link->v_r);

			link->reject_exception = 0;

			/*
			 * Dump Q.931 message where Q.921 says to queue it to Q.931 so if
			 * Q.921 is dumping its frames they will be in the correct order.
			 */
			if (ctrl->debug & PRI_DEBUG_Q931_DUMP) {
				q931_dump(ctrl, h->h.tei, (q931_h *) h->i.data, len - 4, 0);
			}
			delay_q931_receive = 1;

			if (h->i.p_f) {
				q921_rr(link, 1, 0);
				link->acknowledge_pending = 0;
			} else {
				link->acknowledge_pending = 1;
			}
		} else {
			if (link->reject_exception) {
				if (h->i.p_f) {
					q921_rr(link, 1, 0);
					link->acknowledge_pending = 0;
				}
			} else {
				link->reject_exception = 1;
				q921_reject(link, h->i.p_f);
				link->acknowledge_pending = 0;
			}
		}

		if (!n_r_is_valid(link, h->i.n_r)) {
			n_r_error_recovery(link);
			q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
		} else {
			if (link->state == Q921_TIMER_RECOVERY) {
				update_v_a(link, h->i.n_r);
			} else {
				if (link->peer_rx_busy) {
					update_v_a(link, h->i.n_r);
				} else {
					if (h->i.n_r == link->v_s) {
						update_v_a(link, h->i.n_r);
						stop_t200(link);
						start_t203(link);
					} else {
						if (h->i.n_r != link->v_a) {
							update_v_a(link, h->i.n_r);
							reschedule_t200(link);
						}
					}
				}
			}
		}
		if (delay_q931_receive) {
			/* Q.921 has finished processing the frame so we can give it to Q.931 now. */
			res = q931_receive(link, (q931_h *) h->i.data, len - 4);
			if (res != -1 && (res & Q931_RES_HAVEEVENT)) {
				eres = &ctrl->ev;
			}
		}
		break;
	case Q921_TEI_ASSIGNED:
	case Q921_AWAITING_ESTABLISHMENT:
	case Q921_AWAITING_RELEASE:
		/*
		 * Ignore this frame.
		 * We likely got reset and the other end has not realized it yet.
		 */
		break;
	default:
		pri_error(ctrl, "Don't know what to do with an I-frame in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		break;
	}

	return eres;
}

static pri_event *q921_dm_rx(struct q921_link *link, q921_h *h)
{
	pri_event *res = NULL;
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Got DM\n", link->tei);
	}

	switch (link->state) {
	case Q921_TEI_ASSIGNED:
		if (h->u.p_f)
			break;
		/* else */
		restart_timer_stop(link);
		q921_establish_data_link(link);
		link->l3_initiated = 1;
		q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
		break;
	case Q921_AWAITING_ESTABLISHMENT:
		if (!h->u.p_f)
			break;

		res = q921_check_delay_restart(link);
		q921_discard_iqueue(link);
		/* DL-RELEASE indication */
		q931_dl_event(link, Q931_DL_EVENT_DL_RELEASE_IND);
		stop_t200(link);
		q921_setstate(link, Q921_TEI_ASSIGNED);
		break;
	case Q921_AWAITING_RELEASE:
		if (!h->u.p_f)
			break;
		res = q921_check_delay_restart(link);
		/* DL-RELEASE confirm */
		q931_dl_event(link, Q931_DL_EVENT_DL_RELEASE_CONFIRM);
		stop_t200(link);
		q921_setstate(link, Q921_TEI_ASSIGNED);
		break;
	case Q921_MULTI_FRAME_ESTABLISHED:
		if (h->u.p_f) {
			q921_mdl_error(link, 'B');
			break;
		}

		q921_mdl_error(link, 'E');
		q921_establish_data_link(link);
		link->l3_initiated = 0;
		q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
		if (PTP_MODE(ctrl)) {
			ctrl->ev.gen.e = PRI_EVENT_DCHAN_DOWN;
			res = &ctrl->ev;
		}
		break;
	case Q921_TIMER_RECOVERY:
		if (h->u.p_f) {
			q921_mdl_error(link, 'B');
		} else {
			q921_mdl_error(link, 'E');
		}
		q921_establish_data_link(link);
		link->l3_initiated = 0;
		q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
		if (PTP_MODE(ctrl)) {
			ctrl->ev.gen.e = PRI_EVENT_DCHAN_DOWN;
			res = &ctrl->ev;
		}
		break;
	default:
		pri_error(ctrl, "Don't know what to do with DM frame in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		break;
	}

	return res;
}

static pri_event *q921_rnr_rx(struct q921_link *link, q921_h *h)
{
	pri_event *res = NULL;
	struct pri *ctrl;

	ctrl = link->ctrl;

	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl, "TEI=%d Got RNR N(R)=%d\n", link->tei, h->s.n_r);
	}

	switch (link->state) {
	case Q921_MULTI_FRAME_ESTABLISHED:
		link->peer_rx_busy = 1;
		if (!is_command(ctrl, h)) {
			if (h->s.p_f) {
				q921_mdl_error(link, 'A');
			}
		} else {
			if (h->s.p_f) {
				q921_enquiry_response(link);
			}
		}

		if (!n_r_is_valid(link, h->s.n_r)) {
			n_r_error_recovery(link);
			q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
		} else {
			update_v_a(link, h->s.n_r);
			stop_t203(link);
			restart_t200(link);
		}
		break;
	case Q921_TIMER_RECOVERY:
		/* Q.921 Figure B.8 Q921 (Sheet 6 of 9) Page 85 */
		link->peer_rx_busy = 1;
		if (is_command(ctrl, h)) {
			if (h->s.p_f) {
				q921_enquiry_response(link);
			}
			if (n_r_is_valid(link, h->s.n_r)) {
				update_v_a(link, h->s.n_r);
				break;
			} else {
				n_r_error_recovery(link);
				q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
				break;
			}
		} else {
			if (h->s.p_f) {
				if (n_r_is_valid(link, h->s.n_r)) {
					update_v_a(link, h->s.n_r);
					restart_t200(link);
					q921_invoke_retransmission(link, h->s.n_r);
					q921_setstate(link, Q921_MULTI_FRAME_ESTABLISHED);
					break;
				} else {
					n_r_error_recovery(link);
					q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
					break;
				}
			} else {
				if (n_r_is_valid(link, h->s.n_r)) {
					update_v_a(link, h->s.n_r);
					break;
				} else {
					n_r_error_recovery(link);
					q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
					break;
				}
			}
		}
		break;
	case Q921_TEI_ASSIGNED:
	case Q921_AWAITING_ESTABLISHMENT:
	case Q921_AWAITING_RELEASE:
		/*
		 * Ignore this frame.
		 * We likely got reset and the other end has not realized it yet.
		 */
		break;
	default:
		pri_error(ctrl, "Don't know what to do with RNR in state %d(%s)\n",
			link->state, q921_state2str(link->state));
		break;
	}

	return res;
}

static void q921_acknowledge_pending_check(struct q921_link *link)
{
	if (link->acknowledge_pending) {
		link->acknowledge_pending = 0;
		q921_rr(link, 0, 0);
	}
}

static void q921_statemachine_check(struct q921_link *link)
{
	switch (link->state) {
	case Q921_MULTI_FRAME_ESTABLISHED:
		q921_send_queued_iframes(link);
		q921_acknowledge_pending_check(link);
		break;
	case Q921_TIMER_RECOVERY:
		q921_acknowledge_pending_check(link);
		break;
	default:
		break;
	}
}

static pri_event *__q921_receive_qualified(struct q921_link *link, q921_h *h, int len)
{
	int res;
	pri_event *ev = NULL;
	struct pri *ctrl;

	ctrl = link->ctrl;

	switch (h->h.data[0] & Q921_FRAMETYPE_MASK) {
	case 0:
	case 2:
		ev = q921_iframe_rx(link, h, len);
		break;
	case 1:
		switch ((h->s.x0 << 2) | h->s.ss) {
		case 0x00:
			ev = q921_rr_rx(link, h);
			break;
 		case 0x01:
			ev = q921_rnr_rx(link, h);
			break;
 		case 0x02:
			ev = q921_rej_rx(link, h);
			break;
		default:
			pri_error(ctrl,
				"!! XXX Unknown Supervisory frame x0=%d ss=%d, pf=%d, N(R)=%d, V(A)=%d, V(S)=%d XXX\n",
				h->s.x0, h->s.ss, h->s.p_f, h->s.n_r, link->v_a, link->v_s);
			break;
		}
		break;
	case 3:
		if (len < 3) {
			pri_error(ctrl, "!! Received short unnumbered frame\n");
			break;
		}
		switch ((h->u.m3 << 2) | h->u.m2) {
		case 0x03:
			ev = q921_dm_rx(link, h);
			break;
		case 0x00:
			/* UI-frame */
			if (ctrl->debug & PRI_DEBUG_Q931_DUMP) {
				q931_dump(ctrl, h->h.tei, (q931_h *) h->u.data, len - 3, 0);
			}
			res = q931_receive(link, (q931_h *) h->u.data, len - 3);
			if (res != -1 && (res & Q931_RES_HAVEEVENT)) {
				ev = &ctrl->ev;
			}
			break;
		case 0x08:
			ev = q921_disc_rx(link, h);
			break;
		case 0x0F:
			/* SABME */
			if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
				pri_message(ctrl, "TEI=%d Got SABME from %s peer.\n",
					link->tei, h->h.c_r ? "network" : "cpe");
			}
			if (h->h.c_r) {
				ctrl->remotetype = PRI_NETWORK;
				if (ctrl->localtype == PRI_NETWORK) {
					/* We can't both be networks */
					ev = pri_mkerror(ctrl, "We think we're the network, but they think they're the network, too.");
					break;
				}
			} else {
				ctrl->remotetype = PRI_CPE;
				if (ctrl->localtype == PRI_CPE) {
					/* We can't both be CPE */
					ev = pri_mkerror(ctrl, "We think we're the CPE, but they think they're the CPE too.\n");
					break;
				}
			}
			ev = q921_sabme_rx(link, h);
			break;
		case 0x0C:
			ev = q921_ua_rx(link, h);
			break;
		case 0x11:
			ev = q921_frmr_rx(link, h);
			break;
		case 0x17:
			pri_error(ctrl, "!! XID frames not supported\n");
			break;
		default:
			pri_error(ctrl, "!! Don't know what to do with u-frame (m3=%d, m2=%d)\n",
				h->u.m3, h->u.m2);
			break;
		}
		break;
	}

	q921_statemachine_check(link);

	return ev;
}

static pri_event *q921_handle_unmatched_frame(struct pri *ctrl, q921_h *h, int len)
{
	if (!BRI_NT_PTMP(ctrl)) {
		return NULL;
	}

	if (h->h.tei < Q921_TEI_AUTO_FIRST) {
		if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
			pri_message(ctrl, "Manual TEI range is not supported in NT-PTMP mode. Discarding\n");
		}
		return NULL;
	}

	if (h->h.sapi != Q921_SAPI_CALL_CTRL) {
		if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
			pri_message(ctrl, "Message with SAPI other than CALL CTRL is discarded\n");
		}
		return NULL;
	}

	/* This means an unrecognized TEI that we'll kill */
	if (ctrl->debug & PRI_DEBUG_Q921_STATE) {
		pri_message(ctrl,
			"Could not find a layer 2 link for received frame with SAPI/TEI of %d/%d.\n",
			h->h.sapi, h->h.tei);
		pri_message(ctrl, "Sending TEI release, in order to re-establish TEI state\n");
	}
	q921_tei_remove(ctrl, h->h.tei);

	return NULL;
}

/* This code assumes that the pri structure is the master pri */
static pri_event *__q921_receive(struct pri *ctrl, q921_h *h, int len)
{
	pri_event *ev = NULL;
	struct q921_link *link;

	/* Discard FCS */
	len -= 2;
	
	if (ctrl->debug & (PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW)) {
		q921_dump(ctrl, h, len, ctrl->debug, 0);
	}

	/* Check some reject conditions -- Start by rejecting improper ea's */
	if (h->h.ea1 || !h->h.ea2) {
		return NULL;
	}

	if (h->h.sapi == Q921_SAPI_LAYER2_MANAGEMENT) {
		return q921_mdl_receive(ctrl, &h->u, len);
	}

	if (h->h.tei == Q921_TEI_GROUP && h->h.sapi != Q921_SAPI_CALL_CTRL) {
		pri_error(ctrl, "Do not handle group messages to services other than MDL or CALL CTRL\n");
		return NULL;
	}

	if (BRI_TE_PTMP(ctrl)) {
		/* We're operating on the specific TEI link */
		link = ctrl->link.next;
		if (h->h.sapi == link->sapi
			&& ((link->state >= Q921_TEI_ASSIGNED
				&& h->h.tei == link->tei)
				|| h->h.tei == Q921_TEI_GROUP)) {
			ev = __q921_receive_qualified(link, h, len);
		}
		/* Only support reception on our specific TEI link */
	} else if (BRI_NT_PTMP(ctrl)) {
		link = pri_find_tei(ctrl, h->h.sapi, h->h.tei);
		if (link) {
			ev = __q921_receive_qualified(link, h, len);
		} else {
			ev = q921_handle_unmatched_frame(ctrl, h, len);
		}
	} else if (PTP_MODE(ctrl)
		&& h->h.sapi == ctrl->link.sapi
		&& (h->h.tei == ctrl->link.tei || h->h.tei == Q921_TEI_GROUP)) {
		ev = __q921_receive_qualified(&ctrl->link, h, len);
	} else {
		ev = NULL;
	}

	if (ctrl->debug & PRI_DEBUG_Q921_DUMP) {
		pri_message(ctrl, "Done handling message for SAPI/TEI=%d/%d\n", h->h.sapi, h->h.tei);
	}

	return ev;
}

pri_event *q921_receive(struct pri *ctrl, q921_h *h, int len)
{
	pri_event *e;
	e = __q921_receive(ctrl, h, len);
	ctrl->q921_rxcount++;
	return e;
}

static void q921_establish_data_link(struct q921_link *link)
{
	q921_clear_exception_conditions(link);
	link->RC = 0;
	stop_t203(link);
	reschedule_t200(link);
	q921_send_sabme(link);
}

static void nt_ptmp_dchannel_up(void *vpri)
{
	struct pri *ctrl = vpri;

	ctrl->schedev = 1;
	ctrl->ev.gen.e = PRI_EVENT_DCHAN_UP;
}

void q921_start(struct q921_link *link)
{
	struct pri *ctrl;

	ctrl = link->ctrl;
	if (PTMP_MODE(ctrl)) {
		if (TE_MODE(ctrl)) {
			q921_setstate(link, Q921_ASSIGN_AWAITING_TEI);
			q921_tei_request(link);
		} else {
			q921_setstate(link, Q921_TEI_UNASSIGNED);
			pri_schedule_event(ctrl, 0, nt_ptmp_dchannel_up, ctrl);
			if (!ctrl->link.next) {
				/*
				 * We do not have any TEI's so make sure there are no devices
				 * that think they have a TEI.  A device may think it has a TEI
				 * if the upper layer program is restarted or the system
				 * reboots.
				 */
				q921_tei_remove(ctrl, Q921_TEI_GROUP);
			}
		}
	} else {
		/* PTP mode, no need for TEI management junk */
		q921_establish_data_link(link);
		link->l3_initiated = 1;
		q921_setstate(link, Q921_AWAITING_ESTABLISHMENT);
	}
}