aboutsummaryrefslogtreecommitdiffstats
path: root/src/common/rsl.c
blob: 18c0349120ad4520fb3119d645f366f1fe5c5c02 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
/* GSM TS 08.58 RSL, BTS Side */

/* (C) 2011 by Andreas Eversberg <jolly@eversberg.eu>
 * (C) 2011-2019 by Harald Welte <laforge@gnumonks.org>
 * (C) 2020 by sysmocom - s.m.f.c. GmbH <info@sysmocom.de>
 *
 * All Rights Reserved
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "btsconfig.h"	/* for PACKAGE_VERSION */

#include <stdio.h>
#include <errno.h>
#include <netdb.h>
#include <stdbool.h>
#include <inttypes.h>
#include <sys/types.h>
#include <arpa/inet.h>

#include <osmocom/core/byteswap.h>
#include <osmocom/core/msgb.h>
#include <osmocom/core/talloc.h>
#include <osmocom/gsm/rsl.h>
#include <osmocom/gsm/lapdm.h>
#include <osmocom/gsm/gsm0808.h>
#include <osmocom/gsm/protocol/gsm_12_21.h>
#include <osmocom/gsm/protocol/gsm_08_58.h>
#include <osmocom/gsm/protocol/gsm_04_08.h>
#include <osmocom/gsm/protocol/ipaccess.h>
#include <osmocom/trau/osmo_ortp.h>

#include <osmo-bts/logging.h>
#include <osmo-bts/gsm_data.h>
#include <osmo-bts/abis.h>
#include <osmo-bts/bts.h>
#include <osmo-bts/rsl.h>
#include <osmo-bts/oml.h>
#include <osmo-bts/amr.h>
#include <osmo-bts/signal.h>
#include <osmo-bts/measurement.h>
#include <osmo-bts/pcu_if.h>
#include <osmo-bts/handover.h>
#include <osmo-bts/cbch.h>
#include <osmo-bts/l1sap.h>
#include <osmo-bts/bts_model.h>
#include <osmo-bts/pcuif_proto.h>

//#define FAKE_CIPH_MODE_COMPL

/* Parse power attenuation (in dB) from BS Power IE (see 9.3.4) */
#define BS_POWER2DB(bs_power) \
	((bs_power & 0x0f) * 2)

static int rsl_tx_error_report(struct gsm_bts_trx *trx, uint8_t cause, const uint8_t *chan_nr,
				const uint8_t *link_id, const struct msgb *orig_msg);

/* list of RSL SI types that can occur on the SACCH */
static const unsigned int rsl_sacch_sitypes[] = {
	RSL_SYSTEM_INFO_5,
	RSL_SYSTEM_INFO_6,
	RSL_SYSTEM_INFO_5bis,
	RSL_SYSTEM_INFO_5ter,
	RSL_EXT_MEAS_ORDER,
	RSL_MEAS_INFO,
};

/* FIXME: move this to libosmocore */
int osmo_in_array(unsigned int search, const unsigned int *arr, unsigned int size)
{
	unsigned int i;
	for (i = 0; i < size; i++) {
		if (arr[i] == search)
			return 1;
	}
	return 0;
}
#define OSMO_IN_ARRAY(search, arr) osmo_in_array(search, arr, ARRAY_SIZE(arr))

int msgb_queue_flush(struct llist_head *list)
{
	struct msgb *msg, *msg2;
	int count = 0;

	llist_for_each_entry_safe(msg, msg2, list, list) {
		msgb_free(msg);
		count++;
	}

	return count;
}

/* FIXME: move this to libosmocore */
void gsm48_gen_starting_time(uint8_t *out, struct gsm_time *gtime)
{
	uint8_t t1p = gtime->t1 % 32;
	out[0] = (t1p << 3) | (gtime->t3 >> 3);
	out[1] = (gtime->t3 << 5) | gtime->t2;
}

/* Handle RSL Channel Mode IE (see section 9.3.6) */
static int rsl_handle_chan_mod_ie(struct gsm_lchan *lchan,
				  const struct tlv_parsed *tp,
				  uint8_t *cause)
{
	const struct rsl_ie_chan_mode *cm;

	if (!TLVP_PRES_LEN(tp, RSL_IE_CHAN_MODE, sizeof(*cm))) {
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Channel Mode IE is not present\n");
		*cause = RSL_ERR_MAND_IE_ERROR;
		return -ENODEV;
	}

	cm = (const struct rsl_ie_chan_mode *) TLVP_VAL(tp, RSL_IE_CHAN_MODE);
	lchan->rsl_cmode = cm->spd_ind;
	lchan->ts->trx->bts->dtxd = (cm->dtx_dtu & RSL_CMOD_DTXd) ? true : false;

	/* Octet 5: Channel rate and type */
	switch (cm->chan_rt) {
	case RSL_CMOD_CRT_SDCCH:
	case RSL_CMOD_CRT_TCH_Bm:
	case RSL_CMOD_CRT_TCH_Lm:
		break;
	case RSL_CMOD_CRT_OSMO_TCH_VAMOS_Bm:
	case RSL_CMOD_CRT_OSMO_TCH_VAMOS_Lm:
		/* Make sure that Osmocom specific TSC IE is present */
		if (!TLVP_PRES_LEN(tp, RSL_IE_OSMO_TRAINING_SEQUENCE, 2)) {
			LOGPLCHAN(lchan, DRSL, LOGL_ERROR,
				  "Training Sequence IE is not present\n");
			*cause = RSL_ERR_MAND_IE_ERROR;
			return -ENODEV;
		}
		break;
	default:
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Channel Mode IE contains "
			  "unknown 'Channel rate and type' value 0x%02x\n",
			  cm->chan_rt);
		*cause = RSL_ERR_IE_CONTENT;
		return -ENOTSUP;
	}

#define RSL_CMODE(spd_ind, chan_rate) \
	((spd_ind << 8) | chan_rate)

	/* Octet 6: Speech coding algorithm/data rate + transparency indicator.
	 * NOTE: coding of this octet depends on 'Speech or data indicator' */
	switch (RSL_CMODE(cm->spd_ind, cm->chan_rate)) {
	/* If octet 4 indicates signalling */
	case RSL_CMODE(RSL_CMOD_SPD_SIGN, 0x00):
		/* No resources required, all other values are reserved */
		lchan->tch_mode = GSM48_CMODE_SIGN;
		break;

	/* If octet 4 indicates speech */
	case RSL_CMODE(RSL_CMOD_SPD_SPEECH, RSL_CMOD_SP_GSM1):
		lchan->tch_mode = GSM48_CMODE_SPEECH_V1;
		break;
	case RSL_CMODE(RSL_CMOD_SPD_SPEECH, RSL_CMOD_SP_GSM2):
		lchan->tch_mode = GSM48_CMODE_SPEECH_EFR;
		break;
	case RSL_CMODE(RSL_CMOD_SPD_SPEECH, RSL_CMOD_SP_GSM3):
		lchan->tch_mode = GSM48_CMODE_SPEECH_AMR;
		break;
	case RSL_CMODE(RSL_CMOD_SPD_SPEECH, RSL_CMOD_SP_GSM4):
	case RSL_CMODE(RSL_CMOD_SPD_SPEECH, RSL_CMOD_SP_GSM5):
	case RSL_CMODE(RSL_CMOD_SPD_SPEECH, RSL_CMOD_SP_GSM6):
		/* TODO: also handle RSL_CMOD_SP_{GSM4,GSM5,GSM6} */
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Channel Mode IE contains "
			  "unhandled speech coding algorithm 0x%02x\n",
			  cm->chan_rate);
		*cause = RSL_ERR_IE_CONTENT;
		return -ENOTSUP;

	/* If octet 4 indicates non-transparent data */
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_NT_14k5):
		lchan->tch_mode = GSM48_CMODE_DATA_14k5;
		break;
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_NT_12k0):
		lchan->tch_mode = GSM48_CMODE_DATA_12k0;
		break;
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_NT_6k0):
		lchan->tch_mode = GSM48_CMODE_DATA_6k0;
		break;
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_NT_43k5):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_NT_28k8):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_NTA_43k5_14k5):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_NTA_29k0_14k5):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_NTA_43k5_29k0):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_NTA_14k5_43k5):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_NTA_14k5_29k0):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_NTA_29k0_43k5):
		/* TODO: also handle other non-transparent data rates */
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Channel Mode IE contains "
			  "unhandled non-transparent CSD data rate 0x%02x\n",
			  cm->chan_rate & 0x3f);
		*cause = RSL_ERR_IE_CONTENT;
		return -ENOTSUP;

	/* If octet 4 indicates transparent data */
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_T_32000):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_T_29000):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_T_14400):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_T_9600):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_T_4800):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_T_2400):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_T_1200):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_T_600):
	case RSL_CMODE(RSL_CMOD_SPD_DATA, RSL_CMOD_CSD_T_1200_75):
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Channel Mode IE contains "
			  "unhandled transparent CSD data rate 0x%02x\n",
			  cm->chan_rate & 0x3f);
		*cause = RSL_ERR_IE_CONTENT;
		return -ENOTSUP;

	default:
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Channel Mode IE contains "
			  "an unknown/unhandled combination of "
			  "'Speech or data indicator' 0x%02x and "
			  "'Speech coding algorithm/data rate' 0x%02x\n",
			  cm->spd_ind, cm->chan_rate);
		*cause = RSL_ERR_IE_CONTENT;
		return -ENOPROTOOPT;
	}

#undef RSL_CMODE

	if (bts_supports_cm(lchan->ts->trx->bts, cm) != 1) {
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Channel type=0x%02x/mode=%s "
			  "is not supported by the PHY\n", cm->chan_rt,
			  gsm48_chan_mode_name(lchan->tch_mode));
		*cause = RSL_ERR_SERV_OPT_UNAVAIL;
		return -ENOTSUP;
	}

	return 0;
}

/* Handle RSL Channel Identification IE (see section 9.3.5) */
static int rsl_handle_chan_ident_ie(struct gsm_lchan *lchan,
				    const struct tlv_parsed *tp,
				    uint8_t *cause)
{
	const struct gsm_bts_trx_ts *ts = lchan->ts;
	const struct gsm_bts *bts = ts->trx->bts;
	const struct gsm48_chan_desc *cd;

	if (TLVP_PRES_LEN(tp, RSL_IE_CHAN_IDENT, sizeof(*cd) + 1)) {
		/* Channel Description IE comes together with its IEI (see 9.3.5) */
		cd = (const struct gsm48_chan_desc *) (TLVP_VAL(tp, RSL_IE_CHAN_IDENT) + 1);

		/* The PHY may not support using different TSCs */
		if (!osmo_bts_has_feature(bts->features, BTS_FEAT_MULTI_TSC)
		    && cd->h0.tsc != BTS_TSC(bts)) {
			LOGPLCHAN(lchan, DL1C, LOGL_ERROR, "This PHY does not support "
				  "lchan TSC %u != BSIC-TSC %u, sending NACK\n",
				  cd->h0.tsc, BTS_TSC(bts));
			*cause = RSL_ERR_SERV_OPT_UNIMPL;
			return -ENOTSUP;
		}
	}

	return 0;
}

/* Handle Osmocom specific TSC IE */
static int rsl_handle_osmo_tsc_ie(struct gsm_lchan *lchan,
				  const struct tlv_parsed *tp,
				  uint8_t *cause)
{
	/* Osmocom specific IE indicating Training Sequence Code and Set */
	if (TLVP_PRES_LEN(tp, RSL_IE_OSMO_TRAINING_SEQUENCE, 2)) {
		const uint8_t *ie = TLVP_VAL(tp, RSL_IE_OSMO_TRAINING_SEQUENCE);
		lchan->ts->tsc_set = ie[0] & 0x03; /* Range: 0..3 */
		lchan->ts->tsc     = ie[1] & 0x07; /* Range: 0..7 */
	} else {
		lchan->ts->tsc = lchan->ts->tsc_oml;
		lchan->ts->tsc_set = 0;
	}

	return 0;
}


/*
 * support
 */

/* Is this channel number for a dedicated channel (true) or not (false) */
static bool chan_nr_is_dchan(uint8_t chan_nr)
{
	/* See TS 48.058 9.3.1 + Osmocom extension for RSL_CHAN_OSMO_PDCH */
	if ((chan_nr & 0xc0) == 0x80)
		return false;
	else
		return true;
}

static struct gsm_lchan *lchan_lookup(struct gsm_bts_trx *trx, uint8_t chan_nr,
				      const char *log_name)
{
	int rc;
	struct gsm_lchan *lchan = rsl_lchan_lookup(trx, chan_nr, &rc);

	if (!lchan) {
		LOGP(DRSL, LOGL_ERROR, "%sunknown chan_nr=0x%02x\n", log_name,
		     chan_nr);
		return NULL;
	}

	if (rc < 0) {
		LOGP(DRSL, LOGL_ERROR, "%s %smismatching chan_nr=0x%02x\n",
		     gsm_ts_and_pchan_name(lchan->ts), log_name, chan_nr);
		return NULL;
	}
	return lchan;
}

static struct msgb *rsl_msgb_alloc(int hdr_size)
{
	struct msgb *nmsg;

	hdr_size += sizeof(struct ipaccess_head);

	nmsg = msgb_alloc_headroom(600+hdr_size, hdr_size, "RSL");
	if (!nmsg)
		return NULL;
	nmsg->l3h = nmsg->data;
	return nmsg;
}

static void rsl_trx_push_hdr(struct msgb *msg, uint8_t msg_type)
{
	struct abis_rsl_common_hdr *th;

	th = (struct abis_rsl_common_hdr *) msgb_push(msg, sizeof(*th));
	th->msg_discr = ABIS_RSL_MDISC_TRX;
	th->msg_type = msg_type;
}

static void rsl_cch_push_hdr(struct msgb *msg, uint8_t msg_type, uint8_t chan_nr)
{
	struct abis_rsl_cchan_hdr *cch;

	cch = (struct abis_rsl_cchan_hdr *) msgb_push(msg, sizeof(*cch));
	cch->c.msg_discr = ABIS_RSL_MDISC_COM_CHAN;
	cch->c.msg_type = msg_type;
	cch->ie_chan = RSL_IE_CHAN_NR;
	cch->chan_nr = chan_nr;
}

static void rsl_dch_push_hdr(struct msgb *msg, uint8_t msg_type, uint8_t chan_nr)
{
	struct abis_rsl_dchan_hdr *dch;

	dch = (struct abis_rsl_dchan_hdr *) msgb_push(msg, sizeof(*dch));
	dch->c.msg_discr = ABIS_RSL_MDISC_DED_CHAN;
	dch->c.msg_type = msg_type;
	dch->ie_chan = RSL_IE_CHAN_NR;
	dch->chan_nr = chan_nr;
}

static void rsl_ipa_push_hdr(struct msgb *msg, uint8_t msg_type, uint8_t chan_nr)
{
	struct abis_rsl_dchan_hdr *dch;

	dch = (struct abis_rsl_dchan_hdr *) msgb_push(msg, sizeof(*dch));
	dch->c.msg_discr = ABIS_RSL_MDISC_IPACCESS;
	dch->c.msg_type = msg_type;
	dch->ie_chan = RSL_IE_CHAN_NR;
	dch->chan_nr = chan_nr;
}

/*
 * TRX related messages
 */

/* 8.6.4 sending ERROR REPORT */
static int rsl_tx_error_report(struct gsm_bts_trx *trx, uint8_t cause, const uint8_t *chan_nr,
				const uint8_t *link_id, const struct msgb *orig_msg)
{
	unsigned int len = sizeof(struct abis_rsl_common_hdr);
	struct msgb *nmsg;

	LOGP(DRSL, LOGL_NOTICE, "Tx RSL Error Report: cause = 0x%02x\n", cause);

	if (orig_msg)
		len += 2 + 3+msgb_l2len(orig_msg); /* chan_nr + TLV(orig_msg) */
	if (chan_nr)
		len += 2;
	if (link_id)
		len += 2;

	nmsg = rsl_msgb_alloc(len);
	if (!nmsg)
		return -ENOMEM;
	msgb_tlv_put(nmsg, RSL_IE_CAUSE, 1, &cause);
	if (orig_msg && msgb_l2len(orig_msg) >= sizeof(struct abis_rsl_common_hdr)) {
		struct abis_rsl_common_hdr *ch = (struct abis_rsl_common_hdr *) msgb_l2(orig_msg);
		msgb_tv_put(nmsg, RSL_IE_MSG_ID, ch->msg_type);
	}
	if (chan_nr)
		msgb_tv_put(nmsg, RSL_IE_CHAN_NR, *chan_nr);
	if (link_id)
		msgb_tv_put(nmsg, RSL_IE_LINK_IDENT, *link_id);
	if (orig_msg)
		msgb_tlv_put(nmsg, RSL_IE_ERR_MSG, msgb_l2len(orig_msg), msgb_l2(orig_msg));

	rsl_trx_push_hdr(nmsg, RSL_MT_ERROR_REPORT);
	nmsg->trx = trx;

	return abis_bts_rsl_sendmsg(nmsg);
}

/* 8.6.1 sending RF RESOURCE INDICATION */
int rsl_tx_rf_res(struct gsm_bts_trx *trx)
{
	unsigned int tn, ln;
	struct msgb *nmsg;

	LOGP(DRSL, LOGL_INFO, "Tx RSL RF RESource INDication\n");

	nmsg = rsl_msgb_alloc(sizeof(struct abis_rsl_common_hdr));
	if (!nmsg)
		return -ENOMEM;

	/* Add interference levels for each logical channel */
	uint8_t *len = msgb_tl_put(nmsg, RSL_IE_RESOURCE_INFO);

	for (tn = 0; tn < ARRAY_SIZE(trx->ts); tn++) {
		struct gsm_bts_trx_ts *ts = &trx->ts[tn];

		for (ln = 0; ln < ARRAY_SIZE(ts->lchan); ln++) {
			struct gsm_lchan *lchan = &ts->lchan[ln];

			/* We're not interested in active lchans */
			if (lchan->state == LCHAN_S_ACTIVE) {
				/* Avoid potential buffer overflow */
				lchan->meas.interf_meas_num = 0;
				continue;
			}

			/* Only for GSM_LCHAN_{SDCCH,TCH_F,TCH_H} */
			if (!lchan_is_dcch(lchan))
				continue;

			/* Average all collected samples */
			int band = gsm_lchan_interf_meas_calc_band(lchan);
			if (band < 0)
				continue;

			msgb_v_put(nmsg, gsm_lchan2chan_nr(lchan));
			msgb_v_put(nmsg, (band & 0x07) << 5);
		}
	}

	/* Calculate length of the V part */
	*len = msgb_l3len(nmsg) - 2;

	rsl_trx_push_hdr(nmsg, RSL_MT_RF_RES_IND);
	nmsg->trx = trx;

	return abis_bts_rsl_sendmsg(nmsg);
}

/*
 * common channel related messages
 */

/* 8.5.1 BCCH INFOrmation is received */
static int rsl_rx_bcch_info(struct gsm_bts_trx *trx, struct msgb *msg)
{
	struct abis_rsl_cchan_hdr *cch = msgb_l2(msg);
	struct gsm_bts *bts = trx->bts;
	struct tlv_parsed tp;
	uint8_t rsl_si, count;
	enum osmo_sysinfo_type osmo_si;
	struct gsm48_system_information_type_2quater *si2q;
	struct bitvec bv;
	const uint8_t *si_buf;
	rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));

	/* 9.3.30 System Info Type */
	if (!TLVP_PRESENT(&tp, RSL_IE_SYSINFO_TYPE))
		return rsl_tx_error_report(trx, RSL_ERR_MAND_IE_ERROR, &cch->chan_nr, NULL, msg);

	rsl_si = *TLVP_VAL(&tp, RSL_IE_SYSINFO_TYPE);
	if (OSMO_IN_ARRAY(rsl_si, rsl_sacch_sitypes))
		return rsl_tx_error_report(trx, RSL_ERR_IE_CONTENT, &cch->chan_nr, NULL, msg);

	osmo_si = osmo_rsl2sitype(rsl_si);
	if (osmo_si == SYSINFO_TYPE_NONE) {
		LOGP(DRSL, LOGL_NOTICE, " Rx RSL SI 0x%02x not supported.\n", rsl_si);
		return rsl_tx_error_report(trx, RSL_ERR_IE_CONTENT, &cch->chan_nr, NULL, msg);
	}
	/* 9.3.39 Full BCCH Information */
	if (TLVP_PRESENT(&tp, RSL_IE_FULL_BCCH_INFO)) {
		uint8_t len = TLVP_LEN(&tp, RSL_IE_FULL_BCCH_INFO);
		if (len > sizeof(sysinfo_buf_t)) {
			LOGP(DRSL, LOGL_ERROR, "Truncating received Full BCCH Info (%u -> %zu) for SI%s\n",
			     len, sizeof(sysinfo_buf_t), get_value_string(osmo_sitype_strs, osmo_si));
			len = sizeof(sysinfo_buf_t);
		}

		LOGP(DRSL, LOGL_INFO, " Rx RSL BCCH INFO (SI%s, %u bytes)\n",
		     get_value_string(osmo_sitype_strs, osmo_si), len);

		if (SYSINFO_TYPE_2quater == osmo_si) {
			si2q = (struct gsm48_system_information_type_2quater *) TLVP_VAL(&tp, RSL_IE_FULL_BCCH_INFO);
			bv.data = si2q->rest_octets;
			bv.data_len = GSM_MACBLOCK_LEN;
			bv.cur_bit = 3;
			bts->si2q_index = (uint8_t) bitvec_get_uint(&bv, 4);

			count = (uint8_t) bitvec_get_uint(&bv, 4);
			if (bts->si2q_count && bts->si2q_count != count) {
				LOGP(DRSL, LOGL_NOTICE, " Rx RSL SI2quater count updated: %u -> %d\n",
				     bts->si2q_count, count);
			}

			bts->si2q_count = count;
			if (bts->si2q_index > bts->si2q_count) {
				LOGP(DRSL, LOGL_ERROR, " Rx RSL SI2quater with index %u > count %u\n",
				     bts->si2q_index, bts->si2q_count);
				return rsl_tx_error_report(trx, RSL_ERR_IE_CONTENT, &cch->chan_nr, NULL, msg);
			}

			if (bts->si2q_index > SI2Q_MAX_NUM || bts->si2q_count > SI2Q_MAX_NUM) {
				LOGP(DRSL, LOGL_ERROR, " Rx RSL SI2quater with impossible parameters: index %u, count %u"
				     "should be <= %u\n", bts->si2q_index, bts->si2q_count, SI2Q_MAX_NUM);
				return rsl_tx_error_report(trx, RSL_ERR_IE_CONTENT, &cch->chan_nr, NULL, msg);
			}

			memset(GSM_BTS_SI2Q(bts, bts->si2q_index), GSM_MACBLOCK_PADDING, sizeof(sysinfo_buf_t));
			memcpy(GSM_BTS_SI2Q(bts, bts->si2q_index), TLVP_VAL(&tp, RSL_IE_FULL_BCCH_INFO), len);
		} else {
			memset(bts->si_buf[osmo_si], GSM_MACBLOCK_PADDING, sizeof(sysinfo_buf_t));
			memcpy(bts->si_buf[osmo_si], TLVP_VAL(&tp, RSL_IE_FULL_BCCH_INFO), len);
		}

		bts->si_valid |= (1 << osmo_si);

		switch (osmo_si) {
		case SYSINFO_TYPE_3:
			if (trx->nr == 0 && num_agch(trx, "RSL") != 1) {
				lchan_deactivate(&trx->bts->c0->ts[0].lchan[CCCH_LCHAN]);
				/* will be reactivated by sapi_deactivate_cb() */
				trx->bts->c0->ts[0].lchan[CCCH_LCHAN].rel_act_kind =
					LCHAN_REL_ACT_REACT;
			}
			/* decode original SI3 Rest Octets as sent by BSC */
			si_buf = (const uint8_t *) GSM_BTS_SI(bts, osmo_si);
			si_buf += offsetof(struct gsm48_system_information_type_3, rest_octets);
			osmo_gsm48_rest_octets_si3_decode(&bts->si3_ro_decoded, si_buf);
			/* patch out GPRS indicator from binary if PCU is not connected; will be enabled
			 * after PCU connects */
			regenerate_si3_restoctets(bts);
			pcu_tx_si(trx->bts, SYSINFO_TYPE_3, true);
			break;
		case SYSINFO_TYPE_4:
			/* decode original SI4 Rest Octets as sent by BSC */
			si_buf = (const uint8_t *) GSM_BTS_SI(bts, osmo_si);
			int si4_ro_offset = get_si4_ro_offset(si_buf);
			if (si4_ro_offset > 0) {
				osmo_gsm48_rest_octets_si4_decode(&bts->si4_ro_decoded,
								  si_buf + si4_ro_offset,
								  GSM_MACBLOCK_LEN - si4_ro_offset);
				/* patch out GPRS indicator from binary if PCU is not connected; will be
				 * enabled after PCU connects */
				regenerate_si4_restoctets(bts);
			}
			break;
		case SYSINFO_TYPE_1:
		case SYSINFO_TYPE_2:
		case SYSINFO_TYPE_13:
			pcu_tx_si(trx->bts, osmo_si, true);
			break;
		default:
			break;
		}

	} else if (TLVP_PRESENT(&tp, RSL_IE_L3_INFO)) {
		uint16_t len = TLVP_LEN(&tp, RSL_IE_L3_INFO);
		if (len > sizeof(sysinfo_buf_t))
			len = sizeof(sysinfo_buf_t);
		bts->si_valid |= (1 << osmo_si);
		memset(bts->si_buf[osmo_si], 0x2b, sizeof(sysinfo_buf_t));
		memcpy(bts->si_buf[osmo_si],
			TLVP_VAL(&tp, RSL_IE_L3_INFO), len);
		LOGP(DRSL, LOGL_INFO, " Rx RSL BCCH INFO (SI%s)\n",
			get_value_string(osmo_sitype_strs, osmo_si));
	} else {
		bts->si_valid &= ~(1 << osmo_si);
		LOGP(DRSL, LOGL_INFO, " RX RSL Disabling BCCH INFO (SI%s)\n",
			get_value_string(osmo_sitype_strs, osmo_si));
		switch (osmo_si) {
		case SYSINFO_TYPE_13:
			pcu_tx_si(trx->bts, SYSINFO_TYPE_13, false);
			break;
		case SYSINFO_TYPE_3:
			memset(&bts->si3_ro_decoded, 0, sizeof(bts->si3_ro_decoded));
			pcu_tx_si(trx->bts, SYSINFO_TYPE_3, false);
			break;
		case SYSINFO_TYPE_1:
			pcu_tx_si(trx->bts, SYSINFO_TYPE_1, false);
			break;
		default:
			break;
		}
	}
	osmo_signal_dispatch(SS_GLOBAL, S_NEW_SYSINFO, bts);

	return 0;
}

/* 8.5.2 CCCH Load Indication (PCH) */
int rsl_tx_ccch_load_ind_pch(struct gsm_bts *bts, uint16_t paging_avail)
{
	struct msgb *msg;

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_cchan_hdr));
	if (!msg)
		return -ENOMEM;
	rsl_cch_push_hdr(msg, RSL_MT_CCCH_LOAD_IND, RSL_CHAN_PCH_AGCH);
	msgb_tv16_put(msg, RSL_IE_PAGING_LOAD, paging_avail);
	msg->trx = bts->c0;

	return abis_bts_rsl_sendmsg(msg);
}

/* 8.5.2 CCCH Load Indication (RACH) */
int rsl_tx_ccch_load_ind_rach(struct gsm_bts *bts, uint16_t total,
			      uint16_t busy, uint16_t access)
{
	struct msgb *msg;

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_cchan_hdr));
	if (!msg)
		return -ENOMEM;
	rsl_cch_push_hdr(msg, RSL_MT_CCCH_LOAD_IND, RSL_CHAN_RACH);
	/* tag and length */
	msgb_tv_put(msg, RSL_IE_RACH_LOAD, 6);
	/* content of the IE */
	msgb_put_u16(msg, total);
	msgb_put_u16(msg, busy);
	msgb_put_u16(msg, access);

	msg->trx = bts->c0;

	return abis_bts_rsl_sendmsg(msg);
}

/* 8.5.4 DELETE INDICATION */
int rsl_tx_delete_ind(struct gsm_bts *bts, const uint8_t *ia, uint8_t ia_len)
{
	struct msgb *msg;

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_cchan_hdr));
	if (!msg)
		return -ENOMEM;
	rsl_cch_push_hdr(msg, RSL_MT_DELETE_IND, RSL_CHAN_PCH_AGCH);
	msgb_tlv_put(msg, RSL_IE_FULL_IMM_ASS_INFO, ia_len, ia);
	msg->trx = bts->c0;

	return abis_bts_rsl_sendmsg(msg);
}

/* 8.5.5 PAGING COMMAND */
static int rsl_rx_paging_cmd(struct gsm_bts_trx *trx, struct msgb *msg)
{
	struct abis_rsl_cchan_hdr *cch = msgb_l2(msg);
	struct tlv_parsed tp;
	struct gsm_bts *bts = trx->bts;
	uint8_t chan_needed = 0, paging_group;
	const uint8_t *identity_lv;
	int rc;

	rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));

	if (!TLVP_PRESENT(&tp, RSL_IE_PAGING_GROUP) ||
	    !TLVP_PRESENT(&tp, RSL_IE_MS_IDENTITY))
		return rsl_tx_error_report(trx, RSL_ERR_MAND_IE_ERROR, &cch->chan_nr, NULL, msg);

	paging_group = *TLVP_VAL(&tp, RSL_IE_PAGING_GROUP);
	identity_lv = TLVP_VAL(&tp, RSL_IE_MS_IDENTITY)-1;

	if (TLVP_PRES_LEN(&tp, RSL_IE_CHAN_NEEDED, 1))
		chan_needed = *TLVP_VAL(&tp, RSL_IE_CHAN_NEEDED);

	rc = paging_add_identity(bts->paging_state, paging_group, identity_lv, chan_needed);
	if (rc < 0) {
		/* FIXME: notfiy the BSC on other errors? */
		if (rc == -ENOSPC) {
			oml_tx_failure_event_rep(&trx->bts->mo, NM_SEVER_WARNING,
						 OSMO_EVT_MIN_PAG_TAB_FULL, "BTS paging table is full");
		}
	}

	pcu_tx_pag_req(identity_lv, chan_needed);

	return 0;
}

/* 8.5.8 SMS BROADCAST COMMAND */
static int rsl_rx_sms_bcast_cmd(struct gsm_bts_trx *trx, struct msgb *msg)
{
	struct abis_rsl_cchan_hdr *cch = msgb_l2(msg);
	struct tlv_parsed tp;
	struct rsl_ie_cb_cmd_type *cb_cmd_type;
	bool extended_cbch = false;
	int rc;

	rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));

	if (!TLVP_PRESENT(&tp, RSL_IE_CB_CMD_TYPE) ||
	    !TLVP_PRESENT(&tp, RSL_IE_SMSCB_MSG))
		return rsl_tx_error_report(trx, RSL_ERR_MAND_IE_ERROR, &cch->chan_nr, NULL, msg);

	if (TLVP_PRESENT(&tp, RSL_IE_SMSCB_CHAN_INDICATOR)) {
		if ((*TLVP_VAL(&tp, RSL_IE_SMSCB_CHAN_INDICATOR) & 0x0f) == 0x01)
			extended_cbch = true;
	}

	cb_cmd_type = (struct rsl_ie_cb_cmd_type *)
					TLVP_VAL(&tp, RSL_IE_CB_CMD_TYPE);

	rc = bts_process_smscb_cmd(trx->bts, *cb_cmd_type, extended_cbch,
				   TLVP_LEN(&tp, RSL_IE_SMSCB_MSG), TLVP_VAL(&tp, RSL_IE_SMSCB_MSG));
	if (rc < 0)
		return rsl_tx_error_report(trx, RSL_ERR_IE_CONTENT, &cch->chan_nr, NULL, msg);

	return 0;
}

/* OSMO_ETWS_CMD - proprietary extension as TS 48.058 has no standardized way to do this :( */
static int rsl_rx_osmo_etws_cmd(struct gsm_bts_trx *trx, struct msgb *msg)
{
	struct abis_rsl_cchan_hdr *cch = msgb_l2(msg);
	struct gsm_bts *bts = trx->bts;
	struct tlv_parsed tp;

	rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));

	if (!TLVP_PRESENT(&tp, RSL_IE_SMSCB_MSG))
		return rsl_tx_error_report(trx, RSL_ERR_MAND_IE_ERROR, &cch->chan_nr, NULL, msg);

	bts->etws.prim_notif_len = TLVP_LEN(&tp, RSL_IE_SMSCB_MSG);
	if (bts->etws.prim_notif_len == 0) {
		LOGP(DRSL, LOGL_NOTICE, "ETWS Primary Notification OFF\n");
		talloc_free(bts->etws.prim_notif);
		bts->etws.prim_notif = NULL;
		bts->etws.prim_notif_len = 0;
		bts->etws.page_size = 0;
		bts->etws.num_pages = 0;
		bts->etws.next_page = 0;
	} else {
		LOGP(DRSL, LOGL_NOTICE, "ETWS Primary Notification: %s\n",
		     osmo_hexdump(TLVP_VAL(&tp, RSL_IE_SMSCB_MSG),
				  TLVP_LEN(&tp, RSL_IE_SMSCB_MSG)));
		talloc_free(bts->etws.prim_notif);
		bts->etws.prim_notif = talloc_memdup(bts, TLVP_VAL(&tp, RSL_IE_SMSCB_MSG),
						     bts->etws.prim_notif_len);

		bts->etws.page_size = 14; /* maximum possible in SI1 Rest Octets */
		bts->etws.num_pages = bts->etws.prim_notif_len / bts->etws.page_size;
		if (bts->etws.prim_notif_len % bts->etws.page_size)
			bts->etws.num_pages++;

		/* toggle the PNI to allow phones to distinguish new from old primary notification */
		bts->etws.pni = !bts->etws.pni;

		/* forward the request to the PCU, so the PCU can send it over any active TBF
		 * to phones which currently don't listen to the paging channel */
		pcu_tx_app_info_req(bts, 0, TLVP_LEN(&tp, RSL_IE_SMSCB_MSG),
				    TLVP_VAL(&tp, RSL_IE_SMSCB_MSG));
	}
	return 0;
}

/*! Prefix a given SACCH frame with a L2/LAPDm UI header and store it in given output buffer.
 *  \param[out] buf Output buffer, must be caller-allocated and hold at least len + 2 or sizeof(sysinfo_buf_t) bytes
 *  \param[out] valid pointer to bit-mask of 'valid' System information types
 *  \param[in] current input data (L3 without L2/L1 header)
 *  \param[in] osmo_si Sytstem Information Type (SYSINFO_TYPE_*)
 *  \param[in] len length of \a current in octets */
static inline void lapdm_ui_prefix(uint8_t *buf, uint32_t *valid, const uint8_t *current, uint8_t osmo_si, uint16_t len)
{
	/* We have to pre-fix with the two-byte LAPDM UI header */
	if (len > sizeof(sysinfo_buf_t) - 2) {
		LOGP(DRSL, LOGL_ERROR, "Truncating received SI%s (%u -> %zu) to prepend LAPDM UI header (2 bytes)\n",
		     get_value_string(osmo_sitype_strs, osmo_si), len, sizeof(sysinfo_buf_t) - 2);
		len = sizeof(sysinfo_buf_t) - 2;
	}

	(*valid) |= (1 << osmo_si);
	buf[0] = 0x03;	/* C/R + EA */
	buf[1] = 0x03;	/* UI frame */

	memset(buf + 2, GSM_MACBLOCK_PADDING, sizeof(sysinfo_buf_t) - 2);
	memcpy(buf + 2, current, len);
}

/*! Prefix a given SACCH frame with a L2/LAPDm UI header and store it in given BTS SACCH buffer
 *  \param[out] bts BTS in whose System Information State we shall store
 *  \param[in] current input data (L3 without L2/L1 header)
 *  \param[in] osmo_si Sytstem Information Type (SYSINFO_TYPE_*)
 *  \param[in] len length of \a current in octets */
static inline void lapdm_ui_prefix_bts(struct gsm_bts *bts, const uint8_t *current, uint8_t osmo_si, uint16_t len)
{
	lapdm_ui_prefix(GSM_BTS_SI(bts, osmo_si), &bts->si_valid, current, osmo_si, len);
}

/*! Prefix a given SACCH frame with a L2/LAPDm UI header and store it in given lchan SACCH buffer
 *  \param[out] lchan Logical Channel in whose System Information State we shall store
 *  \param[in] current input data (L3 without L2/L1 header)
 *  \param[in] osmo_si Sytstem Information Type (SYSINFO_TYPE_*)
 *  \param[in] len length of \a current in octets */
static inline void lapdm_ui_prefix_lchan(struct gsm_lchan *lchan, const uint8_t *current, uint8_t osmo_si, uint16_t len)
{
	lapdm_ui_prefix(GSM_LCHAN_SI(lchan, osmo_si), &lchan->si.valid, current, osmo_si, len);
}

/* 8.6.2 SACCH FILLING */
static int rsl_rx_sacch_fill(struct gsm_bts_trx *trx, struct msgb *msg)
{
	struct gsm_bts *bts = trx->bts;
	struct tlv_parsed tp;
	uint8_t rsl_si;
	enum osmo_sysinfo_type osmo_si;

	rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));

	/* 9.3.30 System Info Type */
	if (!TLVP_PRESENT(&tp, RSL_IE_SYSINFO_TYPE))
		return rsl_tx_error_report(trx, RSL_ERR_MAND_IE_ERROR, NULL, NULL, msg);

	rsl_si = *TLVP_VAL(&tp, RSL_IE_SYSINFO_TYPE);
	if (!OSMO_IN_ARRAY(rsl_si, rsl_sacch_sitypes))
		return rsl_tx_error_report(trx, RSL_ERR_IE_CONTENT, NULL, NULL, msg);

	osmo_si = osmo_rsl2sitype(rsl_si);
	if (osmo_si == SYSINFO_TYPE_NONE) {
		LOGP(DRSL, LOGL_NOTICE, " Rx SACCH SI 0x%02x not supported.\n", rsl_si);
		return rsl_tx_error_report(trx, RSL_ERR_IE_CONTENT, NULL, NULL, msg);
	}
	if (TLVP_PRESENT(&tp, RSL_IE_L3_INFO)) {
		uint16_t len = TLVP_LEN(&tp, RSL_IE_L3_INFO);
		struct gsm_bts_trx *t;

		lapdm_ui_prefix_bts(bts, TLVP_VAL(&tp, RSL_IE_L3_INFO), osmo_si, len);

		/* Propagate SI change to all lchans which adhere to BTS-global default. */
		llist_for_each_entry(t, &bts->trx_list, list) {
			int i, j;
			for (i = 0; i < ARRAY_SIZE(t->ts); i++) {
				struct gsm_bts_trx_ts *ts = &t->ts[i];
				for (j = 0; j < ARRAY_SIZE(ts->lchan); j++) {
					struct gsm_lchan *lchan = &ts->lchan[j];
					if (lchan->state == LCHAN_S_NONE || (lchan->si.overridden & (1 << osmo_si)))
						continue;
					lapdm_ui_prefix_lchan(lchan, TLVP_VAL(&tp, RSL_IE_L3_INFO), osmo_si, len);
				}
			}
		}

		LOGP(DRSL, LOGL_INFO, " Rx RSL SACCH FILLING (SI%s, %u bytes)\n",
		     get_value_string(osmo_sitype_strs, osmo_si), len);
	} else {
		struct gsm_bts_trx *t;

		bts->si_valid &= ~(1 << osmo_si);

		/* Propagate SI change to all lchans which adhere to BTS-global default. */
		llist_for_each_entry(t, &bts->trx_list, list) {
			int i, j;
			for (i = 0; i < ARRAY_SIZE(t->ts); i++) {
				struct gsm_bts_trx_ts *ts = &t->ts[i];
				for (j = 0; j < ARRAY_SIZE(ts->lchan); j++) {
					struct gsm_lchan *lchan = &ts->lchan[j];
					if (lchan->state == LCHAN_S_NONE || (lchan->si.overridden & (1 << osmo_si)))
						continue;
					lchan->si.valid &= ~(1 << osmo_si);
				}
			}
		}
		LOGP(DRSL, LOGL_INFO, " Rx RSL Disabling SACCH FILLING (SI%s)\n",
			get_value_string(osmo_sitype_strs, osmo_si));
	}
	osmo_signal_dispatch(SS_GLOBAL, S_NEW_SYSINFO, bts);

	return 0;

}

/* Parser for ip.access specific MS/BS Power parameters */
static int parse_power_ctrl_params(struct gsm_power_ctrl_params *params,
				   const uint8_t *data, size_t data_len)
{
	const struct tlv_p_entry *ie;
	struct tlv_parsed tp[2];
	unsigned int i;
	int rc;

	/* There can be multiple RSL_IPAC_EIE_MEAS_AVG_CFG, so we use tlv_parse2() */
	rc = tlv_parse2(&tp[0], ARRAY_SIZE(tp), &rsl_ipac_eie_tlvdef,
			data, data_len, 0, 0);
	if (rc < 0)
		return rc;

	/* Either of RSL_IPAC_EIE_{BS,MS}_PWR_CTL must be present */
	if (TLVP_PRESENT(&tp[0], RSL_IPAC_EIE_BS_PWR_CTL) &&
	    TLVP_PRESENT(&tp[0], RSL_IPAC_EIE_MS_PWR_CTL))
		return -EINVAL;

	/* (TV) Thresholds: {L,U}_RXLEV_XX_P and {L,U}_RXQUAL_XX_P */
	if ((ie = TLVP_GET(&tp[0], RSL_IPAC_EIE_BS_PWR_CTL)) != NULL ||
	    (ie = TLVP_GET(&tp[0], RSL_IPAC_EIE_MS_PWR_CTL)) != NULL) {
		const struct ipac_preproc_pc_thresh *thresh;

		thresh = (const struct ipac_preproc_pc_thresh *) ie->val;

		params->rxlev_meas.lower_thresh = thresh->l_rxlev;
		params->rxlev_meas.upper_thresh = thresh->u_rxlev;

		params->rxqual_meas.lower_thresh = thresh->l_rxqual;
		params->rxqual_meas.upper_thresh = thresh->u_rxqual;
	}

	/* (TV) PC Threshold Comparators */
	if ((ie = TLVP_GET(&tp[0], RSL_IPAC_EIE_PC_THRESH_COMP)) != NULL) {
		const struct ipac_preproc_pc_comp *thresh_comp;

		thresh_comp = (const struct ipac_preproc_pc_comp *) ie->val;

		/* RxLev: P1, N1, P2, N2 (see 3GPP TS 45.008, A.3.2.1, a & b) */
		params->rxlev_meas.lower_cmp_p = thresh_comp->p1;
		params->rxlev_meas.lower_cmp_n = thresh_comp->n1;
		params->rxlev_meas.upper_cmp_p = thresh_comp->p2;
		params->rxlev_meas.upper_cmp_n = thresh_comp->n2;

		/* RxQual: P3, N3, P4, N4 (see 3GPP TS 45.008, A.3.2.1, c & d) */
		params->rxqual_meas.lower_cmp_p = thresh_comp->p3;
		params->rxqual_meas.lower_cmp_n = thresh_comp->n3;
		params->rxqual_meas.upper_cmp_p = thresh_comp->p4;
		params->rxqual_meas.upper_cmp_n = thresh_comp->n4;

		/* Minimum interval between power level changes (P_Con_INTERVAL) */
		params->ctrl_interval = thresh_comp->pc_interval;

		/* Power increase / reduce step size: POWER_{INC,RED}_STEP_SIZE */
		params->inc_step_size_db = thresh_comp->inc_step_size;
		params->red_step_size_db = thresh_comp->red_step_size;
	}

	/* (TLV) Measurement Averaging parameters for RxLev/RxQual */
	for (i = 0; i < ARRAY_SIZE(tp); i++) {
		const struct ipac_preproc_ave_cfg *ave_cfg;
		struct gsm_power_ctrl_meas_params *mp;

		ie = TLVP_GET(&tp[0], RSL_IPAC_EIE_MEAS_AVG_CFG);
		if (ie == NULL)
			break;

		if (ie->len < sizeof(*ave_cfg))
			return -EINVAL;

		ave_cfg = (const struct ipac_preproc_ave_cfg *) ie->val;

		switch (ave_cfg->param_id) {
		case IPAC_RXQUAL_AVE:
			mp = &params->rxqual_meas;
			break;
		case IPAC_RXLEV_AVE:
			mp = &params->rxlev_meas;
			break;
		default:
			/* Skip unknown parameters */
			continue;
		}

		mp->h_reqave = ave_cfg->h_reqave;
		mp->h_reqt = ave_cfg->h_reqt;

		mp->algo = ave_cfg->ave_method + 1;
		switch (ave_cfg->ave_method) {
		case IPAC_OSMO_EWMA_AVE:
			if (ie->len > sizeof(*ave_cfg))
				mp->ewma.alpha = ave_cfg->params[0];
			break;

		/* FIXME: not implemented */
		case IPAC_UNWEIGHTED_AVE:
		case IPAC_WEIGHTED_AVE:
		case IPAC_MEDIAN_AVE:
			break;
		}
	}

	return 0;
}

/* ip.access specific Measurement Pre-processing Defaults for MS/BS Power control */
static int rsl_rx_meas_preproc_dft(struct gsm_bts_trx *trx, struct msgb *msg)
{
	const struct gsm_bts *bts = trx->bts;
	struct gsm_power_ctrl_params *params;
	const struct tlv_p_entry *ie;
	struct tlv_parsed tp;
	int rc;

	LOGPTRX(trx, DRSL, LOGL_INFO, "Rx Measurement Pre-processing Defaults\n");

	rc = rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));
	if (rc < 0) {
		LOGPTRX(trx, DRSL, LOGL_ERROR, "Failed to parse ip.access specific "
			"Measurement Pre-processing Defaults for MS/BS Power control\n");
		return rsl_tx_error_report(trx, RSL_ERR_PROTO, NULL, NULL, msg);
	}

	/* TLV (O) BS Power Parameters IE */
	if ((ie = TLVP_GET(&tp, RSL_IE_BS_POWER_PARAM)) != NULL) {
		/* Allocate a new chunk and initialize with default values */
		params = talloc_memdup(trx, &power_ctrl_params_def, sizeof(*params));

		if (ie->len && parse_power_ctrl_params(params, ie->val, ie->len) == 0) {
			/* Initially it points to the global defaults */
			if (trx->bs_dpc_params != &bts->bs_dpc_params)
				talloc_free(trx->bs_dpc_params);
			trx->bs_dpc_params = params;
		} else {
			LOGPTRX(trx, DRSL, LOGL_ERROR, "Failed to parse BS Power Parameters IE\n");
			rsl_tx_error_report(trx, RSL_ERR_IE_CONTENT, NULL, NULL, msg);
			talloc_free(params);
		}
	}

	/* TLV (O) MS Power Parameters IE */
	if ((ie = TLVP_GET(&tp, RSL_IE_MS_POWER_PARAM)) != NULL) {
		/* Allocate a new chunk and initialize with default values */
		params = talloc_memdup(trx, &power_ctrl_params_def, sizeof(*params));

		if (ie->len && parse_power_ctrl_params(params, ie->val, ie->len) == 0) {
			/* Initially it points to the global defaults */
			if (trx->ms_dpc_params != &bts->ms_dpc_params)
				talloc_free(trx->ms_dpc_params);
			trx->ms_dpc_params = params;
		} else {
			LOGPTRX(trx, DRSL, LOGL_ERROR, "Failed to parse MS Power Parameters IE\n");
			rsl_tx_error_report(trx, RSL_ERR_IE_CONTENT, NULL, NULL, msg);
			talloc_free(params);
		}
	}

	return 0;
}

/* 8.5.6 IMMEDIATE ASSIGN COMMAND is received */
static int rsl_rx_imm_ass(struct gsm_bts_trx *trx, struct msgb *msg)
{
	struct abis_rsl_cchan_hdr *cch = msgb_l2(msg);
	struct tlv_parsed tp;

	rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));

	if (!TLVP_PRESENT(&tp, RSL_IE_FULL_IMM_ASS_INFO))
		return rsl_tx_error_report(trx, RSL_ERR_MAND_IE_ERROR, &cch->chan_nr, NULL, msg);

	rate_ctr_inc2(trx->bts->ctrs, BTS_CTR_AGCH_RCVD);

	/* cut down msg to the 04.08 RR part */
	msg->l3h = (uint8_t *) TLVP_VAL(&tp, RSL_IE_FULL_IMM_ASS_INFO);
	msg->data = msg->l3h;
	msg->l2h = NULL;
	msg->len = TLVP_LEN(&tp, RSL_IE_FULL_IMM_ASS_INFO);

	/* put into the AGCH queue of the BTS */
	if (bts_agch_enqueue(trx->bts, msg) < 0) {
		/* if there is no space in the queue: send DELETE IND */
		rsl_tx_delete_ind(trx->bts, TLVP_VAL(&tp, RSL_IE_FULL_IMM_ASS_INFO),
				  TLVP_LEN(&tp, RSL_IE_FULL_IMM_ASS_INFO));
		rate_ctr_inc2(trx->bts->ctrs, BTS_CTR_AGCH_DELETED);
		msgb_free(msg);
	}

	/* return 1 means: don't msgb_free() the msg */
	return 1;
}

/*
 * dedicated channel related messages
 */

/* Send an RF CHANnel RELease ACKnowledge with the given chan_nr. This chan_nr may mismatch the current
 * lchan state, if we received a CHANnel RELease for an already released channel, and we're just acking
 * what we got without taking any action. */
static int tx_rf_rel_ack(struct gsm_lchan *lchan, uint8_t chan_nr)
{
	struct msgb *msg;

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	rsl_dch_push_hdr(msg, RSL_MT_RF_CHAN_REL_ACK, chan_nr);
	msg->trx = lchan->ts->trx;

	return abis_bts_rsl_sendmsg(msg);
}

/* 8.4.19 sending RF CHANnel RELease ACKnowledge */
int rsl_tx_rf_rel_ack(struct gsm_lchan *lchan)
{
	uint8_t chan_nr = gsm_lchan2chan_nr(lchan);
	bool send_rel_ack;

	switch (lchan->rel_act_kind) {
	case LCHAN_REL_ACT_RSL:
		send_rel_ack = true;
		break;

	case LCHAN_REL_ACT_PCU:
		switch (lchan->ts->pchan) {
		case GSM_PCHAN_OSMO_DYN:
			if (lchan->ts->dyn.pchan_is != GSM_PCHAN_PDCH) {
				LOGP(DRSL, LOGL_ERROR, "%s (ss=%d) PDCH release: not in PDCH mode\n",
				     gsm_ts_and_pchan_name(lchan->ts), lchan->nr);
				/* well, what to do about it ... carry on and hope it's fine. */
			}
			if (lchan->ts->dyn.pchan_want != GSM_PCHAN_PDCH) {
				/* Continue to ack the release below. (This is a non-standard rel ack invented
				 * specifically for GSM_PCHAN_OSMO_DYN). */
				/* remember the fact that the TS is now released */
				lchan->ts->dyn.pchan_is = GSM_PCHAN_NONE;
				send_rel_ack = true;
			} else {
				/* Administrteively locked TRX, no need to
				   inform BSC. Keep pchan_is for when we are
				   unlocked again, since lower layers are stil
				   lconfigured for PDCH but we simply annonced
				   non-availability to PCU */
				send_rel_ack = false;
			}
			break;
		case GSM_PCHAN_TCH_F_PDCH:
			/* GSM_PCHAN_TCH_F_PDCH, does not require a rel ack. The caller
			 * l1sap_info_rel_cnf() will continue with bts_model_ts_disconnect(). */
			send_rel_ack = false;
			break;
		case GSM_PCHAN_PDCH:
			/* Release was instructed by the BTS, for instance because the TRX is
			 * administrateively Locked */
			send_rel_ack = false;
			break;
		default:
			LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "PCU rel ack for unexpected lchan kind %s\n",
				  gsm_pchan_name(lchan->ts->pchan));
			/* Release certainly was not requested by the BSC via RSL, so don't ack. */
			send_rel_ack = false;
			break;
		}
		break;

	default:
		/* A rel that was not requested by the BSC via RSL, hence not sending a rel ack to the
		 * BSC. */
		send_rel_ack = false;
		break;
	}

	if (!send_rel_ack) {
		LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "%s not sending REL ACK\n", gsm_lchan_name(lchan));
		return 0;
	}

	LOGP(DRSL, LOGL_NOTICE, "%s (ss=%d) %s Tx CHAN REL ACK\n",
	     gsm_ts_and_pchan_name(lchan->ts), lchan->nr,
	     gsm_lchant_name(lchan->type));

	/*
	 * Free the LAPDm resources now that the BTS
	 * has released all the resources.
	 */
	lapdm_channel_exit(&lchan->lapdm_ch);

	/* Also ensure that there are no leftovers from repeated FACCH or
	 * repeated SACCH that might cause memory leakage. */
	msgb_free(lchan->tch.rep_facch[0].msg);
	msgb_free(lchan->tch.rep_facch[1].msg);
	lchan->tch.rep_facch[0].msg = NULL;
	lchan->tch.rep_facch[1].msg = NULL;
	msgb_free(lchan->rep_sacch);
	lchan->rep_sacch = NULL;

	return tx_rf_rel_ack(lchan, chan_nr);
}

/* 8.4.2 sending CHANnel ACTIVation ACKnowledge */
static int rsl_tx_chan_act_ack(struct gsm_lchan *lchan)
{
	struct gsm_time *gtime = get_time(lchan->ts->trx->bts);
	struct msgb *msg;
	uint8_t chan_nr = gsm_lchan2chan_nr(lchan);
	uint8_t ie[2];

	LOGP(DRSL, LOGL_NOTICE, "%s (ss=%d) %s Tx CHAN ACT ACK\n",
	     gsm_ts_and_pchan_name(lchan->ts), lchan->nr,
	     gsm_lchant_name(lchan->type));

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	gsm48_gen_starting_time(ie, gtime);
	msgb_tv_fixed_put(msg, RSL_IE_FRAME_NUMBER, 2, ie);
	rsl_dch_push_hdr(msg, RSL_MT_CHAN_ACTIV_ACK, chan_nr);
	msg->trx = lchan->ts->trx;

	/* since activation was successful, do some lchan initialization */
	lchan_meas_reset(lchan);

	return abis_bts_rsl_sendmsg(msg);
}

/* 8.4.7 sending HANDOver DETection */
int rsl_tx_hando_det(struct gsm_lchan *lchan, uint8_t *ho_delay)
{
	struct msgb *msg;
	uint8_t chan_nr = gsm_lchan2chan_nr(lchan);

	LOGPLCHAN(lchan, DRSL, LOGL_INFO, "Sending HANDOver DETect\n");

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	/* 9.3.17 Access Delay */
	if (ho_delay)
		msgb_tv_put(msg, RSL_IE_ACCESS_DELAY, *ho_delay);

	rsl_dch_push_hdr(msg, RSL_MT_HANDO_DET, chan_nr);
	msg->trx = lchan->ts->trx;

	return abis_bts_rsl_sendmsg(msg);
}

/* 8.4.3 sending CHANnel ACTIVation Negative ACK */
static int _rsl_tx_chan_act_nack(struct gsm_bts_trx *trx, uint8_t chan_nr, uint8_t cause,
				 struct gsm_lchan *lchan)
{
	struct msgb *msg;

	if (lchan)
		LOGP(DRSL, LOGL_NOTICE, "%s: ", gsm_lchan_name(lchan));
	else
		LOGP(DRSL, LOGL_NOTICE, "0x%02x: ", chan_nr);
	LOGPC(DRSL, LOGL_NOTICE, "Sending Channel Activated NACK: cause = 0x%02x\n", cause);

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	/* 9.3.26 Cause */
	msgb_tlv_put(msg, RSL_IE_CAUSE, 1, &cause);
	rsl_dch_push_hdr(msg, RSL_MT_CHAN_ACTIV_NACK, chan_nr);
	msg->trx = trx;

	return abis_bts_rsl_sendmsg(msg);
}
static int rsl_tx_chan_act_nack(struct gsm_lchan *lchan, uint8_t cause) {
	return _rsl_tx_chan_act_nack(lchan->ts->trx, gsm_lchan2chan_nr(lchan), cause, lchan);
}

/* Send an RSL Channel Activation Ack if cause is zero, a Nack otherwise. */
int rsl_tx_chan_act_acknack(struct gsm_lchan *lchan, uint8_t cause)
{
	if (lchan->rel_act_kind != LCHAN_REL_ACT_RSL) {
		LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "not sending CHAN ACT %s\n",
			  cause ? "NACK" : "ACK");
		return 0;
	}

	if (cause)
		return rsl_tx_chan_act_nack(lchan, cause);
	return rsl_tx_chan_act_ack(lchan);
}

/* 8.4.4 sending CONNection FAILure */
int rsl_tx_conn_fail(const struct gsm_lchan *lchan, uint8_t cause)
{
	struct msgb *msg;
	uint8_t chan_nr = gsm_lchan2chan_nr(lchan);

	LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "Sending Connection Failure: cause = 0x%02x\n", cause);

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	/* 9.3.26 Cause */
	msgb_tlv_put(msg, RSL_IE_CAUSE, 1, &cause);
	rsl_dch_push_hdr(msg, RSL_MT_CONN_FAIL, chan_nr);
	msg->trx = lchan->ts->trx;

	return abis_bts_rsl_sendmsg(msg);
}

/* 8.5.3 sending CHANnel ReQuireD */
int rsl_tx_chan_rqd(struct gsm_bts_trx *trx, struct gsm_time *gtime,
		    uint8_t ra, uint8_t acc_delay)
{
	struct msgb *nmsg;
	uint8_t payload[3];

	LOGP(DRSL, LOGL_NOTICE, "Sending Channel Required\n");

	nmsg = rsl_msgb_alloc(sizeof(struct abis_rsl_cchan_hdr));
	if (!nmsg)
		return -ENOMEM;

	/* 9.3.19 Request Reference */
	payload[0] = ra;
	gsm48_gen_starting_time(payload+1, gtime);
	msgb_tv_fixed_put(nmsg, RSL_IE_REQ_REFERENCE, 3, payload);

	/* 9.3.17 Access Delay */
	msgb_tv_put(nmsg, RSL_IE_ACCESS_DELAY, acc_delay);

	rsl_cch_push_hdr(nmsg, RSL_MT_CHAN_RQD, RSL_CHAN_RACH); // FIXME
	nmsg->trx = trx;

	return abis_bts_rsl_sendmsg(nmsg);
}

/* copy the SACCH related sysinfo from BTS global buffer to lchan specific buffer */
static void copy_sacch_si_to_lchan(struct gsm_lchan *lchan)
{
	struct gsm_bts *bts = lchan->ts->trx->bts;
	unsigned int i;

	for (i = 0; i < ARRAY_SIZE(rsl_sacch_sitypes); i++) {
		uint8_t rsl_si = rsl_sacch_sitypes[i];
		int osmo_si = osmo_rsl2sitype(rsl_si);
		uint32_t osmo_si_shifted = (1 << osmo_si);
		osmo_static_assert(_MAX_SYSINFO_TYPE <= sizeof(osmo_si_shifted) * 8,
				   si_enum_vals_fit_in_bit_mask);

		if (osmo_si == SYSINFO_TYPE_NONE)
			continue;
		if (!(bts->si_valid & osmo_si_shifted)) {
			lchan->si.valid &= ~osmo_si_shifted;
			continue;
		}
		lchan->si.valid |= osmo_si_shifted;
		memcpy(GSM_LCHAN_SI(lchan, osmo_si), GSM_BTS_SI(bts, osmo_si), sizeof(sysinfo_buf_t));
	}
}


static int encr_info2lchan(struct gsm_lchan *lchan,
			   const uint8_t *val, uint8_t len)
{
	int rc;
	struct gsm_bts *bts = lchan->ts->trx->bts;
	const char *ciph_name = get_value_string(gsm0808_chosen_enc_alg_names, *val);

	/* check if the encryption algorithm sent by BSC is supported! */
	rc = bts_supports_cipher(bts, *val);
	if (rc != 1) {
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "BTS doesn't support cipher %s\n", ciph_name);
		return -EINVAL;
	}

	/* length can be '1' in case of no ciphering */
	if (len < 1) {
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Encryption Info cannot have len=%d\n", len);
		return -EINVAL;
	}

	lchan->encr.alg_id = *val++;
	lchan->encr.key_len = len -1;
	if (lchan->encr.key_len > sizeof(lchan->encr.key))
		lchan->encr.key_len = sizeof(lchan->encr.key);
	memcpy(lchan->encr.key, val, lchan->encr.key_len);
	LOGPLCHAN(lchan, DRSL, LOGL_DEBUG, "Setting lchan cipher algorithm %s\n", ciph_name);

	return 0;
}

/* Make sure no state from TCH use remains. */
static void clear_lchan_for_pdch_activ(struct gsm_lchan *lchan)
{
	/* These values don't apply to PDCH, just clear them. Particularly the encryption must be
	 * cleared, or we would enable encryption on PDCH with parameters remaining from the TCH. */
	lchan->rsl_cmode = 0;
	lchan->tch_mode = 0;
	memset(&lchan->encr, 0, sizeof(lchan->encr));
	memset(&lchan->ho, 0, sizeof(lchan->ho));
	memset(&lchan->ms_power_ctrl, 0, sizeof(lchan->ms_power_ctrl));
	memset(&lchan->bs_power_ctrl, 0, sizeof(lchan->bs_power_ctrl));
	lchan->rqd_ta = 0;
	copy_sacch_si_to_lchan(lchan);
	memset(&lchan->tch, 0, sizeof(lchan->tch));
}

/*!
 * Store the CHAN_ACTIV msg, connect the L1 timeslot in the proper type and
 * then invoke rsl_rx_chan_activ() with msg.
 */
static int dyn_ts_l1_reconnect(struct gsm_bts_trx_ts *ts, struct msgb *msg)
{
	DEBUGP(DRSL, "%s dyn_ts_l1_reconnect\n", gsm_ts_and_pchan_name(ts));

	switch (ts->dyn.pchan_want) {
	case GSM_PCHAN_TCH_F:
	case GSM_PCHAN_TCH_H:
	case GSM_PCHAN_SDCCH8_SACCH8C:
		break;
	case GSM_PCHAN_PDCH:
		/* Only the first lchan matters for PDCH */
		clear_lchan_for_pdch_activ(ts->lchan);
		break;
	default:
		LOGP(DRSL, LOGL_ERROR,
		     "%s Cannot reconnect as pchan %s\n",
		     gsm_ts_and_pchan_name(ts),
		     gsm_pchan_name(ts->dyn.pchan_want));
		return -EINVAL;
	}

	/* We will feed this back to rsl_rx_chan_activ() later */
	ts->dyn.pending_chan_activ = msg;

	/* Disconnect, continue connecting from cb_ts_disconnected(). */
	DEBUGP(DRSL, "%s Disconnect\n", gsm_ts_and_pchan_name(ts));
	return bts_model_ts_disconnect(ts);
}

static enum gsm_phys_chan_config dyn_pchan_from_chan_nr(uint8_t chan_nr)
{
	uint8_t cbits = chan_nr >> 3;
	switch (cbits) {
	case ABIS_RSL_CHAN_NR_CBITS_Bm_ACCHs:
		return GSM_PCHAN_TCH_F;
	case ABIS_RSL_CHAN_NR_CBITS_Lm_ACCHs(0):
	case ABIS_RSL_CHAN_NR_CBITS_Lm_ACCHs(1):
		return GSM_PCHAN_TCH_H;
	case ABIS_RSL_CHAN_NR_CBITS_SDCCH8_ACCH(0):
	case ABIS_RSL_CHAN_NR_CBITS_SDCCH8_ACCH(1):
	case ABIS_RSL_CHAN_NR_CBITS_SDCCH8_ACCH(2):
	case ABIS_RSL_CHAN_NR_CBITS_SDCCH8_ACCH(3):
	case ABIS_RSL_CHAN_NR_CBITS_SDCCH8_ACCH(4):
	case ABIS_RSL_CHAN_NR_CBITS_SDCCH8_ACCH(5):
	case ABIS_RSL_CHAN_NR_CBITS_SDCCH8_ACCH(6):
	case ABIS_RSL_CHAN_NR_CBITS_SDCCH8_ACCH(7):
		return GSM_PCHAN_SDCCH8_SACCH8C;
	case ABIS_RSL_CHAN_NR_CBITS_OSMO_PDCH:
		return GSM_PCHAN_PDCH;
	default:
		LOGP(DRSL, LOGL_ERROR,
		     "chan nr 0x%x not covered by dyn_pchan_from_chan_nr()\n",
		     chan_nr);
		return GSM_PCHAN_UNKNOWN;
	}
}

/* Parse RSL_IE_OSMO_REP_ACCH_CAP */
static void parse_repeated_acch_capability(struct gsm_lchan *lchan, struct tlv_parsed *tp)
{
	/* 3GPP TS 24.008, section 10.5.1.7 defines a Repeated ACCH Capability
	 * bit that indicates if REPEATED FACCH/SACCH is supported or not.
	 * Unfortunately there is not 3gpp spec that describes how this bit
	 * should be communicated in the RSL CHANNEL ACTIVATION. For osmo-bts
	 * we will use a propritary IE. */

	memset(&lchan->repeated_acch_capability, 0, sizeof(lchan->repeated_acch_capability));

	if (!TLVP_PRESENT(tp, RSL_IE_OSMO_REP_ACCH_CAP))
		return;
	if (TLVP_LEN(tp, RSL_IE_OSMO_REP_ACCH_CAP) != sizeof(lchan->repeated_acch_capability))
		return;

	memcpy(&lchan->repeated_acch_capability, TLVP_VAL(tp, RSL_IE_OSMO_REP_ACCH_CAP),
	       sizeof(lchan->repeated_acch_capability));
}

/* 8.4.1 CHANnel ACTIVation is received */
static int rsl_rx_chan_activ(struct msgb *msg)
{
	struct abis_rsl_dchan_hdr *dch = msgb_l2(msg);
	struct gsm_lchan *lchan = msg->lchan;
	struct gsm_bts_trx_ts *ts = lchan->ts;
	struct tlv_parsed tp;
	const struct tlv_p_entry *ie;
	uint8_t type, cause;
	int rc;

	if (lchan->state != LCHAN_S_NONE) {
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "error: lchan is not available, but in state: %s.\n",
			  gsm_lchans_name(lchan->state));
		return rsl_tx_chan_act_nack(lchan, RSL_ERR_EQUIPMENT_FAIL);
	}

	if (ts->pchan == GSM_PCHAN_OSMO_DYN) {
		ts->dyn.pchan_want = dyn_pchan_from_chan_nr(dch->chan_nr);
		DEBUGP(DRSL, "%s rx chan activ\n", gsm_ts_and_pchan_name(ts));

		if (ts->dyn.pchan_is != ts->dyn.pchan_want) {
			/*
			 * The phy has the timeslot connected in a different
			 * mode than this activation needs it to be.
			 * Re-connect, then come back to rsl_rx_chan_activ().
			 */
			rc = dyn_ts_l1_reconnect(ts, msg);
			if (rc)
				return rsl_tx_chan_act_nack(lchan, RSL_ERR_NORMAL_UNSPEC);
			/* indicate that the msgb should not be freed. */
			return 1;
		}
	}

	LOGPLCHAN(lchan, DRSL, LOGL_DEBUG, "rx Channel Activation in state: %s.\n",
		  gsm_lchans_name(lchan->state));

	/* Initialize MS Power Control defaults */
	lchan->ms_power_ctrl = (struct lchan_power_ctrl_state) {
		.max = ms_pwr_ctl_lvl(lchan->ts->trx->bts->band, 0),
		.current = lchan->ms_power_ctrl.max,
	};

	/* Initialize BS Power Control defaults */
	lchan->bs_power_ctrl = (struct lchan_power_ctrl_state) {
		.max = 2 * 15, /* maximum defined in 9.3.4 */
		.current = 0,
	};

	rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));

	/* 9.3.3 Activation Type */
	if (!TLVP_PRESENT(&tp, RSL_IE_ACT_TYPE)) {
		LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "missing Activation Type\n");
		return rsl_tx_chan_act_nack(lchan, RSL_ERR_MAND_IE_ERROR);
	}
	type = *TLVP_VAL(&tp, RSL_IE_ACT_TYPE);

	/* 9.3.6 Channel Mode */
	if (type != RSL_ACT_OSMO_PDCH) {
		if (rsl_handle_chan_mod_ie(lchan, &tp, &cause) != 0)
			return rsl_tx_chan_act_nack(lchan, cause);
		if (rsl_handle_chan_ident_ie(lchan, &tp, &cause) != 0)
			return rsl_tx_chan_act_nack(lchan, cause);
		if (rsl_handle_osmo_tsc_ie(lchan, &tp, &cause) != 0)
			return rsl_tx_chan_act_nack(lchan, cause);
	}

	/* 9.3.7 Encryption Information */
	if (TLVP_PRESENT(&tp, RSL_IE_ENCR_INFO)) {
		uint8_t len = TLVP_LEN(&tp, RSL_IE_ENCR_INFO);
		const uint8_t *val = TLVP_VAL(&tp, RSL_IE_ENCR_INFO);

		if (encr_info2lchan(lchan, val, len) < 0) {
			rsl_tx_error_report(msg->trx, RSL_ERR_IE_CONTENT, &dch->chan_nr, NULL, msg);
			return rsl_tx_chan_act_acknack(lchan, RSL_ERR_ENCR_UNIMPL);
		}
	} else
		memset(&lchan->encr, 0, sizeof(lchan->encr));

	/* 9.3.9 Handover Reference */
	if ((type == RSL_ACT_INTER_ASYNC || type == RSL_ACT_INTER_SYNC)) {
		/* According to 8.4.1, the Handover Reference element is included
		 * if activation type is handover. Assuming it's mandatory. */
		if (!TLVP_PRES_LEN(&tp, RSL_IE_HANDO_REF, 1)) {
			LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "Missing Handover Reference IE\n");
			return rsl_tx_chan_act_nack(lchan, RSL_ERR_MAND_IE_ERROR);
		}
		lchan->ho.active = HANDOVER_ENABLED;
		lchan->ho.ref = *TLVP_VAL(&tp, RSL_IE_HANDO_REF);
	}

	/* 9.3.4 BS Power */
	if (TLVP_PRES_LEN(&tp, RSL_IE_BS_POWER, 1)) {
		if (*TLVP_VAL(&tp, RSL_IE_BS_POWER) & (1 << 4)) {
			LOGPLCHAN(lchan, DRSL, LOGL_NOTICE,
				  "Fast Power Control is not supported\n");
			return rsl_tx_chan_act_nack(lchan, RSL_ERR_SERV_OPT_UNIMPL);
		}

		uint8_t red = BS_POWER2DB(*TLVP_VAL(&tp, RSL_IE_BS_POWER));

		/* BS power reduction is generally not allowed on BCCH/CCCH carrier.
		 * However, we allow it in the BCCH carrier power reduction operation.
		 * Constrain BS power value by the maximum reduction for this timeslot. */
		if (ts->trx->bts->c0 == ts->trx)
			red = OSMO_MIN(red, ts->c0_power_red_db);

		lchan->bs_power_ctrl.max = red;
		lchan->bs_power_ctrl.current = red;

		LOGPLCHAN(lchan, DRSL, LOGL_DEBUG, "BS Power attenuation %u dB\n",
			  lchan->bs_power_ctrl.current);
	}

	/* 9.3.13 MS Power */
	if (TLVP_PRES_LEN(&tp, RSL_IE_MS_POWER, 1)) {
		lchan->ms_power_ctrl.max = *TLVP_VAL(&tp, RSL_IE_MS_POWER) & 0x1F;
		lchan->ms_power_ctrl.current = lchan->ms_power_ctrl.max;
	}
	/* 9.3.24 Timing Advance */
	if (TLVP_PRES_LEN(&tp, RSL_IE_TIMING_ADVANCE, 1))
		lchan->rqd_ta = *TLVP_VAL(&tp, RSL_IE_TIMING_ADVANCE);

	/* 9.3.31 (TLV) MS Power Parameters IE (vendor specific) */
	if ((ie = TLVP_GET(&tp, RSL_IE_MS_POWER_PARAM)) != NULL) {
		struct gsm_power_ctrl_params *params = &lchan->ms_dpc_params;

		/* Parsed parameters will override per-TRX defaults */
		memcpy(params, ts->trx->ms_dpc_params, sizeof(*params));

		if (ie->len && parse_power_ctrl_params(params, ie->val, ie->len) != 0) {
			LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Failed to parse MS Power Parameters IE\n");
			return rsl_tx_chan_act_nack(lchan, RSL_ERR_IE_CONTENT);
		}

		/* Spec explicitly states BTS should only perform
		* autonomous MS power control loop in BTS if 'MS Power
		* Parameters' IE is present! */
		lchan->ms_power_ctrl.dpc_params = params;
	}

	/* 9.3.32 (TLV) BS Power Parameters IE (vendor specific) */
	if ((ie = TLVP_GET(&tp, RSL_IE_BS_POWER_PARAM)) != NULL) {
		struct gsm_power_ctrl_params *params = &lchan->bs_dpc_params;

		/* Parsed parameters will override per-TRX defaults */
		memcpy(params, ts->trx->bs_dpc_params, sizeof(*params));

		/* Parsed parameters will override per-TRX defaults */
		if (ie->len && parse_power_ctrl_params(params, ie->val, ie->len) != 0) {
			LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Failed to parse BS Power Parameters IE\n");
			return rsl_tx_chan_act_nack(lchan, RSL_ERR_IE_CONTENT);
		}

		/* NOTE: it's safer to start from 0 */
		lchan->bs_power_ctrl.current = 0;
		lchan->bs_power_ctrl.dpc_params = params;
	}

	/* 9.3.16 Physical Context */

	/* 9.3.29 SACCH Information */
	if (TLVP_PRESENT(&tp, RSL_IE_SACCH_INFO)) {
		uint8_t tot_len = TLVP_LEN(&tp, RSL_IE_SACCH_INFO);
		const uint8_t *val = TLVP_VAL(&tp, RSL_IE_SACCH_INFO);
		const uint8_t *cur = val;
		uint8_t num_msgs = *cur++;
		unsigned int i;
		for (i = 0; i < num_msgs; i++) {
			uint8_t rsl_si = *cur++;
			uint8_t si_len = *cur++;
			uint8_t osmo_si;

			if (!OSMO_IN_ARRAY(rsl_si, rsl_sacch_sitypes)) {
				rsl_tx_error_report(msg->trx, RSL_ERR_IE_CONTENT,
						    &dch->chan_nr, NULL, msg);
				return rsl_tx_chan_act_acknack(lchan, RSL_ERR_IE_CONTENT);
			}

			osmo_si = osmo_rsl2sitype(rsl_si);
			if (osmo_si == SYSINFO_TYPE_NONE) {
				LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "Rx SACCH SI 0x%02x not supported.\n", rsl_si);
				rsl_tx_error_report(msg->trx, RSL_ERR_IE_CONTENT, &dch->chan_nr,
						    NULL, msg);
				return rsl_tx_chan_act_acknack(lchan, RSL_ERR_IE_CONTENT);
			}

			lapdm_ui_prefix_lchan(lchan, cur, osmo_si, si_len);

			cur += si_len;
			if (cur > val + tot_len) {
				LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Error parsing SACCH INFO IE\n");
				rsl_tx_error_report(msg->trx, RSL_ERR_IE_CONTENT, &dch->chan_nr,
						    NULL, msg);
				return rsl_tx_chan_act_acknack(lchan, RSL_ERR_IE_CONTENT);
			}
		}
	} else {
		/* use standard SACCH filling of the BTS */
		copy_sacch_si_to_lchan(lchan);
	}
	/* 9.3.52 MultiRate Configuration */
	if (TLVP_PRESENT(&tp, RSL_IE_MR_CONFIG)) {
		rc = amr_parse_mr_conf(&lchan->tch.amr_mr,
				       TLVP_VAL(&tp, RSL_IE_MR_CONFIG),
				       TLVP_LEN(&tp, RSL_IE_MR_CONFIG));
		if (rc < 0) {
			LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Error parsing MultiRate conf IE\n");
			rsl_tx_error_report(msg->trx, RSL_ERR_IE_CONTENT, &dch->chan_nr, NULL, msg);
			return rsl_tx_chan_act_acknack(lchan, RSL_ERR_IE_CONTENT);
		}

		amr_log_mr_conf(DRTP, LOGL_DEBUG, gsm_lchan_name(lchan), &lchan->tch.amr_mr);
		lchan->tch.last_cmr = AMR_CMR_NONE;
	}
	/* 9.3.53 MultiRate Control */
	/* 9.3.54 Supported Codec Types */

	LOGPLCHAN(lchan, DRSL, LOGL_INFO, "chan_nr=%s type=0x%02x=%s mode=%s\n",
		  rsl_chan_nr_str(dch->chan_nr),
		  type, get_value_string(rsl_act_type_names, type),
		  gsm48_chan_mode_name(lchan->tch_mode));

	/* Connecting PDCH on dyn TS goes via PCU instead. */
	if (ts->pchan == GSM_PCHAN_OSMO_DYN
	    && ts->dyn.pchan_want == GSM_PCHAN_PDCH) {
		/*
		 * We ack the activation to the BSC right away, regardless of
		 * the PCU succeeding or not; if a dynamic timeslot fails to go
		 * to PDCH mode for any reason, the BSC should still be able to
		 * switch it back to TCH modes and should not put the time slot
		 * in an error state. So for operating dynamic TS, the BSC
		 * would not take any action if the PDCH mode failed, e.g.
		 * because the PCU is not yet running. Even if alerting the
		 * core network of broken GPRS service is desired, this only
		 * makes sense when the PCU has not shown up for some time.
		 * It's easiest to not forward activation delays to the BSC: if
		 * the BSC tells us to do PDCH, we do our best, and keep the
		 * details on the BTS and PCU level. This is kind of analogous
		 * to how plain PDCH TS operate. Directly call
		 * rsl_tx_chan_act_ack() instead of rsl_tx_chan_act_acknack()
		 * because we don't want/need to decide whether to drop due to
		 * lchan->rel_act_kind.
		 */
		rc = rsl_tx_chan_act_ack(lchan);
		if (rc < 0)
			LOGP(DRSL, LOGL_ERROR, "%s Cannot send act ack: %d\n",
			     gsm_ts_and_pchan_name(ts), rc);

		/*
		 * pcu_tx_info_ind() will pick up the ts->dyn.pchan_want. If
		 * the PCU is not connected yet, ignore for now; the PCU will
		 * catch up (and send the RSL ack) once it connects.
		 */
		if (pcu_connected()) {
			DEBUGP(DRSL, "%s Activate via PCU\n", gsm_ts_and_pchan_name(ts));
			rc = pcu_tx_info_ind();
		}
		else {
			DEBUGP(DRSL, "%s Activate via PCU when PCU connects\n",
			       gsm_ts_and_pchan_name(ts));
			rc = 0;
		}
		if (rc) {
			rsl_tx_error_report(msg->trx, RSL_ERR_NORMAL_UNSPEC, &dch->chan_nr, NULL, msg);
			return rsl_tx_chan_act_acknack(lchan, RSL_ERR_NORMAL_UNSPEC);
		}
		return 0;
	}

	/* Indicate which SAPIs should be enabled before the first RACH is received, for handover. See 3GPP TS 48.058
	 * 4.1.3 and 4.1.4.
	 *
	 *          |          | Access ||  transmit         |  activate         |  This implementation
	 *          | MS Power | Delay  ||  on main channel  |  dl SACCH         |  activates DL SACCH
	 * -----------------------------------------------------------------------------------------
	 * async ho   no         *     -->  yes                 no                  no
	 * async ho   yes        *     -->  yes                 may be started      no
	 * async ho   yes        yes   -->  yes                 may be started      yes
	 * sync ho    no         no    -->  yes                 no                  no
	 * sync ho    yes        no    -->  yes                 may be started      no
	 * sync ho    yes        yes   -->  yes                 shall be started    yes
	 */
	switch (type) {
	case RSL_ACT_INTER_ASYNC:
	case RSL_ACT_INTER_SYNC:
		lchan->want_dl_sacch_active = (TLVP_PRES_LEN(&tp, RSL_IE_MS_POWER, 1)
					       && TLVP_PRES_LEN(&tp, RSL_IE_ACCESS_DELAY, 1));
		break;
	default:
		lchan->want_dl_sacch_active = true;
		break;
	}

	/* Remember to send an RSL ACK once the lchan is active */
	lchan->rel_act_kind = LCHAN_REL_ACT_RSL;

	parse_repeated_acch_capability(lchan, &tp);

	/* actually activate the channel in the BTS */
	rc = l1sap_chan_act(lchan->ts->trx, dch->chan_nr, &tp);
	if (rc < 0)
		return rsl_tx_chan_act_acknack(lchan, -rc);

	return 0;
}

static int dyn_ts_pdch_release(struct gsm_lchan *lchan)
{
	struct gsm_bts_trx_ts *ts = lchan->ts;

	if (ts->dyn.pchan_is != ts->dyn.pchan_want) {
		LOGP(DRSL, LOGL_ERROR, "%s: PDCH release requested but already"
		     " in switchover\n", gsm_ts_and_pchan_name(ts));
		return -EINVAL;
	}

	/*
	 * Indicate PDCH Disconnect in dyn_pdch.want, let pcu_tx_info_ind()
	 * pick it up and wait for PCU to disable the channel.
	 */
	ts->dyn.pchan_want = GSM_PCHAN_NONE;

	if (!pcu_connected()) {
		/* PCU not connected yet. Just record the new type and done,
		 * the PCU will pick it up once connected. */
		ts->dyn.pchan_is = GSM_PCHAN_NONE;
		return 1;
	}

	return pcu_tx_info_ind();
}

/* 8.4.14 RF CHANnel RELease is received */
static int rsl_rx_rf_chan_rel(struct gsm_lchan *lchan, uint8_t chan_nr)
{
	int rc;

	if (lchan->state == LCHAN_S_NONE) {
		LOGP(DRSL, LOGL_ERROR,
		     "%s ss=%d state=%s Rx RSL RF Channel Release, but is already inactive;"
		     " just ACKing the release\n",
		     gsm_ts_and_pchan_name(lchan->ts), lchan->nr,
		     gsm_lchans_name(lchan->state));
		/* Just ack the release and ignore. Make sure to reflect the same chan_nr we received,
		 * not necessarily reflecting the current lchan state. */
		return tx_rf_rel_ack(lchan, chan_nr);
	}

	if (lchan->abis_ip.rtp_socket) {
		rsl_tx_ipac_dlcx_ind(lchan, RSL_ERR_NORMAL_UNSPEC);
		osmo_rtp_socket_log_stats(lchan->abis_ip.rtp_socket, DRTP, LOGL_INFO,
			"Closing RTP socket on Channel Release ");
		osmo_rtp_socket_free(lchan->abis_ip.rtp_socket);
		lchan->abis_ip.rtp_socket = NULL;
		msgb_queue_flush(&lchan->dl_tch_queue);
	}

	/* release handover state */
	handover_reset(lchan);

	lchan->rel_act_kind = LCHAN_REL_ACT_RSL;

	/* Dynamic channel in PDCH mode is released via PCU */
	if (lchan->ts->pchan == GSM_PCHAN_OSMO_DYN
	    && lchan->ts->dyn.pchan_is == GSM_PCHAN_PDCH) {
		rc = dyn_ts_pdch_release(lchan);
		if (rc == 1) {
			/* If the PCU is not connected, continue to rel ack right away. */
			lchan->rel_act_kind = LCHAN_REL_ACT_PCU;
			return rsl_tx_rf_rel_ack(lchan);
		}
		/* Waiting for PDCH release */
		return rc;
	}

	l1sap_chan_rel(lchan->ts->trx, chan_nr);

	lapdm_channel_exit(&lchan->lapdm_ch);

	return 0;
}

#ifdef FAKE_CIPH_MODE_COMPL
/* ugly hack to send a fake CIPH MODE COMPLETE back to the BSC */
#include <osmocom/gsm/protocol/gsm_04_08.h>
#include <osmocom/gsm/gsm48.h>
static int tx_ciph_mod_compl_hack(struct gsm_lchan *lchan, uint8_t link_id,
				  const char *imeisv)
{
	struct msgb *fake_msg;
	struct gsm48_hdr *g48h;
	uint8_t mid_buf[11];
	int rc;

	fake_msg = rsl_msgb_alloc(128);
	if (!fake_msg)
		return -ENOMEM;

	/* generate 04.08 RR message */
	g48h = (struct gsm48_hdr *) msgb_put(fake_msg, sizeof(*g48h));
	g48h->proto_discr = GSM48_PDISC_RR;
	g48h->msg_type = GSM48_MT_RR_CIPH_M_COMPL;

	/* add IMEISV, if requested */
	if (imeisv) {
		rc = gsm48_generate_mid_from_imsi(mid_buf, imeisv);
		if (rc > 0) {
			mid_buf[2] = (mid_buf[2] & 0xf8) | GSM_MI_TYPE_IMEISV;
			memcpy(msgb_put(fake_msg, rc), mid_buf, rc);
		}
	}

	rsl_rll_push_l3(fake_msg, RSL_MT_DATA_IND, gsm_lchan2chan_nr(lchan),
			link_id, 1);

	fake_msg->lchan = lchan;
	fake_msg->trx = lchan->ts->trx;

	/* send it back to the BTS */
	return abis_bts_rsl_sendmsg(fake_msg);
}

struct ciph_mod_compl {
	struct osmo_timer_list timer;
	struct gsm_lchan *lchan;
	int send_imeisv;
	uint8_t link_id;
};

static void cmc_timer_cb(void *data)
{
	struct ciph_mod_compl *cmc = data;
	const char *imeisv = NULL;

	LOGPLCHAN(cmc->lchan, DRSL, LOGL_NOTICE, "Sending FAKE CIPHERING MODE COMPLETE to BSC (Alg %u)\n",
		  cmc->lchan->encr.alg_id);

	if (cmc->send_imeisv)
		imeisv = "0123456789012345";

	/* We have no clue whatsoever that this lchan still exists! */
	tx_ciph_mod_compl_hack(cmc->lchan, cmc->link_id, imeisv);

	talloc_free(cmc);
}
#endif


/* 8.4.6 ENCRYPTION COMMAND */
static int rsl_rx_encr_cmd(struct msgb *msg)
{
	struct gsm_lchan *lchan = msg->lchan;
	struct abis_rsl_dchan_hdr *dch = msgb_l2(msg);
	struct tlv_parsed tp;
	uint8_t link_id;

	if (rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg)) < 0) {
		return rsl_tx_error_report(msg->trx, RSL_ERR_IE_CONTENT, &dch->chan_nr, NULL, msg);
	}

	if (!TLVP_PRESENT(&tp, RSL_IE_ENCR_INFO) ||
	    !TLVP_PRESENT(&tp, RSL_IE_L3_INFO) ||
	    !TLVP_PRESENT(&tp, RSL_IE_LINK_IDENT)) {
		return rsl_tx_error_report(msg->trx, RSL_ERR_MAND_IE_ERROR, &dch->chan_nr, NULL, msg);
	}

	/* 9.3.7 Encryption Information */
	if (TLVP_PRESENT(&tp, RSL_IE_ENCR_INFO)) {
		uint8_t len = TLVP_LEN(&tp, RSL_IE_ENCR_INFO);
		const uint8_t *val = TLVP_VAL(&tp, RSL_IE_ENCR_INFO);

		if (encr_info2lchan(lchan, val, len) < 0) {
			 return rsl_tx_error_report(msg->trx, RSL_ERR_IE_CONTENT, &dch->chan_nr,
					 	    NULL, msg);
		}
	}

	/* 9.3.2 Link Identifier */
	link_id = *TLVP_VAL(&tp, RSL_IE_LINK_IDENT);

	/* we have to set msg->l3h as rsl_rll_push_l3 will use it to
	 * determine the length field of the L3_INFO IE */
	msg->l3h = (uint8_t *) TLVP_VAL(&tp, RSL_IE_L3_INFO);

	/* pop the RSL dchan header, but keep L3 TLV */
	msgb_pull(msg, msg->l3h - msg->data);

	/* push a fake RLL DATA REQ header */
	rsl_rll_push_l3(msg, RSL_MT_DATA_REQ, dch->chan_nr, link_id, 1);


#ifdef FAKE_CIPH_MODE_COMPL
	if (lchan->encr.alg_id != RSL_ENC_ALG_A5(0)) {
		struct ciph_mod_compl *cmc;
		struct gsm48_hdr *g48h = (struct gsm48_hdr *) msg->l3h;

		cmc = talloc_zero(NULL, struct ciph_mod_compl);
		if (g48h->data[0] & 0x10)
			cmc->send_imeisv = 1;
		cmc->lchan = lchan;
		cmc->link_id = link_id;
		cmc->timer.cb = cmc_timer_cb;
		cmc->timer.data = cmc;
		osmo_timer_schedule(&cmc->timer, 1, 0);

		/* FIXME: send fake CM SERVICE ACCEPT to MS */

		return 0;
	} else
#endif
	{
	LOGPLCHAN(lchan, DRSL, LOGL_INFO, "Fwd RSL ENCR CMD (Alg %u) to LAPDm\n", lchan->encr.alg_id);
	/* hand it into RSLms for transmission of L3_INFO to the MS */
	lapdm_rslms_recvmsg(msg, &lchan->lapdm_ch);
	/* return 1 to make sure the msgb is not free'd */
	return 1;
	}
}

/* 8.4.11 MODE MODIFY NEGATIVE ACKNOWLEDGE */
static int _rsl_tx_mode_modif_nack(struct gsm_bts_trx *trx, uint8_t chan_nr, uint8_t cause,
				  struct gsm_lchan *lchan)
{
	struct msgb *msg;

	if (lchan)
		LOGP(DRSL, LOGL_NOTICE, "%s: ", gsm_lchan_name(lchan));
	else
		LOGP(DRSL, LOGL_NOTICE, "0x%02x: ", chan_nr);
	LOGPC(DRSL, LOGL_NOTICE, "Tx MODE MODIFY NACK (cause = 0x%02x)\n", cause);

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	msg->len = 0;
	msg->data = msg->tail = msg->l3h;

	/* 9.3.26 Cause */
	msgb_tlv_put(msg, RSL_IE_CAUSE, 1, &cause);
	rsl_dch_push_hdr(msg, RSL_MT_MODE_MODIFY_NACK, chan_nr);
	msg->trx = trx;

	return abis_bts_rsl_sendmsg(msg);
}
static int rsl_tx_mode_modif_nack(struct gsm_lchan *lchan, uint8_t cause)
{
	return _rsl_tx_mode_modif_nack(lchan->ts->trx, gsm_lchan2chan_nr(lchan), cause, lchan);
}


/* 8.4.10 MODE MODIFY ACK */
static int rsl_tx_mode_modif_ack(struct gsm_lchan *lchan)
{
	struct msgb *msg;
	uint8_t chan_nr = gsm_lchan2chan_nr(lchan);

	LOGPLCHAN(lchan, DRSL, LOGL_INFO, "Tx MODE MODIF ACK\n");

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	rsl_dch_push_hdr(msg, RSL_MT_MODE_MODIFY_ACK, chan_nr);
	msg->trx = lchan->ts->trx;

	return abis_bts_rsl_sendmsg(msg);
}

/* 8.4.9 MODE MODIFY */
static int rsl_rx_mode_modif(struct msgb *msg)
{
	struct abis_rsl_dchan_hdr *dch = msgb_l2(msg);
	struct gsm_lchan *lchan = msg->lchan;
	struct tlv_parsed tp;
	uint8_t cause;
	int rc;

	rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));

	/* 9.3.6 Channel Mode */
	if (rsl_handle_chan_mod_ie(lchan, &tp, &cause) != 0)
		return rsl_tx_mode_modif_nack(lchan, cause);
	/* 9.3.5 Channel Identification */
	if (rsl_handle_chan_ident_ie(lchan, &tp, &cause) != 0)
		return rsl_tx_mode_modif_nack(lchan, cause);
	/* Osmocom specific TSC IE for VAMOS */
	if (rsl_handle_osmo_tsc_ie(lchan, &tp, &cause) != 0)
		return rsl_tx_mode_modif_nack(lchan, cause);

	/* 9.3.7 Encryption Information */
	if (TLVP_PRESENT(&tp, RSL_IE_ENCR_INFO)) {
		uint8_t len = TLVP_LEN(&tp, RSL_IE_ENCR_INFO);
		const uint8_t *val = TLVP_VAL(&tp, RSL_IE_ENCR_INFO);

		if (encr_info2lchan(lchan, val, len) < 0) {
			rsl_tx_error_report(msg->trx, RSL_ERR_IE_CONTENT, &dch->chan_nr, NULL, msg);
			return rsl_tx_mode_modif_nack(lchan, RSL_ERR_ENCR_UNIMPL);
		}
	}

	/* 9.3.45 Main channel reference */

	/* 9.3.52 MultiRate Configuration */
	if (TLVP_PRESENT(&tp, RSL_IE_MR_CONFIG)) {
		rc = amr_parse_mr_conf(&lchan->tch.amr_mr,
				       TLVP_VAL(&tp, RSL_IE_MR_CONFIG),
				       TLVP_LEN(&tp, RSL_IE_MR_CONFIG));
		if (rc < 0) {
			LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Error parsing MultiRate conf IE\n");
			rsl_tx_error_report(msg->trx, RSL_ERR_IE_CONTENT, &dch->chan_nr, NULL, msg);
			return rsl_tx_mode_modif_nack(lchan, RSL_ERR_IE_CONTENT);;
		}

		amr_log_mr_conf(DRTP, LOGL_DEBUG, gsm_lchan_name(lchan), &lchan->tch.amr_mr);
		lchan->tch.last_cmr = AMR_CMR_NONE;
	}
	/* 9.3.53 MultiRate Control */
	/* 9.3.54 Supported Codec Types */

	parse_repeated_acch_capability(lchan, &tp);

	l1sap_chan_modify(lchan->ts->trx, dch->chan_nr);

	/* FIXME: delay this until L1 says OK? */
	rsl_tx_mode_modif_ack(lchan);

	return 0;
}

/* 8.4.15 MS POWER CONTROL */
static int rsl_rx_ms_pwr_ctrl(struct msgb *msg)
{
	struct abis_rsl_dchan_hdr *dch = msgb_l2(msg);
	struct gsm_lchan *lchan = msg->lchan;
	struct gsm_bts *bts = lchan->ts->trx->bts;
	const struct tlv_p_entry *ie;
	struct tlv_parsed tp;
	uint8_t pwr;
	int max_pwr, curr_pwr;

	rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));

	/* 9.3.13 MS Power (M) */
	if (!TLVP_PRES_LEN(&tp, RSL_IE_MS_POWER, 1))
		return rsl_tx_error_report(msg->trx, RSL_ERR_MAND_IE_ERROR, &dch->chan_nr, NULL, msg);

	pwr = *TLVP_VAL(&tp, RSL_IE_MS_POWER) & 0x1F;
	lchan->ms_power_ctrl.max = pwr;

	LOGPLCHAN(lchan, DRSL, LOGL_INFO, "Rx MS POWER CONTROL %" PRIu8 "\n", pwr);

	/* Spec explicitly states BTS should only perform autonomous MS Power
	 * control loop in BTS if 'MS Power Parameters' IE is present! */
	lchan->ms_power_ctrl.dpc_params = NULL;

	/* 9.3.31 (TLV) MS Power Parameters IE (vendor specific) */
	if ((ie = TLVP_GET(&tp, RSL_IE_MS_POWER_PARAM)) != NULL) {
		struct gsm_power_ctrl_params *params = &lchan->ms_dpc_params;

		/* Parsed parameters will override per-TRX defaults */
		memcpy(params, msg->trx->ms_dpc_params, sizeof(*params));

		/* Parsed parameters will override per-TRX defaults */
		if (ie->len && parse_power_ctrl_params(params, ie->val, ie->len) != 0) {
			LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Failed to parse MS Power Parameters IE\n");
			return rsl_tx_chan_act_nack(lchan, RSL_ERR_IE_CONTENT);
		}

		lchan->ms_power_ctrl.dpc_params = params;
	}

	/* Only set current to max if actual value of current
	   in dBm > value in dBm from max, or if fixed. */
	if (lchan->ms_power_ctrl.dpc_params == NULL) {
		lchan->ms_power_ctrl.current = lchan->ms_power_ctrl.max;
	} else {
		max_pwr = ms_pwr_dbm(bts->band, lchan->ms_power_ctrl.max);
		curr_pwr = ms_pwr_dbm(bts->band, lchan->ms_power_ctrl.current);
		if (max_pwr < 0 || curr_pwr < 0) {
			LOGPLCHAN(lchan, DRSL, LOGL_ERROR,
				  "Unable to calculate power levels to dBm: %" PRIu8 " -> %d, %" PRIu8 " -> %d\n",
				  lchan->ms_power_ctrl.max, max_pwr,
				  lchan->ms_power_ctrl.current, curr_pwr);
		} else if (curr_pwr > max_pwr) {
			lchan->ms_power_ctrl.current = lchan->ms_power_ctrl.max;
		}
	}

	bts_model_adjst_ms_pwr(lchan);

	return 0;
}

/* 8.4.16 BS POWER CONTROL */
static int rsl_rx_bs_pwr_ctrl(struct msgb *msg)
{
	struct abis_rsl_dchan_hdr *dch = msgb_l2(msg);
	struct gsm_lchan *lchan = msg->lchan;
	struct gsm_bts_trx *trx = msg->trx;
	const struct tlv_p_entry *ie;
	struct tlv_parsed tp;
	uint8_t old, new;

	rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));

	/* 9.3.4 BS Power (M) */
	if (!TLVP_PRES_LEN(&tp, RSL_IE_BS_POWER, 1))
		return rsl_tx_error_report(trx, RSL_ERR_MAND_IE_ERROR, &dch->chan_nr, NULL, msg);

	if (*TLVP_VAL(&tp, RSL_IE_BS_POWER) & (1 << 4)) {
		LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "Fast Power Control is not supported\n");
		return rsl_tx_error_report(trx, RSL_ERR_SERV_OPT_UNIMPL, &dch->chan_nr, NULL, msg);
	}

	new = BS_POWER2DB(*TLVP_VAL(&tp, RSL_IE_BS_POWER));
	old = lchan->bs_power_ctrl.current;

	/* Osmocom specific extension for BCCH carrier power reduction */
	if (dch->chan_nr == RSL_CHAN_BCCH) {
		int rc = bts_set_c0_pwr_red(trx->bts, new);
		if (rc != 0) {
			const uint8_t cause = (rc == -ENOTSUP) ?
				RSL_ERR_SERV_OPT_UNIMPL : RSL_ERR_IE_CONTENT;
			return rsl_tx_error_report(trx, cause, &dch->chan_nr, NULL, msg);
		}

		return 0;
	}

	/* BS power reduction is generally not allowed on BCCH/CCCH carrier.
	 * However, we allow it in the BCCH carrier power reduction operation.
	 * Constrain BS power value by the maximum reduction for this timeslot. */
	if (trx->bts->c0 == trx)
		new = OSMO_MIN(new, lchan->ts->c0_power_red_db);

	/* 9.3.32 (TLV) BS Power Parameters IE (vendor specific) */
	if ((ie = TLVP_GET(&tp, RSL_IE_BS_POWER_PARAM)) != NULL) {
		struct gsm_power_ctrl_params *params = &lchan->bs_dpc_params;

		/* Parsed parameters will override per-TRX defaults */
		memcpy(params, trx->bs_dpc_params, sizeof(*params));

		/* Parsed parameters will override per-TRX defaults */
		if (ie->len && parse_power_ctrl_params(params, ie->val, ie->len) != 0) {
			LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Failed to parse BS Power Parameters IE\n");
			return rsl_tx_chan_act_nack(lchan, RSL_ERR_IE_CONTENT);
		}

		/* NOTE: it's safer to start from 0 */
		lchan->bs_power_ctrl.current = 0;
		lchan->bs_power_ctrl.max = new;
		lchan->bs_power_ctrl.dpc_params = params;
	} else {
		lchan->bs_power_ctrl.dpc_params = NULL;
		lchan->bs_power_ctrl.current = new;
	}

	if (lchan->bs_power_ctrl.current != old) {
		LOGPLCHAN(lchan, DRSL, LOGL_INFO, "BS POWER CONTROL: "
			  "attenuation change %u -> %u dB\n",
			  old, lchan->bs_power_ctrl.current);
	}

	return 0;
}


/* 8.4.20 SACCH INFO MODify */
static int rsl_rx_sacch_inf_mod(struct msgb *msg)
{
	struct abis_rsl_dchan_hdr *dch = msgb_l2(msg);
	struct gsm_lchan *lchan = msg->lchan;
	struct gsm_bts *bts = lchan->ts->trx->bts;
	struct tlv_parsed tp;
	uint8_t rsl_si, osmo_si;

	rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));

	if (TLVP_PRESENT(&tp, RSL_IE_STARTNG_TIME)) {
		LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "Starting time not supported\n");
		return rsl_tx_error_report(msg->trx, RSL_ERR_SERV_OPT_UNIMPL, &dch->chan_nr, NULL, msg);
	}

	/* 9.3.30 System Info Type */
	if (!TLVP_PRESENT(&tp, RSL_IE_SYSINFO_TYPE))
		return rsl_tx_error_report(msg->trx, RSL_ERR_MAND_IE_ERROR, &dch->chan_nr, NULL, msg);

	rsl_si = *TLVP_VAL(&tp, RSL_IE_SYSINFO_TYPE);
	if (!OSMO_IN_ARRAY(rsl_si, rsl_sacch_sitypes))
		return rsl_tx_error_report(msg->trx, RSL_ERR_IE_CONTENT, &dch->chan_nr, NULL, msg);

	osmo_si = osmo_rsl2sitype(rsl_si);
	if (osmo_si == SYSINFO_TYPE_NONE) {
		LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "Rx SACCH SI 0x%02x not supported.\n", rsl_si);
		return rsl_tx_error_report(msg->trx, RSL_ERR_IE_CONTENT, &dch->chan_nr, NULL, msg);
	}
	if (TLVP_PRESENT(&tp, RSL_IE_L3_INFO)) {
		uint16_t len = TLVP_LEN(&tp, RSL_IE_L3_INFO);

		lapdm_ui_prefix_lchan(lchan, TLVP_VAL(&tp, RSL_IE_L3_INFO), osmo_si, len);
		if (memcmp(GSM_BTS_SI(bts, osmo_si), TLVP_VAL(&tp, RSL_IE_L3_INFO), sizeof(sysinfo_buf_t)) != 0)
			lchan->si.overridden |= (1 << osmo_si);
		else
			lchan->si.overridden &= ~(1 << osmo_si);

		LOGPLCHAN(lchan, DRSL, LOGL_INFO, "Rx RSL SACCH FILLING (SI%s)\n",
			  get_value_string(osmo_sitype_strs, osmo_si));
	} else {
		lchan->si.valid &= ~(1 << osmo_si);
		LOGPLCHAN(lchan, DRSL, LOGL_INFO, "Rx RSL Disabling SACCH FILLING (SI%s)\n",
			  get_value_string(osmo_sitype_strs, osmo_si));
	}

	return 0;
}

/* 8.5.8 CBCH Load Information */
int rsl_tx_cbch_load_indication(struct gsm_bts *bts, bool ext_cbch, bool overflow, uint8_t amount)
{
	struct gsm_lchan *lchan;
	struct msgb *msg;
	uint8_t load_info;

	lchan = gsm_bts_get_cbch(bts);
	if (!lchan)
		return -ENODEV;

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_cchan_hdr));
	if (!msg)
		return -ENOMEM;

	/* 9.3.1 Channel Number */
	rsl_cch_push_hdr(msg, RSL_MT_CBCH_LOAD_IND, gsm_lchan2chan_nr(lchan));

	/* 9.3.43 CBCH Load Information */
	load_info = ((overflow & 1) << 7) | (amount & 0x0F);
	msgb_tv_put(msg, RSL_IE_CBCH_LOAD_INFO, load_info);
	/* 9.3.44 SMSCB Channel Indicator */
	if (ext_cbch)
		msgb_tv_put(msg, RSL_IE_SMSCB_CHAN_INDICATOR, 0x01);

	msg->trx = bts->c0;

	return abis_bts_rsl_sendmsg(msg);
}

/*
 * ip.access related messages
 */
static void rsl_add_rtp_stats(struct gsm_lchan *lchan, struct msgb *msg)
{
	uint32_t packets_sent, octets_sent;
	uint32_t packets_recv, octets_recv;
	uint32_t packets_lost;
	uint32_t arrival_jitter;

	msgb_tv_put(msg, RSL_IE_IPAC_CONN_STAT, sizeof(uint32_t) * 7);

	if (lchan->abis_ip.rtp_socket) {
		osmo_rtp_socket_stats(lchan->abis_ip.rtp_socket,
				      &packets_sent, &octets_sent,
				      &packets_recv, &octets_recv,
				      &packets_lost, &arrival_jitter);

		/* msgb_put_u32() uses osmo_store32be(),
		 * so we don't need to call htonl(). */
		msgb_put_u32(msg, packets_sent);
		msgb_put_u32(msg, octets_sent);
		msgb_put_u32(msg, packets_recv);
		msgb_put_u32(msg, octets_recv);
		msgb_put_u32(msg, packets_lost);
		msgb_put_u32(msg, arrival_jitter);
		/* FIXME: AVG Tx delay is always 0 */
		msgb_put_u32(msg, 0);
	} else {
		msgb_put(msg, sizeof(uint32_t) * 7);
		memset(msg->tail, 0x00, sizeof(uint32_t) * 7);
	}
}

int rsl_tx_ipac_dlcx_ind(struct gsm_lchan *lchan, uint8_t cause)
{
	struct msgb *nmsg;

	LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "Sending RTP delete indication: cause = %s\n",
		  rsl_err_name(cause));

	nmsg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!nmsg)
		return -ENOMEM;

	msgb_tv16_put(nmsg, RSL_IE_IPAC_CONN_ID, htons(lchan->abis_ip.conn_id));
	rsl_add_rtp_stats(lchan, nmsg);
	msgb_tlv_put(nmsg, RSL_IE_CAUSE, 1, &cause);
	rsl_ipa_push_hdr(nmsg, RSL_MT_IPAC_DLCX_IND, gsm_lchan2chan_nr(lchan));

	nmsg->trx = lchan->ts->trx;

	return abis_bts_rsl_sendmsg(nmsg);
}

/* transmit an CRCX ACK for the lchan */
static int rsl_tx_ipac_XXcx_ack(struct gsm_lchan *lchan, int inc_pt2,
				  uint8_t orig_msgt)
{
	struct msgb *msg;
	uint8_t chan_nr = gsm_lchan2chan_nr(lchan);
	const char *name;
	struct in_addr ia;

	if (orig_msgt == RSL_MT_IPAC_CRCX)
		name = "CRCX";
	else
		name = "MDCX";

	ia.s_addr = htonl(lchan->abis_ip.bound_ip);
	LOGPLCHAN(lchan, DRSL, LOGL_INFO, "RSL Tx IPAC_%s_ACK (local %s:%u, ",
		  name, inet_ntoa(ia), lchan->abis_ip.bound_port);
	ia.s_addr = htonl(lchan->abis_ip.connect_ip);
	LOGPC(DRSL, LOGL_INFO, "remote %s:%u)\n",
		inet_ntoa(ia), lchan->abis_ip.connect_port);

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;


	/* Connection ID */
	msgb_tv16_put(msg, RSL_IE_IPAC_CONN_ID, htons(lchan->abis_ip.conn_id));

	/* locally bound IP */
	msgb_v_put(msg, RSL_IE_IPAC_LOCAL_IP);
	msgb_put_u32(msg, lchan->abis_ip.bound_ip);

	/* locally bound port */
	msgb_tv16_put(msg, RSL_IE_IPAC_LOCAL_PORT,
		      lchan->abis_ip.bound_port);

	if (inc_pt2) {
		/* RTP Payload Type 2 */
		msgb_tv_put(msg, RSL_IE_IPAC_RTP_PAYLOAD2,
					lchan->abis_ip.rtp_payload2);
	}

	/* push the header in front */
	rsl_ipa_push_hdr(msg, orig_msgt + 1, chan_nr);
	msg->trx = lchan->ts->trx;

	return abis_bts_rsl_sendmsg(msg);
}

static int rsl_tx_ipac_dlcx_ack(struct gsm_lchan *lchan, int inc_conn_id)
{
	struct msgb *msg;
	uint8_t chan_nr = gsm_lchan2chan_nr(lchan);

	LOGPLCHAN(lchan, DRSL, LOGL_INFO, "RSL Tx IPAC_DLCX_ACK\n");

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	if (inc_conn_id) {
		msgb_tv16_put(msg, RSL_IE_IPAC_CONN_ID, lchan->abis_ip.conn_id);
		rsl_add_rtp_stats(lchan, msg);
	}

	rsl_ipa_push_hdr(msg, RSL_MT_IPAC_DLCX_ACK, chan_nr);
	msg->trx = lchan->ts->trx;

	return abis_bts_rsl_sendmsg(msg);
}

static int rsl_tx_ipac_dlcx_nack(struct gsm_lchan *lchan, int inc_conn_id,
				 uint8_t cause)
{
	struct msgb *msg;
	uint8_t chan_nr = gsm_lchan2chan_nr(lchan);

	LOGPLCHAN(lchan, DRSL, LOGL_INFO, "RSL Tx IPAC_DLCX_NACK\n");

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	if (inc_conn_id)
		msgb_tv_put(msg, RSL_IE_IPAC_CONN_ID, lchan->abis_ip.conn_id);

	msgb_tlv_put(msg, RSL_IE_CAUSE, 1, &cause);

	rsl_ipa_push_hdr(msg, RSL_MT_IPAC_DLCX_NACK, chan_nr);
	msg->trx = lchan->ts->trx;

	return abis_bts_rsl_sendmsg(msg);

}


/* transmit an CRCX NACK for the lchan */
static int tx_ipac_XXcx_nack(struct gsm_lchan *lchan, uint8_t cause,
			     int inc_ipport, uint8_t orig_msgtype)
{
	struct msgb *msg;
	uint8_t chan_nr = gsm_lchan2chan_nr(lchan);

	/* FIXME: allocate new msgb and copy old over */
	LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "RSL Tx IPAC_BIND_NACK\n");

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	if (inc_ipport) {
		/* remote IP */
		msgb_v_put(msg, RSL_IE_IPAC_REMOTE_IP);
		msgb_put_u32(msg, lchan->abis_ip.connect_ip);

		/* remote port */
		msgb_tv16_put(msg, RSL_IE_IPAC_REMOTE_PORT,
				htons(lchan->abis_ip.connect_port));
	}

	/* 9.3.26 Cause */
	msgb_tlv_put(msg, RSL_IE_CAUSE, 1, &cause);

	/* push the header in front */
	rsl_ipa_push_hdr(msg, orig_msgtype + 2, chan_nr);
	msg->trx = lchan->ts->trx;

	return abis_bts_rsl_sendmsg(msg);
}

static char *get_rsl_local_ip(struct gsm_bts_trx *trx)
{
	struct e1inp_ts *ts = trx->rsl_link->ts;
	struct sockaddr_storage ss;
	socklen_t sa_len = sizeof(ss);
	static char hostbuf[256];
	int rc;

	rc = getsockname(ts->driver.ipaccess.fd.fd, (struct sockaddr *) &ss,
			 &sa_len);
	if (rc < 0)
		return NULL;

	rc = getnameinfo((struct sockaddr *)&ss, sa_len,
			 hostbuf, sizeof(hostbuf), NULL, 0,
			 NI_NUMERICHOST);
	if (rc < 0)
		return NULL;

	return hostbuf;
}

static int bind_rtp(struct gsm_bts *bts, struct osmo_rtp_socket *rs, const char *ip)
{
	int rc;
	unsigned int i;
	unsigned int tries;

	tries = (bts->rtp_port_range_end - bts->rtp_port_range_start) / 2;
	for (i = 0; i < tries; i++) {

		if (bts->rtp_port_range_next >= bts->rtp_port_range_end)
			bts->rtp_port_range_next = bts->rtp_port_range_start;

		rc = osmo_rtp_socket_bind(rs, ip, bts->rtp_port_range_next);

		bts->rtp_port_range_next += 2;

		if (rc != 0)
			continue;

		if (bts->rtp_ip_dscp != -1) {
			if (osmo_rtp_socket_set_dscp(rs, bts->rtp_ip_dscp))
				LOGP(DRSL, LOGL_ERROR, "failed to set DSCP=%i: %s\n",
					bts->rtp_ip_dscp, strerror(errno));
		}
		if (bts->rtp_priority != -1) {
			if (osmo_rtp_socket_set_priority(rs, bts->rtp_priority))
				LOGP(DRSL, LOGL_ERROR, "failed to set socket priority %d: %s\n",
					bts->rtp_priority, strerror(errno));
		}
		return 0;
	}

	return -1;
}

static int rsl_rx_ipac_XXcx(struct msgb *msg)
{
	struct abis_rsl_dchan_hdr *dch = msgb_l2(msg);
	struct tlv_parsed tp;
	struct gsm_lchan *lchan = msg->lchan;
	struct gsm_bts *bts = lchan->ts->trx->bts;
	const uint8_t *payload_type, *speech_mode, *payload_type2;
	uint32_t connect_ip = 0;
	uint16_t connect_port = 0;
	int rc, inc_ip_port = 0, port;
	char *name;
	struct in_addr ia;
	struct in_addr addr;

	if (dch->c.msg_type == RSL_MT_IPAC_CRCX)
		name = "CRCX";
	else
		name = "MDCX";

	/* check the kind of channel and reject */
	if (lchan->type != GSM_LCHAN_TCH_F && lchan->type != GSM_LCHAN_TCH_H)
		return tx_ipac_XXcx_nack(lchan, 0x52,
					 0, dch->c.msg_type);

	rc = rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));
	if (rc < 0)
		return tx_ipac_XXcx_nack(lchan, RSL_ERR_MAND_IE_ERROR,
					 0, dch->c.msg_type);

	LOGPLCHAN(lchan, DRSL, LOGL_DEBUG, "IPAC_%s: ", name);
	if (TLVP_PRES_LEN(&tp, RSL_IE_IPAC_REMOTE_IP, 4)) {
		connect_ip = tlvp_val32_unal(&tp, RSL_IE_IPAC_REMOTE_IP);
		addr.s_addr = connect_ip;
		LOGPC(DRSL, LOGL_DEBUG, "connect_ip=%s ", inet_ntoa(addr));
	}

	if (TLVP_PRES_LEN(&tp, RSL_IE_IPAC_REMOTE_PORT, 2)) {
		connect_port = tlvp_val16be(&tp, RSL_IE_IPAC_REMOTE_PORT);
		LOGPC(DRSL, LOGL_DEBUG, "connect_port=%u ", connect_port);
	}

	speech_mode = TLVP_VAL(&tp, RSL_IE_IPAC_SPEECH_MODE);
	if (speech_mode)
		LOGPC(DRSL, LOGL_DEBUG, "speech_mode=%u ", *speech_mode);

	payload_type = TLVP_VAL(&tp, RSL_IE_IPAC_RTP_PAYLOAD);
	if (payload_type)
		LOGPC(DRSL, LOGL_DEBUG, "payload_type=%u ", *payload_type);

	LOGPC(DRSL, LOGL_DEBUG, "\n");

	payload_type2 = TLVP_VAL(&tp, RSL_IE_IPAC_RTP_PAYLOAD2);

	if (dch->c.msg_type == RSL_MT_IPAC_CRCX && connect_ip && connect_port)
		inc_ip_port = 1;

	if (payload_type && payload_type2) {
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Rx RSL IPAC %s, "
			"RTP_PT and RTP_PT2 in same msg !?!\n", name);
		return tx_ipac_XXcx_nack(lchan, RSL_ERR_MAND_IE_ERROR,
					 inc_ip_port, dch->c.msg_type);
	}

	if (dch->c.msg_type == RSL_MT_IPAC_CRCX) {
		char cname[256+4];
		char *ipstr = NULL;
		if (lchan->abis_ip.rtp_socket) {
			LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Rx RSL IPAC CRCX, "
				  "but we already have socket!\n");
			return tx_ipac_XXcx_nack(lchan, RSL_ERR_RES_UNAVAIL,
						 inc_ip_port, dch->c.msg_type);
		}
		/* FIXME: select default value depending on speech_mode */
		//if (!payload_type)
		lchan->tch.last_fn = LCHAN_FN_DUMMY;
		lchan->abis_ip.rtp_socket = osmo_rtp_socket_create(lchan->ts->trx,
								OSMO_RTP_F_POLL);
		if (!lchan->abis_ip.rtp_socket) {
			LOGPLCHAN(lchan, DRTP, LOGL_ERROR, "IPAC Failed to create RTP/RTCP sockets\n");
			oml_tx_failure_event_rep(&lchan->ts->trx->mo,
						 NM_SEVER_MINOR, OSMO_EVT_CRIT_RTP_TOUT,
						 "%s IPAC Failed to create RTP/RTCP sockets",
						 gsm_lchan_name(lchan));
			return tx_ipac_XXcx_nack(lchan, RSL_ERR_RES_UNAVAIL,
						 inc_ip_port, dch->c.msg_type);
		}
		rc = osmo_rtp_socket_set_param(lchan->abis_ip.rtp_socket,
					       bts->rtp_jitter_adaptive ?
					       OSMO_RTP_P_JIT_ADAP :
					       OSMO_RTP_P_JITBUF,
					       bts->rtp_jitter_buf_ms);
		if (rc < 0)
			LOGPLCHAN(lchan, DRTP, LOGL_ERROR,
				  "IPAC Failed to set RTP socket parameters: %s\n", strerror(-rc));
		else
			LOGPLCHAN(lchan, DRTP, LOGL_INFO, "IPAC set RTP socket parameters: %d\n", rc);
		lchan->abis_ip.rtp_socket->priv = lchan;
		lchan->abis_ip.rtp_socket->rx_cb = &l1sap_rtp_rx_cb;

		if (connect_ip && connect_port) {
			/* if CRCX specifies a remote IP, we can bind()
			 * here to 0.0.0.0 and wait for the connect()
			 * below, after which the kernel will have
			 * selected the local IP address.  */
			ipstr = "0.0.0.0";
		} else {
			/* if CRCX does not specify a remote IP, we will
			 * not do any connect() below, and thus the
			 * local socket will remain bound to 0.0.0.0 -
			 * which however we cannot legitimately report
			 * back to the BSC in the CRCX_ACK */
			ipstr = get_rsl_local_ip(lchan->ts->trx);
		}
		rc = bind_rtp(bts, lchan->abis_ip.rtp_socket, ipstr);
		if (rc < 0) {
			LOGPLCHAN(lchan, DRTP, LOGL_ERROR, "IPAC Failed to bind RTP/RTCP sockets\n");
			oml_tx_failure_event_rep(&lchan->ts->trx->mo,
						 NM_SEVER_MINOR, OSMO_EVT_CRIT_RTP_TOUT,
						 "%s IPAC Failed to bind RTP/RTCP sockets",
						 gsm_lchan_name(lchan));
			osmo_rtp_socket_free(lchan->abis_ip.rtp_socket);
			lchan->abis_ip.rtp_socket = NULL;
			msgb_queue_flush(&lchan->dl_tch_queue);
			return tx_ipac_XXcx_nack(lchan, RSL_ERR_RES_UNAVAIL,
						 inc_ip_port, dch->c.msg_type);
		}
		/* Ensure RTCP SDES contains some useful information */
		snprintf(cname, sizeof(cname), "bts@%s", ipstr);
		osmo_rtp_set_source_desc(lchan->abis_ip.rtp_socket, cname,
					 gsm_lchan_name(lchan), NULL, NULL,
					 gsm_trx_unit_id(lchan->ts->trx),
					 "OsmoBTS-" PACKAGE_VERSION, NULL);
		/* FIXME: multiplex connection, BSC proxy */
	} else {
		/* MDCX */
		if (!lchan->abis_ip.rtp_socket) {
			LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "Rx RSL IPAC MDCX, "
				  "but we have no RTP socket!\n");
			return tx_ipac_XXcx_nack(lchan, RSL_ERR_RES_UNAVAIL,
						 inc_ip_port, dch->c.msg_type);
		}
	}


	/* Special rule: If connect_ip == 0.0.0.0, use RSL IP
	 * address */
	if (connect_ip == 0) {
		struct e1inp_sign_link *sign_link =
					lchan->ts->trx->rsl_link;

		ia.s_addr = htonl(get_signlink_remote_ip(sign_link));
	} else
		ia.s_addr = connect_ip;
	rc = osmo_rtp_socket_connect(lchan->abis_ip.rtp_socket,
				     inet_ntoa(ia), connect_port);
	if (rc < 0) {
		LOGPLCHAN(lchan, DRTP, LOGL_ERROR, "Failed to connect RTP/RTCP sockets\n");
		osmo_rtp_socket_free(lchan->abis_ip.rtp_socket);
		lchan->abis_ip.rtp_socket = NULL;
		msgb_queue_flush(&lchan->dl_tch_queue);
		return tx_ipac_XXcx_nack(lchan, RSL_ERR_RES_UNAVAIL,
					 inc_ip_port, dch->c.msg_type);
	}
	/* save IP address and port number */
	lchan->abis_ip.connect_ip = ntohl(ia.s_addr);
	lchan->abis_ip.connect_port = connect_port;

	rc = osmo_rtp_get_bound_ip_port(lchan->abis_ip.rtp_socket,
					&lchan->abis_ip.bound_ip,
					&port);
	if (rc < 0)
		LOGPLCHAN(lchan, DRTP, LOGL_ERROR, "IPAC cannot obtain locally bound IP/port: %d\n", rc);
	lchan->abis_ip.bound_port = port;

	/* Everything has succeeded, we can store new values in lchan */
	if (payload_type) {
		lchan->abis_ip.rtp_payload = *payload_type;
		if (lchan->abis_ip.rtp_socket)
			osmo_rtp_socket_set_pt(lchan->abis_ip.rtp_socket,
						*payload_type);
	}
	if (payload_type2) {
		lchan->abis_ip.rtp_payload2 = *payload_type2;
		if (lchan->abis_ip.rtp_socket)
			osmo_rtp_socket_set_pt(lchan->abis_ip.rtp_socket,
						*payload_type2);
	}
	if (speech_mode)
		lchan->abis_ip.speech_mode = *speech_mode;

	/* FIXME: CSD, jitterbuffer, compression */

	return rsl_tx_ipac_XXcx_ack(lchan, payload_type2 ? 1 : 0,
				    dch->c.msg_type);
}

static int rsl_rx_ipac_dlcx(struct msgb *msg)
{
	struct tlv_parsed tp;
	struct gsm_lchan *lchan = msg->lchan;
	int rc, inc_conn_id = 0;

	rc = rsl_tlv_parse(&tp, msgb_l3(msg), msgb_l3len(msg));
	if (rc < 0)
		return rsl_tx_ipac_dlcx_nack(lchan, 0, RSL_ERR_MAND_IE_ERROR);

	if (TLVP_PRESENT(&tp, RSL_IE_IPAC_CONN_ID))
		inc_conn_id = 1;

	rc = rsl_tx_ipac_dlcx_ack(lchan, inc_conn_id);
	if (lchan->abis_ip.rtp_socket) {
		osmo_rtp_socket_log_stats(lchan->abis_ip.rtp_socket, DRTP, LOGL_INFO,
					  "Closing RTP socket on DLCX ");
		osmo_rtp_socket_free(lchan->abis_ip.rtp_socket);
		lchan->abis_ip.rtp_socket = NULL;
		msgb_queue_flush(&lchan->dl_tch_queue);
	}
	return rc;
}

/*
 * dynamic TCH/F_PDCH related messages, originally ip.access specific but
 * reused for other BTS models (sysmo-bts, ...)
 */

/* PDCH ACT/DEACT ACKNOWLEDGE */
static int rsl_tx_dyn_pdch_ack(struct gsm_lchan *lchan, bool pdch_act)
{
	struct gsm_time *gtime = get_time(lchan->ts->trx->bts);
	uint8_t chan_nr = gsm_lchan2chan_nr(lchan);
	struct msgb *msg;
	uint8_t ie[2];

	LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "Tx PDCH %s ACK\n", pdch_act? "ACT" : "DEACT");

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	if (pdch_act) {
		gsm48_gen_starting_time(ie, gtime);
		msgb_tv_fixed_put(msg, RSL_IE_FRAME_NUMBER, 2, ie);
	}
	rsl_dch_push_hdr(msg,
			 pdch_act? RSL_MT_IPAC_PDCH_ACT_ACK
				 : RSL_MT_IPAC_PDCH_DEACT_ACK,
			 chan_nr);
	msg->lchan = lchan;
	msg->trx = lchan->ts->trx;

	return abis_bts_rsl_sendmsg(msg);
}

/* PDCH ACT/DEACT NEGATIVE ACKNOWLEDGE */
static int rsl_tx_dyn_pdch_nack(struct gsm_lchan *lchan, bool pdch_act,
				uint8_t cause)
{
	struct msgb *msg;
	uint8_t chan_nr = gsm_lchan2chan_nr(lchan);

	LOGPLCHAN(lchan, DRSL, LOGL_NOTICE, "Tx PDCH %s NACK (cause = 0x%02x)\n",
		  pdch_act ? "ACT" : "DEACT", cause);

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	msg->len = 0;
	msg->data = msg->tail = msg->l3h;

	/* 9.3.26 Cause */
	msgb_tlv_put(msg, RSL_IE_CAUSE, 1, &cause);
	rsl_dch_push_hdr(msg,
			 pdch_act? RSL_MT_IPAC_PDCH_ACT_NACK
				 : RSL_MT_IPAC_PDCH_DEACT_NACK,
			 chan_nr);
	msg->lchan = lchan;
	msg->trx = lchan->ts->trx;

	return abis_bts_rsl_sendmsg(msg);
}

/*
 * Starting point for dynamic PDCH switching. See osmo-gsm-manuals.git for a
 * diagram of what will happen here. The implementation is as follows:
 *
 * PDCH ACT == TCH/F -> PDCH:
 * 1. call bts_model_ts_disconnect() to disconnect TCH/F;
 * 2. cb_ts_disconnected() is called when done;
 * 3. call bts_model_ts_connect() to connect as PDTCH;
 * 4. cb_ts_connected(rc) is called when done;
 * 5. instruct the PCU to enable PDTCH;
 * 6. the PCU will call back with an activation request;
 * 7. l1sap_info_act_cnf() will call ipacc_dyn_pdch_complete() when SAPI
 *    activations are done;
 * 8. send a PDCH ACT ACK.
 *
 * PDCH DEACT == PDCH -> TCH/F:
 * 1. instruct the PCU to disable PDTCH;
 * 2. the PCU will call back with a deactivation request;
 * 3. l1sap_info_rel_cnf() will call bts_model_ts_disconnect() when SAPI
 *    deactivations are done;
 * 4. cb_ts_disconnected() is called when done;
 * 5. call bts_model_ts_connect() to connect as TCH/F;
 * 6. cb_ts_connected(rc) is called when done;
 * 7. directly call ipacc_dyn_pdch_complete(), since no further action required
 *    for TCH/F;
 * 8. send a PDCH DEACT ACK.
 *
 * When an error happens along the way, a PDCH DE/ACT NACK is sent.
 * TODO: may need to be made more waterproof in all stages, to send a NACK and
 * clear the PDCH pending flags from ts->flags.
 */
static void rsl_rx_dyn_pdch(struct msgb *msg, bool pdch_act)
{
	int rc;
	struct gsm_lchan *lchan = msg->lchan;
	struct gsm_bts_trx_ts *ts = lchan->ts;
	bool is_pdch_act = (ts->flags & TS_F_PDCH_ACTIVE);

	if (ts->flags & TS_F_PDCH_PENDING_MASK) {
		/* Only one of the pending flags should ever be set at the same
		 * time, but just log both in case both should be set. */
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR,
			  "Request to PDCH %s, but PDCH%s%s is still pending\n",
			  pdch_act? "ACT" : "DEACT",
			  (ts->flags & TS_F_PDCH_ACT_PENDING)? " ACT" : "",
			  (ts->flags & TS_F_PDCH_DEACT_PENDING)? " DEACT" : "");
		rsl_tx_dyn_pdch_nack(lchan, pdch_act, RSL_ERR_NORMAL_UNSPEC);
		return;
	}

	if (lchan->state != LCHAN_S_NONE) {
		LOGP(DRSL, LOGL_NOTICE,
		     "%s Request to PDCH %s, but lchan is still in state %s\n",
		     gsm_ts_and_pchan_name(ts), pdch_act? "ACT" : "DEACT",
		     gsm_lchans_name(lchan->state));
		/* TCH takes preference over PDCH so allow forcing PDCH DEACT,
		 * but forbid forcing PDCH ACT if lchan still active */
		if (pdch_act) {
			rsl_tx_dyn_pdch_nack(lchan, pdch_act, RSL_ERR_NORMAL_UNSPEC);
			return;
		}
	}

	ts->flags |= pdch_act? TS_F_PDCH_ACT_PENDING
			     : TS_F_PDCH_DEACT_PENDING;

	/* ensure that this is indeed a dynamic-PDCH channel */
	if (ts->pchan != GSM_PCHAN_TCH_F_PDCH) {
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR,
			  "Attempt to PDCH %s on TS that is not a TCH/F_PDCH (is %s)\n",
			  pdch_act? "ACT" : "DEACT", gsm_pchan_name(ts->pchan));
		ipacc_dyn_pdch_complete(ts, -EINVAL);
		return;
	}

	if (is_pdch_act == pdch_act) {
		LOGPLCHAN(lchan, DL1C, LOGL_NOTICE, "Request to PDCH %s, but is already so\n",
			  pdch_act? "ACT" : "DEACT");
		ipacc_dyn_pdch_complete(ts, 0);
		return;
	}

	if (pdch_act) {
		/* Clear TCH state. Only first lchan matters for PDCH */
		clear_lchan_for_pdch_activ(ts->lchan);

		/* First, disconnect the TCH channel, to connect PDTCH later */
		rc = bts_model_ts_disconnect(ts);
	} else {
		/* First, deactivate PDTCH through the PCU, to connect TCH
		 * later.
		 * pcu_tx_info_ind() will pick up TS_F_PDCH_DEACT_PENDING and
		 * trigger a deactivation.
		 * Except when the PCU is not connected yet, then trigger
		 * disconnect immediately from here. The PCU will catch up when
		 * it connects. */
		/* TODO: timeout on channel connect / disconnect request from PCU? */
		if (pcu_connected())
			rc = pcu_tx_info_ind();
		else
			rc = bts_model_ts_disconnect(ts);
	}

	/* Error? then NACK right now. */
	if (rc)
		ipacc_dyn_pdch_complete(ts, rc);
}

static void ipacc_dyn_pdch_ts_disconnected(struct gsm_bts_trx_ts *ts)
{
	int rc;
	enum gsm_phys_chan_config as_pchan;

	if (ts->flags & TS_F_PDCH_DEACT_PENDING) {
		LOGP(DRSL, LOGL_DEBUG,
		     "%s PDCH DEACT operation: channel disconnected, will reconnect as TCH\n",
		     gsm_lchan_name(ts->lchan));
		as_pchan = GSM_PCHAN_TCH_F;
	} else if (ts->flags & TS_F_PDCH_ACT_PENDING) {
		LOGP(DRSL, LOGL_DEBUG,
		     "%s PDCH ACT operation: channel disconnected, will reconnect as PDTCH\n",
		     gsm_lchan_name(ts->lchan));
		as_pchan = GSM_PCHAN_PDCH;
	} else
		/* No reconnect pending. */
		return;

	rc = conf_lchans_as_pchan(ts, as_pchan);
	if (rc)
		goto error_nack;

	bts_model_ts_connect(ts, as_pchan);
	return;

error_nack:
	/* Error? then NACK right now. */
	if (rc)
		ipacc_dyn_pdch_complete(ts, rc);
}

static void osmo_dyn_ts_disconnected(struct gsm_bts_trx_ts *ts)
{
	DEBUGP(DRSL, "%s Disconnected\n", gsm_ts_and_pchan_name(ts));
	ts->dyn.pchan_is = GSM_PCHAN_NONE;

	switch (ts->dyn.pchan_want) {
	case GSM_PCHAN_TCH_F:
	case GSM_PCHAN_TCH_H:
	case GSM_PCHAN_SDCCH8_SACCH8C:
	case GSM_PCHAN_PDCH:
		break;
	default:
		LOGP(DRSL, LOGL_ERROR,
		     "%s Dyn TS disconnected, but invalid desired pchan: %s\n",
		     gsm_ts_and_pchan_name(ts), gsm_pchan_name(ts->dyn.pchan_want));
		ts->dyn.pchan_want = GSM_PCHAN_NONE;
		/* TODO: how would this recover? */
		return;
	}

	conf_lchans_as_pchan(ts, ts->dyn.pchan_want);
	DEBUGP(DRSL, "%s Connect\n", gsm_ts_and_pchan_name(ts));
	bts_model_ts_connect(ts, ts->dyn.pchan_want);
}

void cb_ts_disconnected(struct gsm_bts_trx_ts *ts)
{
	OSMO_ASSERT(ts);

	switch (ts->pchan) {
	case GSM_PCHAN_TCH_F_PDCH:
		return ipacc_dyn_pdch_ts_disconnected(ts);
	case GSM_PCHAN_OSMO_DYN:
		return osmo_dyn_ts_disconnected(ts);
	default:
		return;
	}
}

static void ipacc_dyn_pdch_ts_connected(struct gsm_bts_trx_ts *ts, int rc)
{
	if (rc) {
		LOGP(DRSL, LOGL_NOTICE, "%s PDCH ACT IPA operation failed (%d) in bts model\n",
		     gsm_lchan_name(ts->lchan), rc);
		ipacc_dyn_pdch_complete(ts, rc);
		return;
	}

	if (ts->flags & TS_F_PDCH_DEACT_PENDING) {
		if (ts->lchan[0].type != GSM_LCHAN_TCH_F)
			LOGP(DRSL, LOGL_ERROR, "%s PDCH DEACT error:"
			     " timeslot connected, so expecting"
			     " lchan type TCH/F, but is %s\n",
			     gsm_lchan_name(ts->lchan),
			     gsm_lchant_name(ts->lchan[0].type));

		LOGP(DRSL, LOGL_DEBUG, "%s PDCH DEACT operation:"
		     " timeslot connected as TCH/F\n",
		     gsm_lchan_name(ts->lchan));

		/* During PDCH DEACT, we're done right after the TCH/F came
		 * back up. */
		ipacc_dyn_pdch_complete(ts, 0);

	} else if (ts->flags & TS_F_PDCH_ACT_PENDING) {
		if (ts->lchan[0].type != GSM_LCHAN_PDTCH)
			LOGP(DRSL, LOGL_ERROR, "%s PDCH ACT error:"
			     " timeslot connected, so expecting"
			     " lchan type PDTCH, but is %s\n",
			     gsm_lchan_name(ts->lchan),
			     gsm_lchant_name(ts->lchan[0].type));

		LOGP(DRSL, LOGL_DEBUG, "%s PDCH ACT operation:"
		     " timeslot connected as PDTCH\n",
		     gsm_lchan_name(ts->lchan));

		/* The PDTCH is connected, now tell the PCU about it. Except
		 * when the PCU is not connected (yet), then there's nothing
		 * left to do now. The PCU will catch up when it connects. */
		if (!pcu_connected()) {
			ipacc_dyn_pdch_complete(ts, 0);
			return;
		}

		/* The PCU will request to activate the PDTCH SAPIs, which,
		 * when done, will call back to ipacc_dyn_pdch_complete(). */
		/* TODO: timeout on channel connect / disconnect request from PCU? */
		rc = pcu_tx_info_ind();

		/* Error? then NACK right now. */
		if (rc)
			ipacc_dyn_pdch_complete(ts, rc);
	}
}

static void osmo_dyn_ts_connected(struct gsm_bts_trx_ts *ts, int rc)
{
	struct msgb *msg = ts->dyn.pending_chan_activ;
	ts->dyn.pending_chan_activ = NULL;

	if (rc) {
		LOGP(DRSL, LOGL_NOTICE, "%s PDCH ACT OSMO operation failed (%d) in bts model\n",
		     gsm_lchan_name(ts->lchan), rc);
		ipacc_dyn_pdch_complete(ts, rc);
		return;
	}

	if (!msg) {
		LOGP(DRSL, LOGL_ERROR,
		     "%s TS re-connected, but no chan activ msg pending\n",
		     gsm_ts_and_pchan_name(ts));
		return;
	}

	ts->dyn.pchan_is = ts->dyn.pchan_want;
	DEBUGP(DRSL, "%s Connected\n", gsm_ts_and_pchan_name(ts));

	/* continue where we left off before re-connecting the TS. */
	rc = rsl_rx_chan_activ(msg);
	if (rc != 1)
		msgb_free(msg);
}

void cb_ts_connected(struct gsm_bts_trx_ts *ts, int rc)
{
	OSMO_ASSERT(ts);

	switch (ts->pchan) {
	case GSM_PCHAN_TCH_F_PDCH:
		return ipacc_dyn_pdch_ts_connected(ts, rc);
	case GSM_PCHAN_OSMO_DYN:
		return osmo_dyn_ts_connected(ts, rc);
	default:
		return;
	}
}

void ipacc_dyn_pdch_complete(struct gsm_bts_trx_ts *ts, int rc)
{
	bool pdch_act;
	OSMO_ASSERT(ts);

	pdch_act = ts->flags & TS_F_PDCH_ACT_PENDING;

	if ((ts->flags & TS_F_PDCH_PENDING_MASK) == TS_F_PDCH_PENDING_MASK)
		LOGP(DRSL, LOGL_ERROR,
		     "%s Internal Error: both PDCH ACT and PDCH DEACT pending\n",
		     gsm_lchan_name(ts->lchan));

	ts->flags &= ~TS_F_PDCH_PENDING_MASK;

	if (rc != 0) {
		LOGP(DRSL, LOGL_ERROR,
		     "PDCH %s on dynamic TCH/F_PDCH returned error %d\n",
		     pdch_act? "ACT" : "DEACT", rc);
		rsl_tx_dyn_pdch_nack(ts->lchan, pdch_act, RSL_ERR_NORMAL_UNSPEC);
		return;
	}

	if (pdch_act)
		ts->flags |= TS_F_PDCH_ACTIVE;
	else
		ts->flags &= ~TS_F_PDCH_ACTIVE;
	DEBUGP(DRSL, "%s %s switched to %s mode (ts->flags == %x)\n",
	       gsm_lchan_name(ts->lchan), gsm_pchan_name(ts->pchan),
	       pdch_act? "PDCH" : "TCH/F", ts->flags);

	rc = rsl_tx_dyn_pdch_ack(ts->lchan, pdch_act);
	if (rc)
		LOGP(DRSL, LOGL_ERROR,
		     "Failed to transmit PDCH %s ACK, rc %d\n",
		     pdch_act? "ACT" : "DEACT", rc);
}

/* handle a message with an RSL CHAN_NR that is incompatible/unknown */
static int rsl_reject_unknown_lchan(struct msgb *msg)
{
	struct abis_rsl_common_hdr *rh = msgb_l2(msg);
	struct abis_rsl_dchan_hdr *dch;
	struct abis_rsl_cchan_hdr *cch;
	struct abis_rsl_rll_hdr *rllh;
	int rc;

	/* Handle GSM 08.58 7 Error Handling for the given input. This method will
	 * send either a CHANNEL ACTIVATION NACK, MODE MODIFY NACK or ERROR REPORT
	 * depending on the input of the method. */

	/* TS 48.058 Section 7 explains how to do error handling */
	switch (rh->msg_discr & 0xfe) {
	case ABIS_RSL_MDISC_IPACCESS:
		/* fall-through */
	case ABIS_RSL_MDISC_DED_CHAN:
		dch = msgb_l2(msg);
		switch (dch->c.msg_type) {
		case RSL_MT_CHAN_ACTIV:
			rc = _rsl_tx_chan_act_nack(msg->trx, dch->chan_nr,
						   RSL_ERR_MAND_IE_ERROR, NULL);
			break;
		case RSL_MT_MODE_MODIFY_REQ:
			rc = _rsl_tx_mode_modif_nack(msg->trx, dch->chan_nr,
						     RSL_ERR_MAND_IE_ERROR, NULL);
			break;
		default:
			rc = rsl_tx_error_report(msg->trx, RSL_ERR_MAND_IE_ERROR, &dch->chan_nr,
						 NULL, msg);
			break;
		}
		break;
	case ABIS_RSL_MDISC_RLL:
		rllh = msgb_l2(msg);
		/* ERROR REPORT */
		rc = rsl_tx_error_report(msg->trx, RSL_ERR_MAND_IE_ERROR,
					 &rllh->chan_nr, &rllh->link_id, msg);
		break;
	case ABIS_RSL_MDISC_COM_CHAN:
		cch = msgb_l2(msg);
		/* ERROR REPORT */
		rc = rsl_tx_error_report(msg->trx, RSL_ERR_MAND_IE_ERROR, &cch->chan_nr, NULL, msg);
		break;
	case ABIS_RSL_MDISC_TRX:
		/* fall-through */
	default:
		/* ERROR REPORT */
		rc = rsl_tx_error_report(msg->trx, RSL_ERR_MAND_IE_ERROR, NULL, NULL, msg);
	}

	msgb_free(msg);
	return rc;
}

/*
 * selecting message
 */

static int rsl_rx_rll(struct gsm_bts_trx *trx, struct msgb *msg)
{
	struct abis_rsl_rll_hdr *rh = msgb_l2(msg);
	struct abis_rsl_rll_hdr rh2;
	struct gsm_lchan *lchan;
	int rc;

	if (msgb_l2len(msg) < sizeof(*rh)) {
		LOGP(DRSL, LOGL_NOTICE, "RSL Radio Link Layer message too short\n");
		rsl_tx_error_report(trx, RSL_ERR_PROTO, &rh->chan_nr, &rh->link_id, msg);
		msgb_free(msg);
		return -EIO;
	}
	msg->l3h = (unsigned char *)rh + sizeof(*rh);

	if (!chan_nr_is_dchan(rh->chan_nr))
		return rsl_reject_unknown_lchan(msg);

	lchan = lchan_lookup(trx, rh->chan_nr, "RSL rx RLL: ");
	if (!lchan) {
		LOGP(DRLL, LOGL_NOTICE, "Rx RLL %s for unknown lchan\n",
		     rsl_msg_name(rh->c.msg_type));
		return rsl_reject_unknown_lchan(msg);
	}

	if (lchan->state != LCHAN_S_ACTIVE) {
		LOGPLCHAN(lchan, DRLL, LOGL_NOTICE, "Rx RLL %s for lchan which isn't active\n",
			rsl_msg_name(rh->c.msg_type));
		rsl_tx_error_report(trx, RSL_ERR_MSG_SEQ, &rh->chan_nr, &rh->link_id, msg);
		msgb_free(msg);
		return -1;
	}

	DEBUGP(DRLL, "%s Rx RLL %s Abis -> LAPDm\n", gsm_lchan_name(lchan),
		rsl_msg_name(rh->c.msg_type));

	/* make copy of RLL header, as the message will be free'd in case of erroneous return */
	rh2 = *rh;
	/* exception: RLL messages are _NOT_ freed as they are now
	 * owned by LAPDm which might have queued them */
	rc = lapdm_rslms_recvmsg(msg, &lchan->lapdm_ch);
	if (rc < 0)
		rsl_tx_error_report(trx, RSL_ERR_MSG_TYPE, &rh2.chan_nr, &rh2.link_id, NULL);
	return rc;
}

static inline int rsl_link_id_is_sacch(uint8_t link_id)
{
	if (link_id >> 6 == 1)
		return 1;
	else
		return 0;
}

static int rslms_get_rll_msg_type(struct msgb *msg)
{
	struct abis_rsl_common_hdr *rh = msgb_l2(msg);

	if ((rh->msg_discr & 0xfe) != ABIS_RSL_MDISC_RLL)
		return -1;

	return rh->msg_type;
}

static int rslms_get_rr_msg_type(struct msgb *msg, bool rllh_link_id_is_sacch)
{
	struct abis_rsl_common_hdr *rh = msgb_l2(msg);
	struct abis_rsl_rll_hdr *rllh;
	struct gsm48_hdr *gh;

	if ((rh->msg_discr & 0xfe) != ABIS_RSL_MDISC_RLL)
		return -1;


	rllh = msgb_l2(msg);
	if (rsl_link_id_is_sacch(rllh->link_id) != rllh_link_id_is_sacch)
		return -3;

	gh = msgb_l3(msg);
	if (gh->proto_discr != GSM48_PDISC_RR)
		return -4;

	return gh->msg_type;
}

static bool rslms_is_meas_rep(struct msgb *msg)
{
	int rll_msg_type = rslms_get_rll_msg_type(msg);
	int rr_msg_type;

	if (rll_msg_type != RSL_MT_UNIT_DATA_IND)
		return false;

	rr_msg_type = rslms_get_rr_msg_type(msg, 1);

	switch (rr_msg_type) {
	case GSM48_MT_RR_MEAS_REP:
	case GSM48_MT_RR_EXT_MEAS_REP:
		return true;
	}

	/* FIXME: this does not cover the Bter frame format and the associated
	 * short RR protocol descriptor for ENHANCED MEASUREMENT REPORT */

	return false;
}

static bool rslms_is_gprs_susp_req(struct msgb *msg)
{
	int rll_msg_type = rslms_get_rll_msg_type(msg);
	int rr_msg_type;

	if (rll_msg_type != RSL_MT_DATA_IND)
		return false;

	rr_msg_type = rslms_get_rr_msg_type(msg, false);

	return rr_msg_type == GSM48_MT_RR_GPRS_SUSP_REQ;
}

/* TS 44.018 9.1.13b GPRS suspension request */
static int handle_gprs_susp_req(struct msgb *msg)
{
	struct gsm48_hdr *gh = msgb_l3(msg);
	struct gsm48_gprs_susp_req *gsr;
	uint32_t tlli;
	int rc;

	if (!gh || msgb_l3len(msg) < sizeof(*gh)+sizeof(*gsr)) {
		LOGP(DRSL, LOGL_NOTICE, "%s Short GPRS SUSPEND REQ received, ignoring\n", gsm_lchan_name(msg->lchan));
		return -EINVAL;
	}

	gsr = (struct gsm48_gprs_susp_req *) gh->data;
	tlli = osmo_ntohl(gsr->tlli);

	LOGP(DRSL, LOGL_INFO, "%s Fwd GPRS SUSPEND REQ for TLLI=0x%08x to PCU\n",
		gsm_lchan_name(msg->lchan), tlli);
	rc = pcu_tx_susp_req(msg->lchan, tlli, gsr->ra_id, gsr->cause);

	msgb_free(msg);

	return rc;
}

static inline uint8_t ms_to2rsl(const struct gsm_lchan *lchan, const struct lapdm_entity *le)
{
	return (lchan->ms_t_offs >= 0) ? lchan->ms_t_offs : (lchan->p_offs - le->ta);
}

static inline bool ms_to_valid(const struct gsm_lchan *lchan)
{
	return (lchan->ms_t_offs >= 0) || (lchan->p_offs >= 0);
}

struct osmo_bts_supp_meas_info {
	int16_t toa256_mean;
	int16_t toa256_min;
	int16_t toa256_max;
	uint16_t toa256_std_dev;
} __attribute__((packed));

/* Compose and send 8.4.8 MEASUREMENT RESult via RSL */
int rsl_tx_meas_res(struct gsm_lchan *lchan, uint8_t *l3, int l3_len, const struct lapdm_entity *le)
{
	struct msgb *msg;
	uint8_t meas_res[16];
	uint8_t chan_nr = gsm_lchan2chan_nr(lchan);
	int res_valid = lchan->meas.flags & LC_UL_M_F_RES_VALID;
	struct gsm_bts *bts = lchan->ts->trx->bts;

	LOGPLCHAN(lchan, DRSL, LOGL_DEBUG, "chan_num:%u Tx MEAS RES valid(%d), flags(%02x)\n",
		  chan_nr, res_valid, lchan->meas.flags);

	if (!res_valid)
		return -EINPROGRESS;

	msg = rsl_msgb_alloc(sizeof(struct abis_rsl_dchan_hdr));
	if (!msg)
		return -ENOMEM;

	LOGPLCHAN(lchan, DRSL, LOGL_DEBUG,
	     "Send Meas RES: NUM:%u, RXLEV_FULL:%u, RXLEV_SUB:%u, RXQUAL_FULL:%u, RXQUAL_SUB:%u, MS_PWR:%u, UL_TA:%u, L3_LEN:%d, TimingOff:%u\n",
	     lchan->meas.res_nr,
	     lchan->meas.ul_res.full.rx_lev,
	     lchan->meas.ul_res.sub.rx_lev,
	     lchan->meas.ul_res.full.rx_qual,
	     lchan->meas.ul_res.sub.rx_qual,
	     lchan->meas.l1_info.ms_pwr,
	     lchan->meas.l1_info.ta, l3_len, ms_to2rsl(lchan, le) - MEAS_MAX_TIMING_ADVANCE);

	msgb_tv_put(msg, RSL_IE_MEAS_RES_NR, lchan->meas.res_nr++);
	size_t ie_len = gsm0858_rsl_ul_meas_enc(&lchan->meas.ul_res,
						lchan->tch.dtx.dl_active,
						meas_res);
	lchan->tch.dtx.dl_active = false;
	if (ie_len >= 3) {
		if (bts->supp_meas_toa256 && lchan->meas.flags & LC_UL_M_F_OSMO_EXT_VALID) {
			struct osmo_bts_supp_meas_info *smi;
			smi = (struct osmo_bts_supp_meas_info *) &meas_res[ie_len];
			ie_len += sizeof(struct osmo_bts_supp_meas_info);
			/* append signed 16bit value containing MS timing offset in 1/256th symbols
			 * in the vendor-specific "Supplementary Measurement Information" part of
			 * the uplink measurements IE.  The lchan->meas.ext members are the current
			 * offset *relative* to the TA which the MS has already applied.  As we want
			 * to know the total propagation time between MS and BTS, we need to add
			 * the actual TA value applied by the MS plus the respective toa256 value in
			 * 1/256 symbol periods. */
			int16_t ta256 = lchan->meas.l1_info.ta * 256;
			smi->toa256_mean = htons(ta256 + lchan->meas.ms_toa256);
			smi->toa256_min = htons(ta256 + lchan->meas.ext.toa256_min);
			smi->toa256_max = htons(ta256 + lchan->meas.ext.toa256_max);
			smi->toa256_std_dev = htons(lchan->meas.ext.toa256_std_dev);
			lchan->meas.flags &= ~LC_UL_M_F_OSMO_EXT_VALID;
		}
		msgb_tlv_put(msg, RSL_IE_UPLINK_MEAS, ie_len, meas_res);
		lchan->meas.flags &= ~LC_UL_M_F_RES_VALID;
	}
	msgb_tv_put(msg, RSL_IE_BS_POWER, lchan->bs_power_ctrl.current / 2);
	if (lchan->meas.flags & LC_UL_M_F_L1_VALID) {
		msgb_tv_fixed_put(msg, RSL_IE_L1_INFO, sizeof(lchan->meas.l1_info), (uint8_t*)&lchan->meas.l1_info);
		lchan->meas.flags &= ~LC_UL_M_F_L1_VALID;
	}

	if (l3 && l3_len > 0)
		msgb_tl16v_put(msg, RSL_IE_L3_INFO, l3_len, l3);
	if (ms_to_valid(lchan)) {
		if (l3 && l3_len > 0)
			msgb_tv_put(msg, RSL_IE_MS_TIMING_OFFSET, ms_to2rsl(lchan, le));
		lchan->ms_t_offs = -1;
		lchan->p_offs = -1;
	}

	rsl_dch_push_hdr(msg, RSL_MT_MEAS_RES, chan_nr);
	msg->trx = lchan->ts->trx;

	return abis_bts_rsl_sendmsg(msg);
}

/* call-back for LAPDm code, called when it wants to send msgs UP */
int lapdm_rll_tx_cb(struct msgb *msg, struct lapdm_entity *le, void *ctx)
{
	struct gsm_lchan *lchan = ctx;
	struct abis_rsl_common_hdr *rh;

	OSMO_ASSERT(msg);
	rh = msgb_l2(msg);

	if (lchan->state != LCHAN_S_ACTIVE) {
		LOGPLCHAN(lchan, DRSL, LOGL_ERROR, "(%s) is not active. Dropping message (len=%u): %s\n",
			  gsm_lchans_name(lchan->state), msgb_l2len(msg), msgb_hexdump_l2(msg));
		msgb_free(msg);
		return 0;
	}

	msg->trx = lchan->ts->trx;
	msg->lchan = lchan;

	/* check if this is a measurement report from SACCH which needs special
	 * processing before forwarding */
	if (rslms_is_meas_rep(msg)) {
		int rc;

		LOGPLCHAN(lchan, DRSL, LOGL_INFO, "Handing RLL msg %s from LAPDm to MEAS REP\n",
			  rsl_msg_name(rh->msg_type));

		/* REL_IND handling */
		if (rh->msg_type == RSL_MT_REL_IND &&
			(lchan->type == GSM_LCHAN_TCH_F || lchan->type == GSM_LCHAN_TCH_H)) {
			LOGPLCHAN(lchan, DRSL, LOGL_INFO,
				  "Scheduling %s to L3 in next associated TCH-RTS.ind\n",
				  rsl_msg_name(rh->msg_type));

			if(lchan->pending_rel_ind_msg) {
				LOGPLCHAN(lchan, DRSL, LOGL_INFO,
					  "Dropping pending release indication message\n");
				msgb_free(lchan->pending_rel_ind_msg);
			}

			lchan->pending_rel_ind_msg = msg;
			return 0;
		}

		repeated_dl_facch_active_decision(lchan, msgb_l3(msg), msgb_l3len(msg));
		rc = rsl_tx_meas_res(lchan, msgb_l3(msg), msgb_l3len(msg), le);
		msgb_free(msg);
		return rc;
	} else if (rslms_is_gprs_susp_req(msg)) {
		return handle_gprs_susp_req(msg);
	} else {
		LOGPLCHAN(lchan, DRSL, LOGL_INFO, "Fwd RLL msg %s from LAPDm to A-bis\n",
			  rsl_msg_name(rh->msg_type));

		return abis_bts_rsl_sendmsg(msg);
	}
}

static int rsl_rx_cchan(struct gsm_bts_trx *trx, struct msgb *msg)
{
	struct abis_rsl_cchan_hdr *cch = msgb_l2(msg);
	int ret = 0;

	if (msgb_l2len(msg) < sizeof(*cch)) {
		LOGP(DRSL, LOGL_NOTICE, "RSL Common Channel Management message too short\n");
		rsl_tx_error_report(trx, RSL_ERR_PROTO, NULL, NULL, msg);
		msgb_free(msg);
		return -EIO;
	}
	msg->l3h = (unsigned char *)cch + sizeof(*cch);

	/* normally we don't permit dedicated channels here ... */
	if (chan_nr_is_dchan(cch->chan_nr)) {
		/* ... however, CBCH is on a SDCCH, so we must permit it */
		if (cch->c.msg_type != RSL_MT_SMS_BC_CMD && cch->c.msg_type != RSL_MT_SMS_BC_REQ)
			return rsl_reject_unknown_lchan(msg);
	}

	msg->lchan = lchan_lookup(trx, cch->chan_nr, "RSL rx CCHAN: ");
	if (!msg->lchan) {
		LOGP(DRSL, LOGL_ERROR, "Rx RSL %s for unknown lchan\n",
			rsl_msg_name(cch->c.msg_type));
		return rsl_reject_unknown_lchan(msg);
	}

	LOGPLCHAN(msg->lchan, DRSL, LOGL_INFO, "Rx RSL %s\n", rsl_msg_name(cch->c.msg_type));

	switch (cch->c.msg_type) {
	case RSL_MT_BCCH_INFO:
		ret = rsl_rx_bcch_info(trx, msg);
		break;
	case RSL_MT_IMMEDIATE_ASSIGN_CMD:
		ret = rsl_rx_imm_ass(trx, msg);
		break;
	case RSL_MT_PAGING_CMD:
		ret = rsl_rx_paging_cmd(trx, msg);
		break;
	case RSL_MT_SMS_BC_CMD:
		ret = rsl_rx_sms_bcast_cmd(trx, msg);
		break;
	case RSL_MT_SMS_BC_REQ:
	case RSL_MT_NOT_CMD:
		LOGPLCHAN(msg->lchan, DRSL, LOGL_NOTICE, "unimplemented RSL cchan msg_type %s\n",
			  rsl_msg_name(cch->c.msg_type));
		rsl_tx_error_report(trx, RSL_ERR_MSG_TYPE, &cch->chan_nr, NULL, msg);
		break;
	case RSL_MT_OSMO_ETWS_CMD:
		ret = rsl_rx_osmo_etws_cmd(trx, msg);
		break;
	/* Osmocom specific extension for BCCH carrier power reduction */
	case RSL_MT_BS_POWER_CONTROL:
		ret = rsl_rx_bs_pwr_ctrl(msg);
		break;
	default:
		LOGPLCHAN(msg->lchan, DRSL, LOGL_NOTICE, "undefined RSL cchan msg_type 0x%02x\n",
			  cch->c.msg_type);
		rsl_tx_error_report(trx, RSL_ERR_MSG_TYPE, &cch->chan_nr, NULL, msg);
		ret = -EINVAL;
		break;
	}

	if (ret != 1)
		msgb_free(msg);

	return ret;
}

static int rsl_rx_dchan(struct gsm_bts_trx *trx, struct msgb *msg)
{
	struct abis_rsl_dchan_hdr *dch = msgb_l2(msg);
	int ret = 0;

	if (msgb_l2len(msg) < sizeof(*dch)) {
		LOGP(DRSL, LOGL_NOTICE, "RSL Dedicated Channel Management message too short\n");
		msgb_free(msg);
		return -EIO;
	}
	msg->l3h = (unsigned char *)dch + sizeof(*dch);

	if (!chan_nr_is_dchan(dch->chan_nr))
		return rsl_reject_unknown_lchan(msg);

	msg->lchan = lchan_lookup(trx, dch->chan_nr, "RSL rx DCHAN: ");
	if (!msg->lchan) {
		LOGP(DRSL, LOGL_ERROR, "Rx RSL %s for unknown lchan\n",
			rsl_or_ipac_msg_name(dch->c.msg_type));
		return rsl_reject_unknown_lchan(msg);
	}

	LOGP(DRSL, LOGL_INFO, "%s ss=%d Rx RSL %s\n",
	     gsm_ts_and_pchan_name(msg->lchan->ts), msg->lchan->nr,
	     rsl_or_ipac_msg_name(dch->c.msg_type));

	switch (dch->c.msg_type) {
	case RSL_MT_CHAN_ACTIV:
		ret = rsl_rx_chan_activ(msg);
		break;
	case RSL_MT_RF_CHAN_REL:
		ret = rsl_rx_rf_chan_rel(msg->lchan, dch->chan_nr);
		break;
	case RSL_MT_SACCH_INFO_MODIFY:
		ret = rsl_rx_sacch_inf_mod(msg);
		break;
	case RSL_MT_DEACTIVATE_SACCH:
		ret = l1sap_chan_deact_sacch(trx, dch->chan_nr);
		break;
	case RSL_MT_ENCR_CMD:
		ret = rsl_rx_encr_cmd(msg);
		break;
	case RSL_MT_MODE_MODIFY_REQ:
		ret = rsl_rx_mode_modif(msg);
		break;
	case RSL_MT_MS_POWER_CONTROL:
		ret = rsl_rx_ms_pwr_ctrl(msg);
		break;
	case RSL_MT_BS_POWER_CONTROL:
		ret = rsl_rx_bs_pwr_ctrl(msg);
		break;
	case RSL_MT_IPAC_PDCH_ACT:
	case RSL_MT_IPAC_PDCH_DEACT:
		rsl_rx_dyn_pdch(msg, dch->c.msg_type == RSL_MT_IPAC_PDCH_ACT);
		ret = 0;
		break;
	case RSL_MT_PHY_CONTEXT_REQ:
	case RSL_MT_PREPROC_CONFIG:
	case RSL_MT_RTD_REP:
	case RSL_MT_PRE_HANDO_NOTIF:
	case RSL_MT_MR_CODEC_MOD_REQ:
	case RSL_MT_TFO_MOD_REQ:
		LOGPLCHAN(msg->lchan, DRSL, LOGL_NOTICE, "unimplemented RSL dchan msg_type %s\n",
			  rsl_msg_name(dch->c.msg_type));
		rsl_tx_error_report(trx, RSL_ERR_MSG_TYPE, &dch->chan_nr, NULL, msg);
		break;
	default:
		LOGPLCHAN(msg->lchan, DRSL, LOGL_NOTICE, "undefined RSL dchan msg_type 0x%02x\n",
			  dch->c.msg_type);
		rsl_tx_error_report(trx, RSL_ERR_MSG_TYPE, &dch->chan_nr, NULL, msg);
		ret = -EINVAL;
	}

	if (ret != 1)
		msgb_free(msg);

	return ret;
}

static int rsl_rx_trx(struct gsm_bts_trx *trx, struct msgb *msg)
{
	struct abis_rsl_common_hdr *th = msgb_l2(msg);
	int ret = 0;

	if (msgb_l2len(msg) < sizeof(*th)) {
		LOGP(DRSL, LOGL_NOTICE, "RSL TRX message too short\n");
		rsl_tx_error_report(trx, RSL_ERR_PROTO, NULL, NULL, msg);
		msgb_free(msg);
		return -EIO;
	}
	msg->l3h = (unsigned char *)th + sizeof(*th);

	switch (th->msg_type) {
	case RSL_MT_SACCH_FILL:
		ret = rsl_rx_sacch_fill(trx, msg);
		break;
	case RSL_MT_IPAC_MEAS_PREPROC_DFT:
		ret = rsl_rx_meas_preproc_dft(trx, msg);
		break;
	default:
		LOGP(DRSL, LOGL_NOTICE, "undefined RSL TRX msg_type 0x%02x\n",
			th->msg_type);
		rsl_tx_error_report(trx, RSL_ERR_MSG_TYPE, NULL, NULL, msg);
		ret = -EINVAL;
	}

	if (ret != 1)
		msgb_free(msg);

	return ret;
}

static int rsl_rx_ipaccess(struct gsm_bts_trx *trx, struct msgb *msg)
{
	struct abis_rsl_dchan_hdr *dch = msgb_l2(msg);
	int ret = 0;

	if (msgb_l2len(msg) < sizeof(*dch)) {
		LOGP(DRSL, LOGL_NOTICE, "RSL ip.access message too short\n");
		rsl_tx_error_report(trx, RSL_ERR_PROTO, NULL, NULL, msg);
		msgb_free(msg);
		return -EIO;
	}
	msg->l3h = (unsigned char *)dch + sizeof(*dch);

	if (!chan_nr_is_dchan(dch->chan_nr))
		return rsl_reject_unknown_lchan(msg);

	msg->lchan = lchan_lookup(trx, dch->chan_nr, "RSL rx IPACC: ");
	if (!msg->lchan) {
		LOGP(DRSL, LOGL_ERROR, "Rx RSL %s for unknown lchan\n",
			rsl_msg_name(dch->c.msg_type));
		return rsl_reject_unknown_lchan(msg);
	}

	LOGPLCHAN(msg->lchan, DRSL, LOGL_INFO, "Rx RSL %s\n", rsl_ipac_msg_name(dch->c.msg_type));

	switch (dch->c.msg_type) {
	case RSL_MT_IPAC_CRCX:
	case RSL_MT_IPAC_MDCX:
		ret = rsl_rx_ipac_XXcx(msg);
		break;
	case RSL_MT_IPAC_DLCX:
		ret = rsl_rx_ipac_dlcx(msg);
		break;
	default:
		LOGPLCHAN(msg->lchan, DRSL, LOGL_NOTICE, "unsupported RSL ip.access msg_type 0x%02x\n",
			  dch->c.msg_type);
		rsl_tx_error_report(trx, RSL_ERR_MSG_TYPE, &dch->chan_nr, NULL, msg);
		ret = -EINVAL;
	}

	if (ret != 1)
		msgb_free(msg);
	return ret;
}

int lchan_deactivate(struct gsm_lchan *lchan)
{
	OSMO_ASSERT(lchan);

	lchan->ciph_state = 0;
	return bts_model_lchan_deactivate(lchan);
}

int down_rsl(struct gsm_bts_trx *trx, struct msgb *msg)
{
	struct abis_rsl_common_hdr *rslh;
	int ret = 0;

	OSMO_ASSERT(trx);
	OSMO_ASSERT(msg);

	rslh = msgb_l2(msg);

	if (msgb_l2len(msg) < sizeof(*rslh)) {
		LOGP(DRSL, LOGL_NOTICE, "RSL message too short\n");
		rsl_tx_error_report(trx, RSL_ERR_PROTO, NULL, NULL, msg);
		msgb_free(msg);
		return -EIO;
	}

	switch (rslh->msg_discr & 0xfe) {
	case ABIS_RSL_MDISC_RLL:
		ret = rsl_rx_rll(trx, msg);
		/* exception: RLL messages are _NOT_ freed as they are now
		 * owned by LAPDm which might have queued them */
		break;
	case ABIS_RSL_MDISC_COM_CHAN:
		ret = rsl_rx_cchan(trx, msg);
		break;
	case ABIS_RSL_MDISC_DED_CHAN:
		ret = rsl_rx_dchan(trx, msg);
		break;
	case ABIS_RSL_MDISC_TRX:
		ret = rsl_rx_trx(trx, msg);
		break;
	case ABIS_RSL_MDISC_IPACCESS:
		ret = rsl_rx_ipaccess(trx, msg);
		break;
	default:
		LOGP(DRSL, LOGL_NOTICE, "unknown RSL msg_discr 0x%02x\n",
			rslh->msg_discr);
		rsl_tx_error_report(trx, RSL_ERR_MSG_DISCR, NULL, NULL, msg);
		msgb_free(msg);
		ret = -EINVAL;
	}

	/* we don't free here, as rsl_rx{cchan,dchan,trx,ipaccess,rll} are
	 * responsible for owning the msg */

	return ret;
}