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

/* Integration Tests for OsmoBSC
 * (C) 2017-2018 by Harald Welte <laforge@gnumonks.org>
 * All rights reserved.
 *
 * Released under the terms of GNU General Public License, Version 2 or
 * (at your option) any later version.
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * This test suite tests OsmoBSC while emulating both multiple BTS + MS as
 * well as the MSC. See README for more details.
 *
 * There are test cases that run in so-called 'handler mode' and test cases
 * that run directly on top of the BSSAP and RSL CodecPorts.  The "handler mode"
 * tests abstract the multiplexing/demultiplexing of multiple SCCP connections
 * and/or RSL channels and are hence suitable for higher-level test cases, while
 * the "raw" tests directly on top of the CodecPorts are more suitable for lower-
 * level testing.
 */

friend module BSC_Tests_VAMOS;
friend module BSC_Tests_CBSP;

import from Misc_Helpers all;
import from General_Types all;
import from Osmocom_Types all;
import from GSM_Types all;
import from IPL4asp_Types all;

import from BSSAP_Types all;
import from RAN_Adapter all;
import from BSSAP_LE_Adapter all;
import from BSSAP_LE_CodecPort all;
import from BSSAP_LE_Types all;
import from BSSLAP_Types all;
import from BSSAP_CodecPort all;
import from BSSMAP_Templates all;
import from IPA_Emulation all;
import from IPA_CodecPort all;
import from IPA_Types all;
import from IPA_Testing all;
import from RSL_Types all;
import from RSL_Emulation all;
import from MGCP_Emulation all;
import from MGCP_Templates all;
import from MGCP_Types all;
import from MGCP_CodecPort all;

import from Osmocom_CTRL_Functions all;
import from Osmocom_CTRL_Types all;
import from Osmocom_CTRL_Adapter all;

import from StatsD_Types all;
import from StatsD_CodecPort all;
import from StatsD_CodecPort_CtrlFunct all;
import from StatsD_Checker all;

import from Osmocom_VTY_Functions all;
import from TELNETasp_PortType all;

import from MobileL3_CommonIE_Types all;
import from MobileL3_Types all;
import from MobileL3_RRM_Types all;
import from L3_Templates all;
import from GSM_RR_Types all;

import from SCCP_Templates all;
import from BSSMAP_Templates all;
import from BSSMAP_LE_Templates all;

import from SCCPasp_Types all;

import from GSM_SystemInformation all;
import from GSM_RestOctets all;
import from TCCConversion_Functions all;

const integer NUM_TRX := 4;
const integer NUM_BTS := 3;
const integer NUM_BTS_CFG := 4; /* we have 4 BTS in the osmo-bsc.cfg (for inter-BSC HO tests) but use only 3 */
const integer NUM_TRX_CFG := 1; /* we support up to 4 TRX per BTS, but have only 1 TRX per BTS in osmo-bsc.cfg */
const integer NUM_MSC := 3;
const float T3101_MAX := 12.0;

/* make sure to sync this with the osmo-bts.cfg you're using */
const integer NUM_TCHH_PER_BTS := 2;
const integer NUM_TCHF_PER_BTS := 4;
const integer NUM_SDCCH_PER_BTS := 3;

friend type record BtsTrxIdx {
	uint8_t bts,
	uint8_t trx
}

private type record BtsParams {
	integer trx_num,
	integer tsc
}

/* Default Training Sequence Code expected for bts[i]:
 * BTS 0 has BSIC 10 (and no explicit timeslot training_sequence_code config), so expecting TSC = (BSIC & 7) = 2.
 * BTS 1 has BSIC 11, TSC = (BSIC & 7) = 3.
 * BTS 2 has BSIC 12, TSC = (BSIC & 7) = 4.
 * BTS 2 has BSIC 12, TSC = (BSIC & 7) = 4.
 */
private const BtsParams c_BtsParams[NUM_BTS_CFG] := {
	/* BTS0 */ { trx_num := 1, tsc := 2 },
	/* BTS1 */ { trx_num := 1, tsc := 3 },
	/* BTS2 */ { trx_num := 4, tsc := 4 },
	/* BTS3 */ { trx_num := 1, tsc := 4 }
}

/* per-BTS state which we keep */
type record BTS_State {
	/* component reference to the IPA_Client component used for RSL */
	IPA_Client rsl
}

/* Default list of counters for an 'msc' entity. */
const CounterNameVals counternames_msc_mscpool := {
	{ "mscpool:subscr:new", 0 },
	{ "mscpool:subscr:known", 0 },
	{ "mscpool:subscr:reattach", 0 },
	{ "mscpool:subscr:attach_lost", 0 },
	{ "mscpool:subscr:paged", 0 }
};

/* List of global mscpool counters, not related to a specific 'msc' entity. */
const CounterNameVals counternames_bsc_mscpool := {
	{ "mscpool:subscr:no_msc", 0 }
};

/* Default list of counters for 'bsc' and 'bts' entities. */
const CounterNameVals counternames_bsc_bts_handover := {
	{ "assignment:attempted", 0 },
	{ "assignment:completed", 0 },
	{ "assignment:stopped", 0 },
	{ "assignment:no_channel", 0 },
	{ "assignment:timeout", 0 },
	{ "assignment:failed", 0 },
	{ "assignment:error", 0 },

	{ "handover:attempted", 0 },
	{ "handover:completed", 0 },
	{ "handover:stopped", 0 },
	{ "handover:no_channel", 0 },
	{ "handover:timeout", 0 },
	{ "handover:failed", 0 },
	{ "handover:error", 0 },

	{ "intra_cell_ho:attempted", 0 },
	{ "intra_cell_ho:completed", 0 },
	{ "intra_cell_ho:stopped", 0 },
	{ "intra_cell_ho:no_channel", 0 },
	{ "intra_cell_ho:timeout", 0 },
	{ "intra_cell_ho:failed", 0 },
	{ "intra_cell_ho:error", 0 },

	{ "intra_bsc_ho:attempted", 0 },
	{ "intra_bsc_ho:completed", 0 },
	{ "intra_bsc_ho:stopped", 0 },
	{ "intra_bsc_ho:no_channel", 0 },
	{ "intra_bsc_ho:timeout", 0 },
	{ "intra_bsc_ho:failed", 0 },
	{ "intra_bsc_ho:error", 0 },

	{ "interbsc_ho_out:attempted", 0 },
	{ "interbsc_ho_out:completed", 0 },
	{ "interbsc_ho_out:stopped", 0 },
	{ "interbsc_ho_out:timeout", 0 },
	{ "interbsc_ho_out:failed", 0 },
	{ "interbsc_ho_out:error", 0 },

	{ "interbsc_ho_in:attempted", 0 },
	{ "interbsc_ho_in:completed", 0 },
	{ "interbsc_ho_in:stopped", 0 },
	{ "interbsc_ho_in:no_channel", 0 },
	{ "interbsc_ho_in:timeout", 0 },
	{ "interbsc_ho_in:failed", 0 },
	{ "interbsc_ho_in:error", 0 }
};

const CounterNameVals counternames_bts_handover := {
	{ "incoming_intra_bsc_ho:attempted", 0 },
	{ "incoming_intra_bsc_ho:completed", 0 },
	{ "incoming_intra_bsc_ho:stopped", 0 },
	{ "incoming_intra_bsc_ho:no_channel", 0 },
	{ "incoming_intra_bsc_ho:timeout", 0 },
	{ "incoming_intra_bsc_ho:failed", 0 },
	{ "incoming_intra_bsc_ho:error", 0 }
};

/* Set of all System Information received during one RSL port's startup.
 * Note that some System Information may be sent on RSL, but lacking actual SI data, to indicate that the BTS should not
 * broadcast that SI type. That will be reflected as 'omit' here.
 */
type record SystemInformationConfig {
	SystemInformationType1 si1 optional,
	SystemInformationType2 si2 optional,
	SystemInformationType2bis si2bis optional,
	SystemInformationType2ter si2ter optional,
	SI2quaterRestOctetsList si2quater optional,
	SystemInformationType3 si3 optional,
	SystemInformationType4 si4 optional,
	SystemInformationType13 si13 optional,
	SystemInformationType5 si5 optional,
	SystemInformationType5bis si5bis optional,
	SystemInformationType5ter si5ter optional,
	SystemInformationType6 si6 optional
};

const SystemInformationConfig SystemInformationConfig_omit := {
	si1 := omit,
	si2 := omit,
	si2bis := omit,
	si2ter := omit,
	si2quater := omit,
	si3 := omit,
	si4 := omit,
	si13 := omit,
	si5 := omit,
	si5bis := omit,
	si5ter := omit,
	si6 := omit
};

/* tr_EUTRAN_CellDesc with defaults used in BSC_Tests.ttcn */
template EUTRAN_CellDesc tr_EUTRAN_CellDesc_default(template (present) uint16_t e_arfcn := ?,
						    template uint3_t meas_bw := 3)
:= tr_EUTRAN_CellDesc(e_arfcn := e_arfcn,
		      meas_bw_presence := '1'B,
		      meas_bw := meas_bw);

/* tr_EUTRAN_NeighbourCells with defaults used in BSC_Tests.ttcn */
template EUTRAN_NeighbourCells tr_EUTRAN_NeighbourCells_default(template (present) EUTRAN_CellDescs cell_desc_list := { tr_EUTRAN_CellDesc_default },
								template uint3_t prio := 3,
								template (present) uint5_t thresh_high := 20,
								template uint5_t thresh_low := 10,
								template uint5_t qrxlevmin := 22)
:= tr_EUTRAN_NeighbourCells(
	cell_desc_list := cell_desc_list,
	prio_presence := '1'B,
	prio := prio,
	thresh_high := thresh_high,
	thresh_low_presence := '1'B,
	thresh_low := thresh_low,
	qrxlevmin_presence := '1'B,
	qrxlevmin := qrxlevmin);

template SystemInformationConfig SystemInformationConfig_default := {
	si1 := {
	    cell_chan_desc := '8FB38000000000000000000000000000'O,
	    rach_control := {
		max_retrans := RACH_MAX_RETRANS_7,
		tx_integer := '1001'B,
		cell_barr_access := false,
		re_not_allowed := true,
		acc := '0000010000000000'B
	    },
	    rest_octets := ?
	},
	si2 := {
	    bcch_freq_list := '00000000000000000000000000000000'O,
	    ncc_permitted := '11111111'B,
	    rach_control := {
		max_retrans := RACH_MAX_RETRANS_7,
		tx_integer := '1001'B,
		cell_barr_access := false,
		re_not_allowed := true,
		acc := '0000010000000000'B
	    }
	},
	si2bis := omit,
	si2ter := {
	    extd_bcch_freq_list := '8E320000000000000000000000000800'O,
	    rest_octets := ?
	},
	si2quater := {
		tr_SI2quaterRestOctets_EUTRAN( repeated_neigh_cells := { tr_EUTRAN_NeighbourCells_default } )
	},
	si3 := {
	    cell_id := 0,
	    lai := {
		mcc_mnc := '001F01'H,
		lac := 1
	    },
	    ctrl_chan_desc := {
		msc_r99 := true,
		att := true,
		bs_ag_blks_res := 1,
		ccch_conf := CCHAN_DESC_1CCCH_COMBINED,
		si22ind := false,
		cbq3 := CBQ3_IU_MODE_NOT_SUPPORTED,
		spare := '00'B,
		bs_pa_mfrms := 3,
		t3212 := 30
	    },
	    cell_options := {
		dn_ind := false,
		pwrc := false,
		dtx := MS_SHALL_USE_UL_DTX,
		radio_link_tout_div4 := 7
	    },
	    cell_sel_par := {
		cell_resel_hyst_2dB := 2,
		ms_txpwr_max_cch := 7,
		acs := '0'B,
		neci := true,
		rxlev_access_min := 0
	    },
	    rach_control := {
		max_retrans := RACH_MAX_RETRANS_7,
		tx_integer := '1001'B,
		cell_barr_access := false,
		re_not_allowed := true,
		acc := '0000010000000000'B
	    },
	    rest_octets := {
		sel_params := {
		    presence := '0'B,
		    params := omit
		},
		pwr_offset := {
		    presence := '0'B,
		    offset := omit
		},
		si_2ter_ind := '1'B,
		early_cm_ind := '0'B,
		sched_where := {
		    presence := '0'B,
		    where := omit
		},
		gprs_ind := {
		    presence := '1'B,
		    ind := {
			ra_colour := 0,
			si13_pos := '0'B
		    }
		},
		umts_early_cm_ind := '1'B,
		si2_quater_ind := {
		    presence := '1'B,
		    ind := '0'B
		},
		iu_mode_ind := omit,
		si21_ind := {
		    presence := '0'B,
		    pos := omit
		}
	    }
	},
	si4 := {
	    lai := {
		mcc_mnc := '001F01'H,
		lac := 1
	    },
	    cell_sel_par := {
		cell_resel_hyst_2dB := 2,
		ms_txpwr_max_cch := 7,
		acs := '0'B,
		neci := true,
		rxlev_access_min := 0
	    },
	    rach_control := {
		max_retrans := RACH_MAX_RETRANS_7,
		tx_integer := '1001'B,
		cell_barr_access := false,
		re_not_allowed := true,
		acc := '0000010000000000'B
	    },
	    cbch_chan_desc := {
		iei := '64'O,
		v := {
		    chan_nr := {
			u := {
			sdcch4 := {
			    tag := '001'B,
			    sub_chan := 2
			}
			},
			tn := 0
		    },
		    tsc := 2,
		    h := false,
		    arfcn := 871,
		    maio_hsn := omit
		}
	    },
	    cbch_mobile_alloc := omit,
	    rest_octets := {
		sel_params := {
		    presence := '0'B,
		    params := omit
		},
		pwr_offset := {
		    presence := '0'B,
		    offset := omit
		},
		gprs_ind := {
		    presence := '1'B,
		    ind := {
			ra_colour := 0,
			si13_pos := '0'B
		    }
		},
		s_presence := '0'B,
		s := omit
	    }
	},
	si13 := {
		rest_octets := {
			presence := '1'B,
			bcch_change_mark := ?,
			si_change_field := '0000'B,
			presence2 := '0'B,
			si13_change_mark := omit,
			gprs_ma := omit,
			zero := '0'B, /* PBCCH not present in cell */
			rac := 0,
			spgc_ccch_sup := '0'B,
			priority_access_thr := '110'B,
			network_control_order := '00'B,
			gprs_cell_opts := {
				nmo := '01'B,
				t3168 := '011'B,
				t3192 := '010'B,
				drx_timer_max := '011'B,
				access_burst_type := '0'B,
				control_ack_type := '1'B,
				bs_cv_max := 15,
				pan_presence := '1'B,
				pan_dec  := 1,
				pan_inc  := 1,
				pan_max  := '111'B,
				ext_info_presence := ?,
				ext_info_length := *,
				ext_info := *
			},
			gprs_pwr_ctrl_params := {
				alpha := 0,
				t_avg_w := '10000'B,
				t_avg_t := '10000'B,
				pc_meas_chan := '0'B,
				n_avg_i := '1000'B
			}
		}
	},
	si5 := {
	    bcch_freq_list := '10000000000000000000000000000000'O
	},
	si5bis := omit,
	si5ter := {
	    extd_bcch_freq_list := '9E050020000000000000000000000000'O
	},
	si6 := {
	    cell_id := 0,
	    lai := {
		mcc_mnc := '001F01'H,
		lac := 1
	    },
	    cell_options := {
		dtx_ext := '1'B,
		pwrc := false,
		dtx := '01'B,
		radio_link_timeout := '0111'B
	    },
	    ncc_permitted := '11111111'B,
	    rest_octets := {
		pch_nch_info := ?,
		vbs_vgcs_options := ?,
		dtm_support := '0'B,
		rac := omit,
		max_lapdm := omit,
		band_ind := '0'B /* C0 ARFCN indicates 1800 band */
	    }
	}
    };


/* List of all the System Information received on all RSL ports */
type record of SystemInformationConfig SystemInformationConfig_list;

function f_sysinfo_dec_raw(inout SystemInformationConfig si, RSL_Message rsl)
{
	var RSL_IE_Body sysinfo_type_ie;
	var RSL_IE_SysinfoType si_type;
	var octetstring data;

	if (f_rsl_find_ie(rsl, RSL_IE_SYSINFO_TYPE, sysinfo_type_ie) == false) {
		setverdict(fail, "Cannot find RSL_IE_SYSINFO_TYPE");
		mtc.stop;
	}
	si_type := sysinfo_type_ie.sysinfo_type;

	if (rsl.msg_type == RSL_MT_BCCH_INFO) {
		var RSL_IE_Body bcch_ie;
		if (f_rsl_find_ie(rsl, RSL_IE_FULL_BCCH_INFO, bcch_ie)) {
			data := bcch_ie.other.payload;
		}
	} else if (rsl.msg_type == RSL_MT_SACCH_FILL) {
		var RSL_IE_Body l3_ie;
		if (f_rsl_find_ie(rsl, RSL_IE_L3_INFO, l3_ie)) {
			data := l3_ie.l3_info.payload;
		}
	} else {
		setverdict(fail, "Don't understand this System Information message");
		mtc.stop;
	}

	var boolean handled := false;

	if (rsl.msg_type == RSL_MT_BCCH_INFO) {
		handled := true;

		if (si_type == RSL_SYSTEM_INFO_1) {
			if (not isbound(data)) {
				si.si1 := omit;
			} else {
				si.si1 := dec_SystemInformation(data).payload.si1;
			}
		} else if (si_type == RSL_SYSTEM_INFO_2) {
			if (not isbound(data)) {
				si.si2 := omit;
			} else {
				si.si2 := dec_SystemInformation(data).payload.si2;
			}
		} else if (si_type == RSL_SYSTEM_INFO_2bis) {
			if (not isbound(data)) {
				si.si2bis := omit;
			} else {
				si.si2bis := dec_SystemInformation(data).payload.si2bis;
			}
		} else if (si_type == RSL_SYSTEM_INFO_2ter) {
			if (not isbound(data)) {
				si.si2ter := omit;
			} else {
				si.si2ter := dec_SystemInformation(data).payload.si2ter;
			}
		} else if (si_type == RSL_SYSTEM_INFO_2quater) {
			if (not isbound(data)) {
				si.si2quater := {};
			} else {
				var SystemInformationType2quater decoded := dec_SystemInformation(data).payload.si2quater;
				/* this is a *record* of SI2quaterRestOctets! (multiplexed) */
				si.si2quater[decoded.rest_octets.si2quater_index] := decoded.rest_octets;
			}
		} else if (si_type == RSL_SYSTEM_INFO_3) {
			if (not isbound(data)) {
				si.si3 := omit;
			} else {
				si.si3 := dec_SystemInformation(data).payload.si3;
			}
		} else if (si_type == RSL_SYSTEM_INFO_4) {
			if (not isbound(data)) {
				si.si4 := omit;
			} else {
				si.si4 := dec_SystemInformation(data).payload.si4;
			}
		} else if (si_type == RSL_SYSTEM_INFO_13) {
			if (not isbound(data)) {
				si.si13 := omit;
			} else {
				si.si13 := dec_SystemInformation(data).payload.si13;
			}
		} else {
			handled := false;
		}
	} else if (rsl.msg_type == RSL_MT_SACCH_FILL) {
		handled := true;

		if (si_type == RSL_SYSTEM_INFO_5) {
			if (not isbound(data)) {
				si.si5 := omit;
			} else {
				si.si5 := dec_SystemInformation(data).payload.si5;
			}
		} else if (si_type == RSL_SYSTEM_INFO_5bis) {
			if (not isbound(data)) {
				si.si5bis := omit;
			} else {
				si.si5bis := dec_SystemInformation(data).payload.si5bis;
			}
		} else if (si_type == RSL_SYSTEM_INFO_5ter) {
			if (not isbound(data)) {
				si.si5ter := omit;
			} else {
				si.si5ter := dec_SystemInformation(data).payload.si5ter;
			}
		} else if (si_type == RSL_SYSTEM_INFO_6) {
			if (not isbound(data)) {
				si.si6 := omit;
			} else {
				si.si6 := dec_SystemInformation(data).payload.si6;
			}
		} else {
			handled := false;
		}
	}

	if (not handled) {
		setverdict(fail, "Unexpected SI type in ", rsl.msg_type, " message: ", si_type);
	}
}

type component test_CT extends CTRL_Adapter_CT {
	/* Array of per-BTS/TRX state */
	var BTS_State bts[NUM_BTS][NUM_TRX];
	/* RSL common Channel Port (for RSL_Emulation) */
	port RSL_CCHAN_PT RSL_CCHAN[NUM_BTS];
	/* array of per-BTS/TRX RSL test ports */
	port IPA_RSL_PT IPA_RSL[NUM_BTS][NUM_TRX];
	port IPA_CODEC_PT IPA; /* Required for compilation of TC_rsl_unknown_unit_id() */
	/* CTRL muxed over IPA in SCCPlite conn BSC<->MSC (or BSC-NAT) */
	port IPA_CTRL_PT SCCPLITE_IPA_CTRL;
	/* Configure/manage IPA_Emulation per-BTS/TRX port: */
	port IPA_CFG_PT IPA_CFG_PORT[NUM_BTS][NUM_TRX];

	var MGCP_Emulation_CT vc_MGCP;
	port MGCP_CODEC_PT MGCP;

	port TELNETasp_PT BSCVTY;

	/* StatsD */
	var StatsD_Checker_CT vc_STATSD;

	var RAN_Adapter g_bssap[NUM_MSC];
	var BSSAP_LE_Adapter g_bssap_le;
	/* for old legacy-tests only */
	port BSSAP_CODEC_PT BSSAP;
	port BSSAP_LE_CODEC_PT BSSAP_LE;

	/* are we initialized yet */
	var boolean g_initialized := false;

	/* Osmux is enabled through VTY */
	var boolean g_osmux_enabled := false;

	/*Configure T(tias) over VTY, seconds */
	var integer g_bsc_sccp_timer_ias :=  7 * 60;
	/*Configure T(tiar) over VTY, seconds */
	var integer g_bsc_sccp_timer_iar := 15 * 60;

	/* global test case guard timer (actual timeout value is set in f_init()) */
	timer T_guard := 30.0;

	var CounterNameValsList g_ctr_msc;
	var CounterNameValsList g_ctr_bsc;
	var CounterNameValsList g_ctr_bts;

	/* System Information bytes as received during RSL startup, for each RSL[idx]. */
	var SystemInformationConfig_list g_system_information := {};
}

type record of charstring phys_chan_configs;
modulepar {
	/* IP address at which the BSC can be reached */
	charstring mp_bsc_ip := "127.0.0.1";
	/* port number to which to establish the IPA OML connections */
	integer mp_bsc_oml_port := 3002;
	/* port number to which to establish the IPA RSL connections */
	integer mp_bsc_rsl_port := 3003;
	/* port number to which to establish the IPA CTRL connection */
	integer mp_bsc_ctrl_port := 4249;
	/* port number to which to listen for STATSD metrics */
	integer mp_bsc_statsd_port := 8125;
	/* IP address at which the test binds */
	charstring mp_test_ip := "127.0.0.1";

	RAN_Configurations mp_bssap_cfg := {
		{
			transport := BSSAP_TRANSPORT_AoIP,
			sccp_service_type := "mtp3_itu",
			sctp_addr := { 23905, "127.0.0.1", 2905, "127.0.0.1" },
			own_pc := 185,	/* 0.23.1 first MSC emulation */
			own_ssn := 254,
			peer_pc := 187, /* 0.23.3 osmo-bsc */
			peer_ssn := 254,
			sio := '83'O,
			rctx := 1
		},
		{
			transport := BSSAP_TRANSPORT_AoIP,
			sccp_service_type := "mtp3_itu",
			sctp_addr := { 23906, "127.0.0.1", 2905, "127.0.0.1" },
			own_pc := 2,	/* 0.0.2 second MSC emulation */
			own_ssn := 254,
			peer_pc := 187, /* 0.23.3 osmo-bsc */
			peer_ssn := 254,
			sio := '83'O,
			rctx := 2
		},
		{
			transport := BSSAP_TRANSPORT_AoIP,
			sccp_service_type := "mtp3_itu",
			sctp_addr := { 23907, "127.0.0.1", 2905, "127.0.0.1" },
			own_pc := 3,	/* 0.0.3 third MSC emulation */
			own_ssn := 254,
			peer_pc := 187, /* 0.23.3 osmo-bsc */
			peer_ssn := 254,
			sio := '83'O,
			rctx := 3
		}
	};

	/* Must match per BTS config in osmo-bsc.cfg */
	phys_chan_configs phys_chan_config := {
		"CCCH+SDCCH4+CBCH",
		"TCH/F",
		"TCH/F",
		"TCH/F",
		"TCH/F",
		"TCH/H",
		"PDCH",
		"PDCH"
	};

	BSSAP_LE_Configuration mp_bssap_le_cfg := {
		sccp_service_type := "mtp3_itu",
		sctp_addr := { 23908, "127.0.0.1", 2905, "127.0.0.1" },
		own_pc := 190,	/* 0.23.6 SMLC emulation */
		own_ssn := 252,	/* SMLC side SSN */
		peer_pc := 187, /* 0.23.3 osmo-bsc */
		peer_ssn := 250, /* BSC side SSN */
		sio := '83'O,
		rctx := 6
	};
	boolean mp_enable_lcs_tests := true;

	/* Value set in osmo-bsc.cfg "ms max power" */
	uint8_t mp_exp_ms_power_level := 7;

	/* Whether to check for memory leaks */
	boolean mp_verify_talloc_count := true;
}

friend function f_gen_test_hdlr_pars(integer bssap_idx := 0) return TestHdlrParams {

	var TestHdlrParams pars := valueof(t_def_TestHdlrPars);
	if (mp_bssap_cfg[bssap_idx].transport == BSSAP_TRANSPORT_AoIP) {
		pars.aoip := true;
	} else {
		pars.aoip := false;
	}
	pars.exp_ms_power_level := mp_exp_ms_power_level;
	pars.mscpool.bssap_idx := bssap_idx;
	pars.expect_tsc := c_BtsParams[0].tsc;
	pars.imsi := f_rnd_imsi('00101'H);

	log(testcasename(), ": using IMSI ", pars.imsi);

	return pars;
}

/* Convenience functions for rate counters using g_ctr_msc. */

private function f_ctrs_msc_init(integer mscs_count := NUM_MSC, CounterNameVals counternames := counternames_msc_mscpool) runs on test_CT {
	g_ctr_msc := f_counter_name_vals_get_n(IPA_CTRL, "msc", mscs_count, counternames);
	log("initial msc rate counters: ", g_ctr_msc);
}

private function f_ctrs_msc_add(integer msc_nr, charstring countername, integer val := 1) runs on test_CT {
	f_counter_name_vals_list_add(g_ctr_msc, msc_nr, countername, val);
}

/*  f_ctrs_msc_init();
 *  f_do_thing(on_msc := 0);
 *  f_do_thing(on_msc := 0);
 *  f_do_other(on_msc := 1);
 *  f_ctrs_msc_add(0, "thing", 2);
 *  f_ctrs_msc_add(1, "other");
 *  f_ctrs_msc_verify();
 */
private function f_ctrs_msc_verify() runs on test_CT {
	log("verifying msc rate counters: ", g_ctr_msc);
	f_counter_name_vals_expect_n(IPA_CTRL, "msc", g_ctr_msc);
}

/* convenience: f_ctrs_msc_add() and f_ctrs_msc_verify() in one call.
 *  f_ctrs_msc_init();
 *  f_do_thing(on_msc := 0);
 *  f_do_thing(on_msc := 0);
 *  f_do_thing(on_msc := 0);
 *  f_ctrs_msc_expect(0, "thing", 3);
 */
private function f_ctrs_msc_expect(integer msc_nr, charstring countername, integer val := 1) runs on test_CT {
	f_ctrs_msc_add(msc_nr, countername, val);
	f_ctrs_msc_verify();
}

/* Convenience functions for rate counters using g_ctr_bts, always also including g_ctr_bsc. */

private function f_ctrs_bts_init(integer bts_count := NUM_BTS, CounterNameVals counternames := counternames_bsc_bts_handover) runs on test_CT {
	g_ctr_bts := f_counter_name_vals_get_n(IPA_CTRL, "bts", bts_count, counternames);
	log("initial bts rate counters: ", g_ctr_bts);
}

function f_ctrs_bsc_and_bts_init(integer bts_count := NUM_BTS, CounterNameVals counternames := counternames_bsc_bts_handover) runs on test_CT {
	f_ctrs_bts_init(bts_count, counternames);
	f_ctrs_bsc_init(counternames);
}

private function f_ctrs_bsc_and_bts_handover_init(integer bts_count := NUM_BTS) runs on test_CT {
	var CounterNameVals bts_names := counternames_bsc_bts_handover & counternames_bts_handover;
	f_ctrs_bts_init(bts_count, bts_names);
	f_ctrs_bsc_init(counternames_bsc_bts_handover);
}

private function f_ctrs_bts_add(integer bts_nr, charstring countername, integer val := 1) runs on test_CT {
	f_counter_name_vals_list_add(g_ctr_bts, bts_nr, countername, val);
}

private function f_ctrs_bsc_and_bts_add(integer bts_nr, charstring countername, integer val := 1) runs on test_CT {
	f_ctrs_bts_add(bts_nr, countername, val);
	f_ctrs_bsc_add(countername, val);
}

function f_ctrs_bts_verify() runs on test_CT {
	f_counter_name_vals_expect_n(IPA_CTRL, "bts", g_ctr_bts);
}

/*  f_ctrs_bsc_and_bts_init();
 *  f_do_thing(on_bts := 0);
 *  f_do_thing(on_bts := 0);
 *  f_do_other(on_bts := 1);
 *  f_ctrs_bsc_and_bts_add(0, "thing", 2);
 *  f_ctrs_bsc_and_bts_add(1, "other");
 *  f_ctrs_bsc_and_bts_verify();
 */
private function f_ctrs_bsc_and_bts_verify() runs on test_CT {
	f_ctrs_bts_verify();
	f_ctrs_bsc_verify();
}

/* convenience: f_ctrs_bsc_and_bts_add() and f_ctrs_bsc_and_bts_verify() in one call.
 *  f_ctrs_bsc_and_bts_init();
 *  f_do_thing(on_bts := 0);
 *  f_do_thing(on_bts := 0);
 *  f_do_thing(on_bts := 0);
 *  f_ctrs_bsc_and_bts_expect(0, "thing", 3);
 */
private function f_ctrs_bsc_and_bts_expect(integer bts_nr, charstring countername, integer val := 1) runs on test_CT {
	f_ctrs_bsc_and_bts_add(bts_nr, countername, val);
	f_ctrs_bsc_and_bts_verify();
}


/* Convenience functions for rate counters using g_ctr_bsc. */

private function f_ctrs_bsc_init(CounterNameVals counternames := counternames_bsc_bts_handover) runs on test_CT {
	g_ctr_bsc := f_counter_name_vals_get_n(IPA_CTRL, "bsc", 1, counternames);
	log("initial bsc rate counters: ", g_ctr_bsc);
}

private function f_ctrs_bsc_add(charstring countername, integer val := 1) runs on test_CT {
	f_counter_name_vals_list_add(g_ctr_bsc, 0, countername, val);
}

/*  f_ctrs_bsc_init();
 *  f_do_thing();
 *  f_do_thing();
 *  f_do_other();
 *  f_ctrs_bsc_add("thing", 2);
 *  f_ctrs_bsc_add("other");
 *  f_ctrs_bsc_verify();
 */
private function f_ctrs_bsc_verify() runs on test_CT {
	f_counter_name_vals_expect_n(IPA_CTRL, "bsc", g_ctr_bsc);
}

/* convenience: f_ctrs_bsc_add() and f_ctrs_bsc_verify() in one call.
 *  f_ctrs_bsc_init();
 *  f_do_thing();
 *  f_ctrs_bsc_expect("thing", 1);
 */
private function f_ctrs_bsc_expect(charstring countername, integer val := 1) runs on test_CT {
	f_ctrs_bsc_add(countername, val);
	f_ctrs_bsc_verify();
}


friend function f_shutdown_helper() runs on test_CT {
	/* Run the subscr and conn leak test only when the VTY is initialized */
	if (BSCVTY.checkstate("Mapped") and mp_verify_talloc_count) {
		f_verify_talloc_count(BSCVTY, {"struct bsc_subscr", "struct gsm_subscriber_connection"});
	}

	all component.stop;
	setverdict(pass);
	mtc.stop;
}

private function f_legacy_bssap_reset(integer bssap_idx := 0) runs on test_CT {
	var BSSAP_N_UNITDATA_ind ud_ind;
	var boolean reset_received := false;
	timer T := 5.0;
	BSSAP.send(ts_BSSAP_UNITDATA_req(g_bssap[bssap_idx].sccp_addr_peer, g_bssap[bssap_idx].sccp_addr_own,
					 ts_BSSMAP_Reset(0, g_osmux_enabled)));
	T.start;
	alt {
	[] BSSAP.receive(tr_BSSAP_UNITDATA_ind(g_bssap[bssap_idx].sccp_addr_own, g_bssap[bssap_idx].sccp_addr_peer,
					       tr_BSSMAP_ResetAck(g_osmux_enabled))) {
		log("BSSMAP: Received RESET-ACK in response to RESET, we're ready to go!");
		}
	[] BSSAP.receive(tr_BSSAP_UNITDATA_ind(?, ?, tr_BSSMAP_Reset(g_osmux_enabled))) -> value ud_ind {
		log("BSSMAP: Respoding to inbound RESET with RESET-ACK");
		BSSAP.send(ts_BSSAP_UNITDATA_req(ud_ind.callingAddress, ud_ind.calledAddress,
			   ts_BSSMAP_ResetAck(g_osmux_enabled)));
		reset_received := true;
		repeat;
		}
	[] BSSAP.receive { repeat; }
	[] T.timeout {
			log("BSSMAP: Timeout waiting for RESET-ACK after sending RESET");
			/* If we received a RESET after ours was sent, it
			   may be a race condition where the other peer beacame
			   available after we sent it, but we are in a desired
			   state anyway, so go forward. */
			if (not reset_received) {
				setverdict(fail);
			}
		}
	}
}

type record IPA_Client {
	/* IPA Emulation component reference */
	IPA_Emulation_CT vc_IPA,
	/* Unit-ID and other CCM parameters to use for IPA client emulation */
	IPA_CCM_Parameters ccm_pars,
	/* String identifier for this IPA Client */
	charstring id,
	/* Associated RSL Emulation Component (if any). Only used in "Handler mode" */
	RSL_Emulation_CT vc_RSL optional
}

/*! Start the IPA/RSL related bits for one IPA_Client.
 *  \param clnt IPA_Client for which to establish
 *  \param bsc_host IP address / hostname of the BSC
 *  \param bsc_port TCP port number of the BSC
 *  \param idx BTS/TRX index values
 *  \param handler_mode Start an RSL_Emulation_CT component (true) or not (false) */
function f_ipa_rsl_start(inout IPA_Client clnt, charstring bsc_host, PortNumber bsc_port,
			 BtsTrxIdx idx := {0, 0}, boolean handler_mode := false)
runs on test_CT {
	timer T := 10.0;

	clnt.id := "IPA-BTS" & int2str(idx.bts) & "-TRX" & int2str(idx.trx) & "-RSL";
	clnt.vc_IPA := IPA_Emulation_CT.create(clnt.id & "-IPA") alive;
	clnt.ccm_pars := c_IPA_default_ccm_pars;
	clnt.ccm_pars.name := "Osmocom TTCN-3 BTS Simulator";
	clnt.ccm_pars.unit_id := int2str(1234 + idx.bts) & "/0/" & int2str(idx.trx);
	if (handler_mode) {
		clnt.vc_RSL := RSL_Emulation_CT.create(clnt.id & "-RSL") alive;
		connect(clnt.vc_RSL:CCHAN_PT, self:RSL_CCHAN[idx.bts]);
	}

	map(clnt.vc_IPA:IPA_PORT, system:IPA_CODEC_PT);
	connect(clnt.vc_IPA:CFG_PORT, self:IPA_CFG_PORT[idx.bts][idx.trx]);
	if (handler_mode) {
		connect(clnt.vc_IPA:IPA_RSL_PORT, clnt.vc_RSL:IPA_PT);
	} else {
		connect(clnt.vc_IPA:IPA_RSL_PORT, self:IPA_RSL[idx.bts][idx.trx]);
	}

	var integer local_port := 10000 + idx.bts * 1000 + idx.trx;
	clnt.vc_IPA.start(IPA_Emulation.main_client(bsc_host, bsc_port, "", local_port, clnt.ccm_pars));
	if (handler_mode) {
		clnt.vc_RSL.start(RSL_Emulation.main());
		return;
	}

	/* wait for IPA RSL link to connect and send ID ACK */
	T.start;
	alt {
	[] IPA_RSL[idx.bts][idx.trx].receive(tr_ASP_IPA_EV(ASP_IPA_EVENT_ID_ACK)) {
		T.stop;
		}
	[] IPA_RSL[idx.bts][idx.trx].receive(ASP_IPA_Event:?) { repeat }
	[] IPA_RSL[idx.bts][idx.trx].receive { repeat }
	[] T.timeout {
		setverdict(fail, "Timeout RSL waiting for ASP_IPA_EVENT_ID_ACK");
		mtc.stop;
		}
	}
}

function f_ipa_rsl_stop(inout IPA_Client clnt, BtsTrxIdx idx := {0, 0}) runs on test_CT {
	var IPL4asp_Types.Result res := {
		errorCode := omit,
		connId := omit,
		os_error_code := omit,
		os_error_text := omit
	};

	if (not isbound(clnt) or not isbound(clnt.vc_IPA)) {
		return;
	}

	/* Alive components don't finish sockets (TCP FIN) when they are
	 * stopped. Hence, we need to manually call close() on them to make sure
	 * the IUT knows about it. */
	f_ipa_cfg_disconnect(IPA_CFG_PORT[idx.bts][idx.trx], res);

	clnt.vc_IPA.stop;
	if (isbound(clnt.vc_RSL)) {
		clnt.vc_RSL.stop;
	}
}

/* Wait for the OML connection to be brought up by the external osmo-bts-omldummy */
function f_wait_oml(integer bts_nr, charstring status, float secs_max) runs on test_CT {
	timer T := secs_max;
	T.start;
	while (true) {
		if (f_ctrl_get_bts(IPA_CTRL, bts_nr, "oml-connection-state") == status) {
			T.stop;
			/* the 'degraded' state exists from OML connection time, and we have to wait
			 * until all MO's are initialized */
			T.start(1.0);
			T.timeout;
			return;
		}
		f_sleep(0.1);
		if (not T.running) {
			setverdict(fail, "Timeout waiting for BTS" & int2str(bts_nr) & " oml-connection-state ", status);
			mtc.stop;
		}
	}
}

/* global altstep for global guard timer; also takes care of responding RESET witH RESET-ACK */
altstep as_Tguard() runs on test_CT {
	var BSSAP_N_UNITDATA_ind ud_ind;
	[] T_guard.timeout {
			setverdict(fail, "Timeout of T_guard");
			mtc.stop;
		}
	/* always respond with RESET ACK to RESET */
	[] BSSAP.receive(tr_BSSAP_UNITDATA_ind(?, ?, tr_BSSMAP_Reset(g_osmux_enabled))) -> value ud_ind {
		BSSAP.send(ts_BSSAP_UNITDATA_req(ud_ind.callingAddress, ud_ind.calledAddress,
			   ts_BSSMAP_ResetAck(g_osmux_enabled)));
		repeat;
		}
}

altstep no_bssmap_reset() runs on test_CT {
	[] BSSAP.receive(tr_BSSAP_UNITDATA_ind(?, ?, tr_BSSMAP_Reset(g_osmux_enabled))) {
		setverdict(fail, "unexpected BSSMAP Reset");
		mtc.stop;
	}
}

function f_init_mgcp(charstring id) runs on test_CT {
	id := id & "-MGCP";

	var MGCPOps ops := {
		create_cb := refers(MGCP_Emulation.ExpectedCreateCallback),
		unitdata_cb := refers(MGCP_Emulation.DummyUnitdataCallback)
	};
	var MGCP_conn_parameters mgcp_pars := {
		callagent_ip := mp_bsc_ip,
		callagent_udp_port := -1,
		mgw_ip := mp_test_ip,
		mgw_udp_port := 2427,
		/* Enable it for SCCPlite, since we have 2 MGCP sockets towards MGW (UDP one +
		   the on  with MGCP over IPA forwarded from MSC one) */
		multi_conn_mode := (mp_bssap_cfg[0].transport == BSSAP_TRANSPORT_SCCPlite_SERVER)
	};

	vc_MGCP := MGCP_Emulation_CT.create(id) alive;
	vc_MGCP.start(MGCP_Emulation.main(ops, mgcp_pars, id));
}

/* Enable or disable (current default) Osmux. When enabling, BSSMAP Reset
 * contains extra IE (OsmuxSupport) and osmo-bsc will handle AssignReq with
 * OsmuxCID IE.
 */
private function f_vty_allow_osmux(boolean allow) runs on test_CT {
	f_vty_enter_cfg_msc(BSCVTY, 0);
	if (allow) {
		f_vty_transceive(BSCVTY, "osmux on");
	} else {
		f_vty_transceive(BSCVTY, "osmux off");
	}
	f_vty_transceive(BSCVTY, "exit");
	f_vty_transceive(BSCVTY, "exit");
	g_osmux_enabled := allow;
}

function f_init_vty(charstring id := "foo") runs on test_CT {
	if (BSCVTY.checkstate("Mapped")) {
		/* skip initialization if already executed once */
		return;
	}
	map(self:BSCVTY, system:BSCVTY);
	f_vty_set_prompts(BSCVTY);
	f_vty_transceive(BSCVTY, "enable");
	f_cs7_inst_0_cfg(BSCVTY, {"sccp-timer ias " & int2str(g_bsc_sccp_timer_ias),
			  "sccp-timer iar " & int2str(g_bsc_sccp_timer_iar)});
}

friend function f_logp(TELNETasp_PT pt, charstring log_msg)
{
	// log on TTCN3 log output
	log(log_msg);
	// log in stderr log
	if (pt.checkstate("Mapped")) {
		f_vty_transceive(pt, "logp lglobal notice TTCN3 f_logp(): " & log_msg);
	}
}

private function f_sysinfo_seen(integer rsl_idx, RSL_Message rsl) runs on test_CT
{
	if (rsl_idx >= lengthof(g_system_information)) {
		g_system_information[rsl_idx] := SystemInformationConfig_omit
	}
	f_sysinfo_dec_raw(g_system_information[rsl_idx], rsl);
}

altstep as_catch_RSL_sysinfo(integer rsl_idx) runs on test_CT {
	var ASP_RSL_Unitdata rx_rsl_ud;

	/* For handler_mode := false, receiving the RSL bootstrap messages directly on IPA_RSL */
	[] IPA_RSL[rsl_idx][0].receive(tr_ASP_RSL_UD(tr_RSL_NO_BCCH_INFO)) -> value rx_rsl_ud {
		f_sysinfo_seen(rsl_idx, rx_rsl_ud.rsl);
		repeat;
		}
	[] IPA_RSL[rsl_idx][0].receive(tr_ASP_RSL_UD(tr_RSL_BCCH_INFO)) -> value rx_rsl_ud {
		f_sysinfo_seen(rsl_idx, rx_rsl_ud.rsl);
		repeat;
		}
	[] IPA_RSL[rsl_idx][0].receive(tr_ASP_RSL_UD(tr_RSL_NO_SACCH_FILL)) -> value rx_rsl_ud {
		f_sysinfo_seen(rsl_idx, rx_rsl_ud.rsl);
		repeat;
		}
	[] IPA_RSL[rsl_idx][0].receive(tr_ASP_RSL_UD(tr_RSL_SACCH_FILL)) -> value rx_rsl_ud {
		f_sysinfo_seen(rsl_idx, rx_rsl_ud.rsl);
		repeat;
		}

	/* For handler_mode := true, receiving the RSL bootstrap messages via RSL_Emulation  */
	[] RSL_CCHAN[rsl_idx].receive(tr_ASP_RSL_UD(tr_RSL_NO_BCCH_INFO)) -> value rx_rsl_ud {
		f_sysinfo_seen(rsl_idx, rx_rsl_ud.rsl);
		repeat;
		}
	[] RSL_CCHAN[rsl_idx].receive(tr_ASP_RSL_UD(tr_RSL_BCCH_INFO)) -> value rx_rsl_ud {
		f_sysinfo_seen(rsl_idx, rx_rsl_ud.rsl);
		repeat;
		}
	[] RSL_CCHAN[rsl_idx].receive(tr_ASP_RSL_UD(tr_RSL_NO_SACCH_FILL)) -> value rx_rsl_ud {
		f_sysinfo_seen(rsl_idx, rx_rsl_ud.rsl);
		repeat;
		}
	[] RSL_CCHAN[rsl_idx].receive(tr_ASP_RSL_UD(tr_RSL_SACCH_FILL)) -> value rx_rsl_ud {
		f_sysinfo_seen(rsl_idx, rx_rsl_ud.rsl);
		repeat;
		}
}

/* TODO: use BooleanList from COMMON/src/General_Types.ttcn */
private type record of boolean my_BooleanList;

private function f_vty_msc_allow_attach(TELNETasp_PT pt, my_BooleanList allow_attach_list)
{
	var charstring config := f_vty_transceive_ret(pt, "show running-config");

	for (var integer msc_nr := 0; msc_nr < sizeof(allow_attach_list); msc_nr := msc_nr+1) {
		if (f_strstr(config, "\nmsc " & int2str(msc_nr) & "\n") < 0) {
			/* There is no 'msc N' for this msc_nr in the running config, so don't create an empty msc by
			 * stepping into that config node. */
			log("msc ", msc_nr, " is not configured, skipping");
			continue;
		}
		f_vty_enter_cfg_msc(pt, msc_nr);
		if (allow_attach_list[msc_nr]) {
			/* strict := false: ignore if osmo-bsc does not support this config option (latest build) */
			f_vty_transceive(pt, "allow-attach", strict := false);
		} else {
			f_vty_transceive(pt, "no allow-attach", strict := false);
		}
		f_vty_transceive(pt, "exit");
		f_vty_transceive(pt, "exit");
	}
}

/* global initialization function
 * \param nr_bts Number of BTSs we should start/bring up
 * \param handler_mode Start an RSL_Emulation_CT component (true) or not (false).
 * \param nr_msc Number of virtual MSCs to bring up to connect to osmo-bsc.
 */
function f_init(integer nr_bts := NUM_BTS, boolean handler_mode := false, boolean allow_osmux := false,
		integer nr_msc := 1, float guard_timeout := 30.0) runs on test_CT {
	var integer bssap_idx;

	if (g_initialized) {
		return;
	}
	g_initialized := true;

	T_guard.start(guard_timeout);
	activate(as_Tguard());

	f_init_vty("VirtMSC");
	f_vty_allow_osmux(allow_osmux);

	var my_BooleanList allow_attach := { false, false, false };
	f_init_statsd("VirtMSC", vc_STATSD, mp_test_ip, mp_bsc_statsd_port);

	/* Make sure each MSC's internal state is "DISCONNECTED" at first */
	for (bssap_idx := 0; bssap_idx < NUM_MSC; bssap_idx := bssap_idx+1) {
		f_vty_transceive(BSCVTY, "msc " & int2str(bssap_idx) & " bssmap reset", strict := false);
	}

	for (bssap_idx := 0; bssap_idx < nr_msc; bssap_idx := bssap_idx+1) {
		allow_attach[bssap_idx] := true;
		/* Call a function of our 'parent component' RAN_Adapter_CT to start the
		 * MSC-side BSSAP emulation */
		if (handler_mode) {
			var RanOps ranops := MSC_RanOps;
			ranops.use_osmux := g_osmux_enabled;
			f_ran_adapter_init(g_bssap[bssap_idx], mp_bssap_cfg[bssap_idx], "VirtMSC", ranops);
			connect(self:SCCPLITE_IPA_CTRL, g_bssap[bssap_idx].vc_RAN:CTRL_CLIENT);
			f_ran_adapter_start(g_bssap[bssap_idx]);
		} else {
			f_ran_adapter_init(g_bssap[bssap_idx], mp_bssap_cfg[bssap_idx], "VirtMSC", omit);
			connect(self:BSSAP, g_bssap[bssap_idx].vc_SCCP:SCCP_SP_PORT);
			f_ran_adapter_start(g_bssap[bssap_idx]);
			f_legacy_bssap_reset();
		}
	}

	if (mp_enable_lcs_tests) {
		if (handler_mode) {
			f_bssap_le_adapter_init(g_bssap_le, mp_bssap_le_cfg, "VirtSMLC", SMLC_BssapLeOps);
		} else {
			f_bssap_le_adapter_init(g_bssap_le, mp_bssap_le_cfg, "VirtSMLC", omit);
			connect(self:BSSAP_LE, g_bssap_le.vc_SCCP:SCCP_SP_PORT);
		}
		f_bssap_le_adapter_start(g_bssap_le);
	}

	/* start the test with exactly all enabled MSCs allowed to attach */
	f_vty_msc_allow_attach(BSCVTY, allow_attach);

	f_ipa_ctrl_start_client(mp_bsc_ip, mp_bsc_ctrl_port);

	f_init_mgcp("VirtMSC");

	for (var integer i := 0; i < nr_bts; i := i+1) {
		f_init_bts(i, c_BtsParams[i].trx_num, handler_mode);
	}

	/* Emit a marker to appear in the SUT's own logging output */
	f_logp(BSCVTY, testcasename() & "() start");
}

function f_init_bts(integer bts_idx := 0,
		    integer trx_num := NUM_TRX_CFG,
		    boolean handler_mode := false)
runs on test_CT {
	/* wait until osmo-bts-omldummy has respawned */
	f_wait_oml(bts_idx, "degraded", 5.0);

	/* start RSL connection(s) */
	for (var integer trx_idx := 0; trx_idx < trx_num; trx_idx := trx_idx + 1) {
		f_ipa_rsl_start(bts[bts_idx][trx_idx].rsl,
				mp_bsc_ip, mp_bsc_rsl_port,
				{bts_idx, trx_idx}, handler_mode);
	}
	/* wait until BSC tells us "connected" */
	f_wait_oml(bts_idx, "connected", 5.0);
}

function f_init_bts_and_check_sysinfo(integer bts_idx := 0,
				      integer trx_num := NUM_TRX_CFG,
				      boolean handler_mode := false,
				      template SystemInformationConfig expect_si)
runs on test_CT {
	var default sysinfo := activate(as_catch_RSL_sysinfo(bts_idx));

	f_init_bts(bts_idx, trx_num, handler_mode);

	/* Give some time to (hopefully/most likely) collect all system informations from RSL startup.
	 * We could stop as soon as all expected SI are received, but then we might miss SI that we don't expect and
	 * that might be sent afterwards. So rather give a generous timeout and be quite sure to catch all SI.
	 */
	f_sleep(5.0);
	log("RSL ", bts_idx, " SYSTEM INFORMATION: ", g_system_information[bts_idx]);

	deactivate(sysinfo);

	if (match(g_system_information[bts_idx], expect_si)) {
		setverdict(pass);
	} else {
		log("RSL ", bts_idx, ": EXPECTED SI: ", expect_si);
		log("RSL ", bts_idx, ": GOT SI: ", g_system_information[bts_idx]);
		setverdict(fail, "received SI does not match expectations");
		return;
	}
}

/* expect to receive a RSL message matching a specified template on a given BTS / TRX */
function f_exp_ipa_rx(template (present) RSL_Message t_rx,
		      BtsTrxIdx idx := {0, 0},
		      float Tval := 2.0)
runs on test_CT return RSL_Message {
	var ASP_RSL_Unitdata rx_rsl_ud;
	timer T := Tval;

	T.start;
	alt {
	[] IPA_RSL[idx.bts][idx.trx].receive(tr_ASP_RSL_UD(t_rx, ?)) -> value rx_rsl_ud {
		T.stop;
		}
	[] IPA_RSL[idx.bts][idx.trx].receive { repeat; }
	[] T.timeout {
		setverdict(fail, "Timeout expecting ", t_rx);
		mtc.stop;
		}
	}
	return rx_rsl_ud.rsl;
}

/* helper function to transmit RSL on a given BTS/stream */
function f_ipa_tx(template (value) RSL_Message t_tx,
		  BtsTrxIdx idx := {0, 0},
		  IpaStreamId sid := IPAC_PROTO_RSL_TRX0)
runs on test_CT {
	IPA_RSL[idx.bts][idx.trx].send(ts_ASP_RSL_UD(t_tx, sid));
}


/* verify we get a CHAN_ACT after CHAN RQD */
testcase TC_chan_act_noreply() runs on test_CT {
	var BSSAP_N_UNITDATA_ind ud_ind;
	var RSL_Message rsl_unused;

	f_init(1);

	f_ipa_tx(ts_RSL_CHAN_RQD('23'O, 23));
	rsl_unused := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));
	f_shutdown_helper();
}

const CounterNameVals counternames_bts_chreq := {
	{ "chreq:total", 0 },
	{ "chreq:attempted_emerg", 0 },
	{ "chreq:attempted_call", 0 },
	{ "chreq:attempted_location_upd", 0 },
	{ "chreq:attempted_pag", 0 },
	{ "chreq:attempted_pdch", 0 },
	{ "chreq:attempted_other", 0 },
	{ "chreq:attempted_unknown", 0 },
	{ "chreq:successful", 0 },
	{ "chreq:successful_emerg", 0 },
	{ "chreq:successful_call", 0 },
	{ "chreq:successful_location_upd", 0 },
	{ "chreq:successful_pag", 0 },
	{ "chreq:successful_pdch", 0 },
	{ "chreq:successful_other", 0 },
	{ "chreq:successful_unknown", 0 },
	{ "chreq:no_channel", 0 },
	{ "chreq:max_delay_exceeded", 0 }
};

/* verify the "chreq:*" counters */
private function f_chan_act_counter(OCT1 ra, charstring chreq_ctr_suffix) runs on test_CT
{
	var GsmFrameNumber fn := 23;

	f_logp(BSCVTY, "f_chan_act_counter(" & chreq_ctr_suffix & ")");

	var RSL_Message rx_rsl;
	f_ipa_tx(ts_RSL_CHAN_RQD(ra, fn));
	rx_rsl := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));
	var RslChannelNr chan_nr := rx_rsl.ies[0].body.chan_nr;

	f_ctrs_bts_add(0, "chreq:total");
	f_ctrs_bts_add(0, "chreq:attempted_" & chreq_ctr_suffix);
	f_ctrs_bts_verify();

	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, fn+10));
	rx_rsl := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0));

	f_ctrs_bts_add(0, "chreq:successful");
	f_ctrs_bts_add(0, "chreq:successful_" & chreq_ctr_suffix);
	f_ctrs_bts_verify();

	/* test is done, release RSL Conn Fail Ind to clean up */
	f_ipa_tx(ts_RSL_CONN_FAIL_IND(chan_nr, RSL_ERR_RADIO_LINK_FAIL));
	rx_rsl := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_RF_CHAN_REL), Tval := 10.0);
	f_ipa_tx(ts_RSL_RF_CHAN_REL_ACK(chan_nr));
	f_sleep(1.0);
}

testcase TC_chan_act_counter() runs on test_CT {
	var BSSAP_N_UNITDATA_ind ud_ind;
	var integer chreq_total;
	var RSL_Message rsl_unused;

	f_init(1);

	f_vty_allow_emerg_bts(true, 0);

	f_ctrs_bts_init(1, counternames_bts_chreq);

	/* emergency call: RA & 0xe0 == 0xa0 --> CHREQ_T_EMERG_CALL */
	f_chan_act_counter('a3'O, "emerg");

	/* voice TCH/H: RA & 0xf0 == 0x40 --> CHREQ_T_VOICE_CALL_TCH_H */
	f_chan_act_counter('43'O, "call");

	/* LU: RA & 0xf0 == 0x00 --> CHREQ_T_LOCATION_UPD */
	f_chan_act_counter('03'O, "location_upd");

	/* Paging: RA & 0xf0 == 0x20 --> CHREQ_T_PAG_R_TCH_F */
	f_chan_act_counter('23'O, "pag");
	/* Paging: RA & 0xf0 == 0x30 --> CHREQ_T_PAG_R_TCH_FH */
	f_chan_act_counter('33'O, "pag");

	/* LU: RA & 0xfc == 0x78 --> CHREQ_T_PDCH_TWO_PHASE */
	/* no PCU, so PDCH not allowed. Skip this test for now. */
	/* f_chan_act_counter('7b'O, "pdch"); */

	/* LU: RA & 0xf0 == 0x10 --> CHREQ_T_SDCCH */
	f_chan_act_counter('13'O, "other");

	f_shutdown_helper();
}

/* CHAN RQD -> CHAN ACT -> CHAN ACT ACK -> RF CHAN REL */
private function f_TC_chan_act_ack_noest(OCT1 ra := '23'O) runs on test_CT {
	var RSL_Message rx_rsl;

	/* Send CHAN RQD and wait for allocation; acknowledge it */
	var RslChannelNr chan_nr := f_chreq_act_ack(ra);

	/* expect BSC to disable the channel again if there's no RLL EST IND */
	rx_rsl := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_RF_CHAN_REL), Tval := T3101_MAX);

	f_shutdown_helper();
}

/* Normal variant */
testcase TC_chan_act_ack_noest() runs on test_CT {
	 f_init(1);
	 f_TC_chan_act_ack_noest();
}

/* Emergency call variant */
testcase TC_chan_act_ack_noest_emerg() runs on test_CT {
	 /* See also: 3GPP TS 04.08, Table 9.9, ra=101xxxxx */
	 f_init(1);
	 f_vty_allow_emerg_bts(true, 0);
	 f_TC_chan_act_ack_noest(ra := 'A5'O);
}

/* Emergency call variant, but emergency calls are not allowed */
testcase TC_chan_rqd_emerg_deny() runs on test_CT {
	 /* See also: 3GPP TS 04.08, Table 9.9, ra=101xxxxx */

	 var RSL_Message rx_rsl;
	 var GsmRrMessage rr;

	 f_init(1);
	 f_vty_allow_emerg_bts(false, 0);

	 IPA_RSL[0][0].clear;
	 f_ipa_tx(ts_RSL_CHAN_RQD('A5'O, 23));

	 rx_rsl := f_exp_ipa_rx(tr_RSL_MsgTypeC(RSL_MT_IMMEDIATE_ASSIGN_CMD));
	 rr := dec_GsmRrMessage(rx_rsl.ies[1].body.full_imm_ass_info.payload);
	 if (rr.header.message_type == IMMEDIATE_ASSIGNMENT_REJECT) {
		setverdict(pass);
	 } else {
		setverdict(fail, "immediate assignment not rejected");
	 }

	f_shutdown_helper();
}

/* Test behavior if MSC never answers to CR */
testcase TC_chan_act_ack_est_ind_noreply() runs on test_CT {
	var RslLinkId main_dcch := valueof(ts_RslLinkID_DCCH(0));
	var IpaStreamId sid := IPAC_PROTO_RSL_TRX0;
	var RSL_Message rx_rsl;
	var ASP_RSL_Unitdata rx_rsl_ud;

	f_init(1);

	/* Send CHAN RQD and wait for allocation; acknowledge it */
	var RslChannelNr chan_nr := f_chreq_act_ack();

	var octetstring l3 := '00010203040506'O
	f_ipa_tx(ts_RSL_EST_IND(chan_nr, valueof(ts_RslLinkID_DCCH(0)), l3));

	BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3)));

	/* expect BSC to disable the channel again if there's no response from MSC */
	/* MS waits 20s (T3210) at LU; 10s (T3230) at CM SERV REQ and 5s (T3220) AT detach */
	f_expect_chan_rel(chan_nr, expect_rll_rel_req := false);
	f_shutdown_helper();
}

/* Test behavior if MSC answers with CREF to CR */
testcase TC_chan_act_ack_est_ind_refused() runs on test_CT {
	var BSSAP_N_CONNECT_ind rx_c_ind;
	var RSL_Message rx_rsl;

	f_init(1);

	/* Send CHAN RQD and wait for allocation; acknowledge it */
	var RslChannelNr chan_nr := f_chreq_act_ack();

	var octetstring l3 := '00010203040506'O
	f_ipa_tx(ts_RSL_EST_IND(chan_nr, valueof(ts_RslLinkID_DCCH(0)), l3));

	BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) -> value rx_c_ind;
	BSSAP.send(ts_BSSAP_DISC_req(rx_c_ind.connectionId, 0));

	/* expect BSC to disable the channel */
	f_expect_chan_rel(chan_nr, expect_rll_rel_req := false);
	f_shutdown_helper();
}

/* CHAN RQD -> CHAN ACT -> CHAN ACT NACK -> RF CHAN REL */
testcase TC_chan_act_nack() runs on test_CT {
	var RSL_Message rx_rsl;
	var integer chact_nack;

	f_init(1);

	chact_nack := f_ctrl_get_ratectr_abs(IPA_CTRL, "bts", 0, "chan_act:nack");

	f_ipa_tx(ts_RSL_CHAN_RQD('33'O, 33));
	rx_rsl := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));
	var RslChannelNr chan_nr := rx_rsl.ies[0].body.chan_nr;

	f_ipa_tx(ts_RSL_CHAN_ACT_NACK(chan_nr, RSL_ERR_EQUIPMENT_FAIL));

	/* wait for some time to hope the NACK arrives before the CTRL GET below */
	f_sleep(0.5);

	f_ctrl_get_exp_ratectr_abs(IPA_CTRL, "bts", 0, "chan_act:nack", chact_nack+1);

	f_shutdown_helper();
}

/* Test for channel exhaustion due to RACH overload */
testcase TC_chan_exhaustion() runs on test_CT {
	var ASP_RSL_Unitdata rsl_ud;
	var integer i;
	var integer chreq_total, chreq_nochan;

	f_init(1);

	chreq_total := f_ctrl_get_ratectr_abs(IPA_CTRL, "bts", 0, "chreq:total");
	chreq_nochan := f_ctrl_get_ratectr_abs(IPA_CTRL, "bts", 0, "chreq:no_channel");

	/* GSM 44.018 Table 9.1.8.2:
	 * RA = '33'O -> Establishment cause = 0011xxxx (MS dual rate capable and asks for "TCH/H or TCH/F").
	 * With current setup, expect 4xSDCCH + 4xTCH/F + 1xTCH/H to succeed */
	for (i := 0; i < NUM_TCHF_PER_BTS + NUM_TCHH_PER_BTS + NUM_SDCCH_PER_BTS; i := i+1) {
		var RslChannelNr chan_nr := f_chreq_act_ack('33'O, i);
	}

	IPA_RSL[0][0].clear;

	f_ctrl_get_exp_ratectr_abs(IPA_CTRL, "bts", 0, "chreq:total",
				   chreq_total + NUM_TCHF_PER_BTS + NUM_TCHH_PER_BTS + NUM_SDCCH_PER_BTS);

	/* now expect additional channel activations to fail */
	f_ipa_tx(ts_RSL_CHAN_RQD('42'O, 42));

	alt {
	[] IPA_RSL[0][0].receive(tr_ASP_RSL_UD(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV))) {
		setverdict(fail, "Received CHAN ACT ACK without resources?!?");
		}
	[] IPA_RSL[0][0].receive(tr_ASP_RSL_UD(tr_RSL_IMM_ASSIGN(?))) -> value rsl_ud {
		var GsmRrMessage rr;
		/* match on IMM ASS REJ */
		rr := dec_GsmRrMessage(rsl_ud.rsl.ies[1].body.full_imm_ass_info.payload);
		if (rr.header.message_type == IMMEDIATE_ASSIGNMENT_REJECT) {
			f_ctrl_get_exp_ratectr_abs(IPA_CTRL, "bts", 0, "chreq:total",
						   chreq_total + NUM_TCHF_PER_BTS + NUM_TCHH_PER_BTS + NUM_SDCCH_PER_BTS+1);
			f_ctrl_get_exp_ratectr_abs(IPA_CTRL, "bts", 0, "chreq:no_channel",
						   chreq_nochan+1);
			setverdict(pass);
		} else {
			repeat;
		}
		}
	[] IPA_RSL[0][0].receive { repeat; }
	}
	f_shutdown_helper();
}

/* Test channel deactivation due to silence from MS */
testcase TC_chan_deact_silence() runs on test_CT {
	var RslChannelNr chan_nr;

	f_init(1);

	/* Request for a dedicated channel */
	chan_nr := f_chreq_act_ack('23'O);

	/* Wait some time until the channel is released */
	f_sleep(2.0);

	/* Expect CHANnel RELease */
	alt {
	[] IPA_RSL[0][0].receive(tr_ASP_RSL_UD(tr_RSL_MsgTypeD(RSL_MT_RF_CHAN_REL))) {
		log("Received CHANnel RELease");
		setverdict(pass);
		}
	[] IPA_RSL[0][0].receive(tr_ASP_RSL_UD(tr_RSL_IMM_ASSIGN(?))) {
		/* See OS#3709, OsmoBSC should not send Immediate
		 * Assignment Reject since a dedicated channel was
		 * already allocated, and Immediate Assignment was
		 * already sent. */
		setverdict(fail, "Unexpected Immediate Assignment!");
		}
	[] IPA_RSL[0][0].receive {
		setverdict(fail, "Unexpected RSL message!");
		}
	}
	f_shutdown_helper();
}

/***********************************************************************
 * Assignment Testing
 ***********************************************************************/

/* Verify that the BSC refuses any BSSAP connection from the MSC (They are all BSC->MSC direction,
 * except for the inter-BSC handover, MT side) */
testcase TC_outbound_connect(integer bssap_idx := 0) runs on test_CT {
	f_init(1);

	BSSAP.send(ts_BSSAP_CONNECT_req(g_bssap[bssap_idx].sccp_addr_peer, g_bssap[bssap_idx].sccp_addr_own,
				        2342, ts_BSSMAP_AssignmentReq));
	BSSAP.receive(tr_BSSAP_DISC_ind(2342, ?, ?));
	f_shutdown_helper();
}

/* Test behavior if MSC answers with CREF to CR */
testcase TC_assignment_cic_only(integer bssap_idx := 0) runs on test_CT {
	var BSSAP_N_CONNECT_ind rx_c_ind;
	var RSL_Message rx_rsl;
	var DchanTuple dt;

	f_init(1);

	dt := f_est_dchan('23'O, 23, '00000000'O);
	if (mp_bssap_cfg[bssap_idx].transport == BSSAP_TRANSPORT_AoIP) {
		/* send assignment without AoIP IEs */
		BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_AssignmentReq(ts_BSSMAP_IE_CIC(0, 1))));
	} else {
		/* Send assignmetn without CIC in IPA case */
		var BSSMAP_IE_AoIP_TransportLayerAddress tla :=
						valueof(ts_BSSMAP_IE_AoIP_TLA4('01020304'O, 2342));
		BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_AssignmentReq(omit, tla)));
	}
	alt {
	[] BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_AssignmentComplete)) {
		setverdict(fail, "AoIP BSC cannot accept ASSIGNMENT without AoIP Transport IE");
		}
	/* TODO: Actually expect GSM0808_CAUSE_REQ_A_IF_TYPE_NOT_SUPP */
	[] BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_AssignmentFail)) {
		setverdict(pass);
		}
	[] BSSAP.receive { repeat; }
	}
	f_perform_clear_test_ct(dt);
	f_shutdown_helper();
}

/* generate an assignment request for either AoIP or SCCPlite */
function f_gen_ass_req(boolean osmux_enabled := false, integer bssap_idx := 0, charstring aoip_tla := "1.2.3.4") return PDU_BSSAP {
	var PDU_BSSAP ass_cmd;
	var BSSMAP_IE_Osmo_OsmuxCID osmux_cid := valueof(ts_OsmuxCID(0));
	if (mp_bssap_cfg[bssap_idx].transport == BSSAP_TRANSPORT_AoIP) {
		var BSSMAP_IE_AoIP_TransportLayerAddress tla :=
			valueof(f_ts_BSSMAP_IE_AoIP_TLA(aoip_tla, 2342));
		if (osmux_enabled) {
			ass_cmd := valueof(ts_BSSMAP_AssignmentReq(omit, tla, osmux_cid));
		} else {
			ass_cmd := valueof(ts_BSSMAP_AssignmentReq(omit, tla));
		}
	} else {
		var BSSMAP_IE_CircuitIdentityCode cic := valueof(ts_BSSMAP_IE_CIC(0,1));
		ass_cmd := valueof(ts_BSSMAP_AssignmentReq(cic, omit));
	}
	return ass_cmd;
}

function f_gen_handover_req(integer bssap_idx := 0, charstring aoip_tla := "1.2.3.4",
			    template (value) BSSMAP_IE_CellIdentifier cell_id_source := ts_CellID_LAC_CI(1, 1),
			    template (omit) BSSMAP_oldToNewBSSIEs oldToNewBSSIEs := omit,
			    template (omit) TestHdlrEncrParams enc := omit) return PDU_BSSAP {
	var PDU_BSSAP ho_req;

	var BSSMAP_IE_EncryptionInformation encryptionInformation :=
		valueof(ts_BSSMAP_IE_EncrInfo('0000000000000000'O,'01'O));
	var template (omit) BSSMAP_IE_ChosenEncryptionAlgorithm chosenEncryptionAlgorithm := omit;
	var template (omit) BSSMAP_IE_KC128 kc128 := omit;
	if (ispresent(enc)) {
		var TestHdlrEncrParams v_enc := valueof(enc);
		encryptionInformation := valueof(ts_BSSMAP_IE_EncrInfo(v_enc.enc_key, v_enc.enc_alg_permitted));
		if (ispresent(v_enc.enc_alg_chosen)) {
			chosenEncryptionAlgorithm := valueof(
				ts_BSSMAP_IE_ChosenEncryptionAlgorithm(int2oct(enum2int(
					f_cipher_mode_bssmap_to_rsl(v_enc.enc_alg_chosen)), 1)));
		}
		if (ispresent(v_enc.enc_kc128)) {
			kc128 := ts_BSSMAP_IE_Kc128(v_enc.enc_kc128);
		}
	}

	if (mp_bssap_cfg[bssap_idx].transport == BSSAP_TRANSPORT_AoIP) {
		var BSSMAP_IE_AoIP_TransportLayerAddress tla :=
			valueof(f_ts_BSSMAP_IE_AoIP_TLA(aoip_tla, 2342));
		ho_req := valueof(ts_BSSMAP_HandoverRequest(omit, tla,
							    cell_id_source := cell_id_source,
							    oldToNewBSSIEs := oldToNewBSSIEs,
							    encryptionInformation := encryptionInformation,
							    chosenEncryptionAlgorithm := chosenEncryptionAlgorithm,
							    kC128 := kc128,
							    /* on AoIP, allow "all" codecs (until we add more concise
							     * tests) */
							    codecList := ts_BSSMAP_IE_CodecList(
								{ts_CodecAMR_F, ts_CodecAMR_H,
								 ts_CodecEFR, ts_CodecFR, ts_CodecHR})));
	} else {
		var BSSMAP_IE_CircuitIdentityCode cic := valueof(ts_BSSMAP_IE_CIC(0,1));
		ho_req := valueof(ts_BSSMAP_HandoverRequest(cic, omit,
							    cell_id_source := cell_id_source,
							    oldToNewBSSIEs := oldToNewBSSIEs,
							    encryptionInformation := encryptionInformation,
							    chosenEncryptionAlgorithm := chosenEncryptionAlgorithm,
							    kC128 := kc128));
	}
	return ho_req;
}

/* generate an assignment complete template for either AoIP or SCCPlite */
function f_gen_exp_compl(boolean expect_osmux := false, integer bssap_idx := 0) return template PDU_BSSAP {
	var template PDU_BSSAP exp_compl;
	var BSSMAP_IE_Osmo_OsmuxCID osmux_cid := valueof(ts_OsmuxCID(0));
	if (mp_bssap_cfg[bssap_idx].transport == BSSAP_TRANSPORT_AoIP) {
		if (expect_osmux) {
			exp_compl := tr_BSSMAP_AssignmentComplete(omit, ?, osmux_cid);
		} else {
			exp_compl := tr_BSSMAP_AssignmentComplete(omit, ?, omit);
		}
	} else {
		/* CIC is optional "*" as the MSC allocated it */
		exp_compl := tr_BSSMAP_AssignmentComplete(*, omit);
	}
	return exp_compl;
}

/* Run everything required up to sending a caller-specified assignment command and expect response */
function f_assignment_exp(PDU_BSSAP ass_cmd, template PDU_BSSAP exp, charstring fail_text)
runs on test_CT return DchanTuple {
	var BSSAP_N_CONNECT_ind rx_c_ind;
	var RSL_Message rx_rsl;
	var DchanTuple dt;

	f_init(1);

	dt := f_est_dchan('23'O, 23, '00000000'O);
	/* send assignment without AoIP IEs */
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ass_cmd));
	alt {
	[] BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_AssignmentComplete)) {
		if (ischosen(exp.pdu.bssmap.assignmentComplete)) {
			setverdict(pass);
		} else {
			setverdict(fail, fail_text);
		}
		}
	[] BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_AssignmentFail)) {
		if (ischosen(exp.pdu.bssmap.assignmentFailure)) {
			setverdict(pass);
		} else {
			setverdict(fail, fail_text);
		}
		}
	[] BSSAP.receive { repeat; }
	}
	return dt;
}
testcase TC_assignment_csd() runs on test_CT {
	var template PDU_BSSAP exp_fail := tr_BSSMAP_AssignmentFail;
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelTypeCSD);
	//exp_fail.pdu.bssmap.assignmentFailure.cause.causeValue := int2bit(enum2int(GSM0808_CAUSE_REQ_CODEC_TYPE_OR_CONFIG_UNAVAIL), 7);
	var DchanTuple dt := f_assignment_exp(ass_cmd, exp_fail, "BSC accepted Assignment for CSD");
	f_perform_clear_test_ct(dt);
	f_shutdown_helper();
}

testcase TC_assignment_ctm() runs on test_CT {
	var template PDU_BSSAP exp_fail := tr_BSSMAP_AssignmentFail;
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelTypeCTM);
	//exp_fail.pdu.bssmap.assignmentFailure.cause.causeValue := int2bit(enum2int(GSM0808_CAUSE_REQ_CODEC_TYPE_OR_CONFIG_UNAVAIL), 7);
	var DchanTuple dt := f_assignment_exp(ass_cmd, exp_fail, "BSC accepted Assignment for Speech+CTM");
	f_perform_clear_test_ct(dt);
	f_shutdown_helper();
}

type record DchanTuple {
	integer sccp_conn_id,
	RslChannelNr rsl_chan_nr,
	BtsTrxIdx idx
}

type record of DchanTuple DchanTuples;

/* Send CHAN RQD and wait for allocation; acknowledge it */
private function f_chreq_act_ack(OCT1 ra := '23'O,
				 GsmFrameNumber fn := 23,
				 BtsTrxIdx idx := {0, 0})
runs on test_CT return RslChannelNr {
	var RSL_Message rx_rsl;
	f_ipa_tx(ts_RSL_CHAN_RQD(ra, fn), {idx.bts, 0});
	rx_rsl := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV), idx);
	var RslChannelNr chan_nr := rx_rsl.ies[0].body.chan_nr;
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, fn+10), idx);
	rx_rsl := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0), {idx.bts, 0});
	return chan_nr;
}

/* helper function to establish a dedicated channel via BTS and MSC */
function f_est_dchan(OCT1 ra, GsmFrameNumber fn, octetstring l3,
		     BtsTrxIdx idx := {0, 0})
runs on test_CT return DchanTuple {
	var BSSAP_N_CONNECT_ind rx_c_ind;
	var DchanTuple dt;

	/* Send CHAN RQD and wait for allocation; acknowledge it */
	dt.rsl_chan_nr := f_chreq_act_ack(ra, fn, idx);

	f_ipa_tx(ts_RSL_EST_IND(dt.rsl_chan_nr, valueof(ts_RslLinkID_DCCH(0)), l3), idx);

	BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) -> value rx_c_ind;
	dt.sccp_conn_id := rx_c_ind.connectionId;
	BSSAP.send(ts_BSSAP_CONNECT_res(dt.sccp_conn_id));

	dt.idx := idx;
	return dt;
}

/* Like f_est_dchan(), but for the first lchan of a dynamic timeslot: first ACK the deactivation of PDCH. */
function f_est_dchan_dyn(OCT1 ra, GsmFrameNumber fn, octetstring l3,
			 BtsTrxIdx idx := {0, 0})
runs on test_CT return DchanTuple {
	var BSSAP_N_CONNECT_ind rx_c_ind;
	var DchanTuple dt;

	/* Send CHAN RQD */
	var RSL_Message rx_rsl;
	f_ipa_tx(ts_RSL_CHAN_RQD(ra, fn), {idx.bts, 0});

	/* The dyn TS first deactivates PDCH */
	rx_rsl := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_RF_CHAN_REL), idx, Tval := T3101_MAX);
	dt.rsl_chan_nr := rx_rsl.ies[0].body.chan_nr;
	f_ipa_tx(ts_RSL_RF_CHAN_REL_ACK(dt.rsl_chan_nr), idx);

	rx_rsl := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV), idx);
	dt.rsl_chan_nr := rx_rsl.ies[0].body.chan_nr;

	/* Now activates the signalling channel */
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(dt.rsl_chan_nr, fn+10), idx);
	rx_rsl := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0), {idx.bts, 0});

	f_ipa_tx(ts_RSL_EST_IND(dt.rsl_chan_nr, valueof(ts_RslLinkID_DCCH(0)), l3), idx);

	BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) -> value rx_c_ind;
	dt.sccp_conn_id := rx_c_ind.connectionId;
	BSSAP.send(ts_BSSAP_CONNECT_res(dt.sccp_conn_id));

	dt.idx := idx;
	return dt;
}

/* expect RF CAN REL from BTS, acknowledge it and clear the MSC side */
private function f_exp_chan_rel_and_clear(DchanTuple dt)
runs on test_CT {
	var RSL_Message rx_rsl;
	/* expect BSC to disable the channel */
	rx_rsl := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_RF_CHAN_REL), dt.idx, Tval := T3101_MAX);
	/* respond with CHAN REL ACK */
	f_ipa_tx(ts_RSL_RF_CHAN_REL_ACK(dt.rsl_chan_nr), dt.idx);

	/* expect Clear Complete from BSC */
	BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_ClearComplete));

	/* MSC disconnects as instructed. */
	BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));
}

/* Test behavior of channel release after unilateral RLL REL IND (DISC from MS) */
testcase TC_chan_rel_rll_rel_ind() runs on test_CT {
	var BSSAP_N_DATA_ind rx_di;
	var DchanTuple dt;

	f_init(1);

	dt := f_est_dchan('23'O, 23, '00010203040506'O);

	/* simulate RLL REL IND */
	f_ipa_tx(ts_RSL_REL_IND(dt.rsl_chan_nr, valueof(ts_RslLinkID_DCCH(0))));

	/* expect Clear Request on MSC side */
	BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_ClearRequest)) -> value rx_di;

	/* Instruct BSC to clear channel */
	var BssmapCause cause := bit2int(rx_di.userData.pdu.bssmap.clearRequest.cause.causeValue);
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(cause)));

	/* expect BSC to disable the channel */
	f_exp_chan_rel_and_clear(dt);

	/* wait for SCCP emulation to do its job */
	f_sleep(1.0);

	f_shutdown_helper();
}

/* Test behavior of channel release after CONN FAIL IND from BTS */
testcase TC_chan_rel_conn_fail() runs on test_CT {
	var BSSAP_N_DATA_ind rx_di;
	var DchanTuple dt;

	f_init(1);

	dt := f_est_dchan('23'O, 23, '00010203040506'O);

	/* simulate CONN FAIL IND */
	f_ipa_tx(ts_RSL_CONN_FAIL_IND(dt.rsl_chan_nr, RSL_ERR_RADIO_LINK_FAIL));
	/* TODO: different cause values? */

	/* expect Clear Request from BSC */
	BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_ClearRequest)) -> value rx_di;

	/* Instruct BSC to clear channel */
	var BssmapCause cause := bit2int(rx_di.userData.pdu.bssmap.clearRequest.cause.causeValue);
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(cause)));

	/* expect BSC to disable the channel */
	f_exp_chan_rel_and_clear(dt);

	/* wait for SCCP emulation to do its job */
	f_sleep(1.0);

	f_shutdown_helper();
}

/* Test behavior of early CONN FAIL IND from BTS (before EST IND!) */
/* See also https://www.osmocom.org/issues/3182 */
testcase TC_early_conn_fail() runs on test_CT {
	var RSL_Message rx_rsl;
	var DchanTuple dt;

	f_init(1);

	/* BTS->BSC: Send CHAN RQD and wait for allocation; acknowledge it */
	dt.rsl_chan_nr := f_chreq_act_ack(f_rnd_ra_cs(), 23);

	/* BTS->BSC: simulate CONN FAIL IND */
	f_ipa_tx(ts_RSL_CONN_FAIL_IND(dt.rsl_chan_nr, RSL_ERR_RADIO_LINK_FAIL));

	/* BTS->BSC: Expect RF channel release from BSC on Abis */
	rx_rsl := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_RF_CHAN_REL), Tval := 10.0);

	/* BTS<-BSC: respond with CHAN REL ACK */
	f_ipa_tx(ts_RSL_RF_CHAN_REL_ACK(dt.rsl_chan_nr));

	f_shutdown_helper();
}

/* Test behavior of late CONN FAIL IND from BTS (ater REL IND!) */
/* See also https://www.osmocom.org/issues/3182 */
testcase TC_late_conn_fail() runs on test_CT {
	var RSL_Message rx_rsl;
	var DchanTuple dt;

	f_init(1);

	dt := f_est_dchan('23'O, 23, '00010203040506'O);

	/* BSC<-MSC: Instruct BSC to clear connection */
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(0)));

	/* BTS->BSC: expect BSC to deactivate SACCH */
	rx_rsl := f_exp_ipa_rx(tr_RSL_DEACT_SACCH(dt.rsl_chan_nr));

	/* BTS->BSC: simulate a late CONN FAIL IND from BTS */
	f_ipa_tx(ts_RSL_CONN_FAIL_IND(dt.rsl_chan_nr, RSL_ERR_RADIO_LINK_FAIL));

	/* BTS<-BSC: Expect RF channel release from BSC on Abis */
	rx_rsl := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_RF_CHAN_REL), Tval := 10.0);
	/* BTS->BSC: respond with CHAN REL ACK */
	f_ipa_tx(ts_RSL_RF_CHAN_REL_ACK(dt.rsl_chan_nr));

	/* BSC->MSC: expect Clear Complete from BSC */
	BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_ClearComplete));

	/* BSC<-MSC: MSC disconnects as requested. */
	BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));

	f_shutdown_helper();
}

private function f_TC_stats_conn_fail(charstring id) runs on MSC_ConnHdlr {
	var template PDU_BSSAP exp_fail := tr_BSSMAP_AssignmentFail;
	var PDU_BSSAP ass_cmd := f_gen_ass_req();

	f_statsd_reset();

	/* Establish SDCCH */
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelTypeCSD);
	f_establish_fully(ass_cmd, exp_fail);

	/* Expect stats to be 0 */
	var StatsDExpects expect := {
		{name := "TTCN3.bts.0.chan.rf_fail", mtype := "c", min := 0, max := 0},
		{name := "TTCN3.bts.0.chan.rf_fail_sdcch", mtype := "c", min := 0, max := 0}
	};
	f_statsd_expect(expect);

	/* Simulate CONN FAIL IND on SDCCH */
	RSL.send(ts_ASP_RSL_UD(
			ts_RSL_CONN_FAIL_IND(g_chan_nr, RSL_ERR_RADIO_LINK_FAIL),
			IPAC_PROTO_RSL_TRX0));

	f_sleep(1.0);

	/* Expect stats to be 1 */
	expect := {
		{name := "TTCN3.bts.0.chan.rf_fail", mtype := "c", min := 1, max := 1},
		{name := "TTCN3.bts.0.chan.rf_fail_sdcch", mtype := "c", min := 1, max := 1}
	};
	f_statsd_expect(expect);
	BSSAP.receive(tr_BSSMAP_ClearRequest);
	f_perform_clear();
}
testcase TC_stats_conn_fail() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	vc_conn := f_start_handler(refers(f_TC_stats_conn_fail), pars);
	vc_conn.done;

	f_shutdown_helper();
}

function f_expect_chan_rel(RslChannelNr rsl_chan_nr,
			   BtsTrxIdx idx := {0, 0},
			   boolean expect_deact_sacch := true,
			   boolean expect_rr_chan_rel := true,
			   boolean expect_rll_rel_req := true,
			   boolean handle_rll_rel := true,
			   template CellSelIndValue expect_cells := omit,
			   template (present) RR_Cause expect_rr_cause := ?
			   ) runs on test_CT {

	var RslLinkId main_dcch := valueof(ts_RslLinkID_DCCH(0));
	var boolean got_deact_sacch := false;
	var boolean got_rr_chan_rel := false;
	var boolean got_rll_rel_req := false;
	var ASP_RSL_Unitdata ud;
	var RSL_IE_Body l3_ie;
	var PDU_ML3_NW_MS l3;
	var RR_Cause got_cause;
	log("f_expect_chan_rel() expecting: expect_deact_sacch=", expect_deact_sacch, " expect_rr_chan_rel=", expect_rr_chan_rel,
	    " expect_rll_rel_req=", expect_rll_rel_req);
	alt {
	[] IPA_RSL[idx.bts][idx.trx].receive(tr_ASP_RSL_UD(tr_RSL_DEACT_SACCH(rsl_chan_nr))) {
		got_deact_sacch := true;
		repeat;
	}
	[] IPA_RSL[idx.bts][idx.trx].receive(tr_ASP_RSL_UD(tr_RSL_DATA_REQ(rsl_chan_nr, ?, decmatch tr_RRM_RR_RELEASE))) -> value ud {
		got_rr_chan_rel := true;

		if (f_rsl_find_ie(ud.rsl, RSL_IE_L3_INFO, l3_ie) == false) {
			setverdict(fail, "cannot find L3");
			mtc.stop;
		}
		l3 := dec_PDU_ML3_NW_MS(l3_ie.l3_info.payload);

		if (not istemplatekind(expect_cells, "omit")) {
			var CellSelIndValue cells := dec_CellSelIndValue(
				l3.msgs.rrm.channelRelease.cellSelectionIndicator.cellSelectionIndicatorValue);

			log("GOT RR CHANNEL RELEASE WITH CELLS: ", cells);
			if (match(cells, expect_cells)) {
				setverdict(pass);
			} else {
				log("EXPECTED CELLS: ", expect_cells);
				setverdict(fail, "Received cells list on RR Channel Release does not match expectations");
			}
		}

		int2enum(oct2int(l3.msgs.rrm.channelRelease.rRCause.valuePart), got_cause);
		log("GOT CAUSE CODE: ", l3.msgs.rrm.channelRelease.rRCause.valuePart, " = ", got_cause);
		if (match(got_cause, expect_rr_cause)) {
			setverdict(pass);
		} else {
			log("EXPECTED CAUSE CODE: ", expect_rr_cause);
			setverdict(fail, "Received RR Channel Release Cause code does not match expectations");
		}
		repeat;
	}
	[] IPA_RSL[idx.bts][idx.trx].receive(tr_ASP_RSL_UD(tr_RSL_REL_REQ(rsl_chan_nr, ?))) {
		got_rll_rel_req := true;
		/* FIXME: Why are we getting this for LinkID SACCH? */
		if (handle_rll_rel) {
			f_ipa_tx(ts_RSL_REL_CONF(rsl_chan_nr, main_dcch));
		}
		repeat;
	}
	[] IPA_RSL[idx.bts][idx.trx].receive(tr_ASP_RSL_UD(tr_RSL_MsgTypeD(RSL_MT_RF_CHAN_REL))) {
		/* respond with CHAN REL ACK */
		f_ipa_tx(ts_RSL_RF_CHAN_REL_ACK(rsl_chan_nr));
		}
	/* ignore any user data */
	[] IPA_RSL[idx.bts][idx.trx].receive(tr_ASP_RSL_UD(tr_RSL_MsgTypeR(?))) {
		repeat;
		}
	}

	log("f_expect_chan_rel() summary: got_deact_sacch=", got_deact_sacch, " got_rr_chan_rel=", got_rr_chan_rel,
	    " got_rll_rel_req=", got_rll_rel_req);

	if (expect_deact_sacch != got_deact_sacch) {
		setverdict(fail, "f_expect_chan_rel(): expect_deact_sacch=", expect_deact_sacch, " got_deact_sacch=", got_deact_sacch);
	}
	if (expect_rr_chan_rel != got_rr_chan_rel) {
		setverdict(fail, "f_expect_chan_rel(): expect_rr_chan_rel=", expect_rr_chan_rel, " got_rr_chan_rel=", got_rr_chan_rel);
	}
	if (expect_rll_rel_req != got_rll_rel_req) {
		setverdict(fail, "f_expect_chan_rel(): expect_rll_rel_req=", expect_rll_rel_req, " got_rll_rel_req=", got_rll_rel_req);
	}
}

/* Test behavior of channel release after hard Clear Command from MSC */
testcase TC_chan_rel_hard_clear() runs on test_CT {
	var BSSAP_N_DATA_ind rx_di;
	var DchanTuple dt;

	f_init(1);

	dt := f_est_dchan('23'O, 23, '00010203040506'O);

	/* Instruct BSC to clear channel */
	var BssmapCause cause := 0;
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(cause)));

	/* expect Clear Complete from BSC on A */
	BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_ClearComplete)) {
		/* release the SCCP connection */
		BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));
	}

	f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false);
	f_shutdown_helper();
}

function f_TC_chan_rel_last_eutran_plmn_hard_clear(boolean tx_csfb_ind) runs on test_CT {
	var BSSAP_N_DATA_ind rx_di;
	var DchanTuple dt;

	f_init(1);

	dt := f_est_dchan('23'O, 23, '00010203040506'O);
	/* Send CommonID with some random PLMN (BSC doesn't take it into account
	/* yet when generating the EUTRAN neigh list in RR CHannel Release) */
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_CommonId('001019876543210'H, '323454'O)));

	/* Instruct BSC to clear channel */
	var BssmapCause cause := 0;
	if (tx_csfb_ind) {
		BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommandCSFB(cause)));
	} else {
		BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(cause)));
	}

	/* expect Clear Complete from BSC on A */
	BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_ClearComplete)) {
		/* release the SCCP connection */
		BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));
	}

	/* 1 neighbor is added by default in osmo-bts.cfg and
	   SystemInformationConfig_default, use that: */
	var template CellSelIndValue exp_cells := f_tr_rr_chan_rel_earfcns(1);

	f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false, expect_cells := exp_cells);
	f_shutdown_helper();
}

/* Test behavior of RR Channel rRelease after Clear Command without CSFB indicator
   from MSC, previously receiving any CommonID containing the "Last Used E-UTRAN
   PLMN Id". According to spec (3GPP TS 48.008 sec 3.1.30) that's the bit requesting
   EUTRAN neighbor list sent later on by BSC in RR Channel, so receiving CSFB
   Indicator or not shouldn't matter at all. */
testcase TC_chan_rel_last_eutran_plmn_hard_clear_no_csfb() runs on test_CT {
	f_TC_chan_rel_last_eutran_plmn_hard_clear(false);
}

/* Test behavior of RR Channel rRelease after Clear Command with CSFB indicator from
   MSC, previously receiving any CommonID containing the "Last Used E-UTRAN PLMN
   Id". According to spec (3GPP TS 48.008 sec 3.1.30) that's the bit requesting
   EUTRAN neighbor list sent later on by BSC in RR Channel. */
testcase TC_chan_rel_last_eutran_plmn_hard_clear_csfb() runs on test_CT {
	f_TC_chan_rel_last_eutran_plmn_hard_clear(true);
}

/* Test behavior of RR Channel Release after Clear Command with CSFB indicator from
   MSC, without receiving any CommonID containing the "Last Used E-UTRAN PLMN
   Id". According to spec (TS 48.008 version 16.0.0 Release 16 "3.2.1.21") the
   CSFB Indicator should not be used anymore, and hence, there should be no
   EUTRAN neighbor list sent by BSC in RR Channel release since no CommonId with
   Last Used E-UTRAN PLMN Id" IE was sent for this conn. */
testcase TC_chan_rel_hard_clear_csfb() runs on test_CT {
	var BSSAP_N_DATA_ind rx_di;
	var DchanTuple dt;

	f_init(1);

	dt := f_est_dchan('23'O, 23, '00010203040506'O);

	/* Instruct BSC to clear channel */
	var BssmapCause cause := 0;
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommandCSFB(cause)));

	/* expect Clear Complete from BSC on A */
	BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_ClearComplete)) {
		/* release the SCCP connection */
		BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));
	}

	f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false);
	f_shutdown_helper();
}

/* Test behavior of channel release after hard RLSD from MSC */
testcase TC_chan_rel_hard_rlsd() runs on test_CT {
	var DchanTuple dt;

	f_init(1);

	dt := f_est_dchan('23'O, 23, '00010203040506'O);

	/* release the SCCP connection */
	BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));

	f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false);
	f_shutdown_helper();
}

/* Test behavior of channel release after hard RLSD from MSC and MS is not responding to RLL REL REQ */
testcase TC_chan_rel_hard_rlsd_ms_dead() runs on test_CT {
	var DchanTuple dt;

	f_init(1);

	dt := f_est_dchan('23'O, 23, '00010203040506'O);

	/* release the SCCP connection */
	BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));

	f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false);
	f_shutdown_helper();
}

/* Test behavior of channel release after BSSMAP RESET from MSC */
testcase TC_chan_rel_a_reset() runs on test_CT {
	var DchanTuple dt;

	f_init(1);

	dt := f_est_dchan('23'O, 23, '00010203040506'O);

	/* Clear the queue, it might still contain stuff like IMMEDIATE ASSIGN */
	IPA_RSL[0][0].clear;

	/* perform BSSAP RESET, expect RESET ACK and DISC.ind on connection */
	BSSAP.send(ts_BSSAP_UNITDATA_req(g_bssap[0].sccp_addr_peer, g_bssap[0].sccp_addr_own, ts_BSSMAP_Reset(0, g_osmux_enabled)));
	interleave {
	[] BSSAP.receive(tr_BSSAP_UNITDATA_ind(g_bssap[0].sccp_addr_own, g_bssap[0].sccp_addr_peer, tr_BSSMAP_ResetAck(g_osmux_enabled))) { }
	[] BSSAP.receive(tr_BSSAP_DISC_ind(dt.sccp_conn_id, ?, ?)) { }
	}

	f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false);
	f_shutdown_helper();
}

/* Verify T(iar) triggers and releases the channel */
testcase TC_chan_rel_sccp_tiar_timeout() runs on test_CT {
	var DchanTuple dt;

	/* Set T(iar) in BSC low enough that it will trigger before other side
	   has time to keep alive with a T(ias). Keep recommended ratio of
	   T(iar) >= T(ias)*2 */
	g_bsc_sccp_timer_ias := 2;
	g_bsc_sccp_timer_iar := 5;

	f_init(1);

	dt := f_est_dchan('23'O, 23, '00010203040506'O);
	f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false);
	f_shutdown_helper();
}

private function f_tc_chan_rel_rr_cause(myBSSMAP_Cause clear_cmd_cause,
					template (present) RR_Cause expect_rr_cause)
runs on test_CT
{
	var DchanTuple dt;

	dt := f_est_dchan('23'O, 23, '00010203040506'O);
	var BssmapCause cause := 0;
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(enum2int(clear_cmd_cause))));
	BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_ClearComplete)) {
		BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));
	}

	f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false, expect_rr_cause := expect_rr_cause);
}

/* Test that Clear Command cause codes affect the RR Channel Release cause code */
testcase TC_chan_rel_rr_cause() runs on test_CT {
	f_init(1);

	f_tc_chan_rel_rr_cause(GSM0808_CAUSE_CALL_CONTROL, GSM48_RR_CAUSE_NORMAL);
	f_tc_chan_rel_rr_cause(GSM0808_CAUSE_HANDOVER_SUCCESSFUL, GSM48_RR_CAUSE_NORMAL);
	f_tc_chan_rel_rr_cause(GSM0808_CAUSE_PREEMPTION, GSM48_RR_CAUSE_PREMPTIVE_REL);
	f_tc_chan_rel_rr_cause(GSM0808_CAUSE_RADIO_INTERFACE_MESSAGE_FAILURE, GSM48_RR_CAUSE_PROT_ERROR_UNSPC);
	f_tc_chan_rel_rr_cause(GSM0808_CAUSE_RADIO_INTERFACE_FAILURE, GSM48_RR_CAUSE_ABNORMAL_UNSPEC);
	f_tc_chan_rel_rr_cause(GSM0808_CAUSE_EQUIPMENT_FAILURE, GSM48_RR_CAUSE_ABNORMAL_UNSPEC);

	f_shutdown_helper();
}

/* Test behavior if RSL EST IND for non-active channel */
testcase TC_rll_est_ind_inact_lchan() runs on test_CT {
	timer T := 2.0;

	f_init(1);

	var octetstring l3 := '00010203040506'O;
	var RslChannelNr chan_nr := valueof(t_RslChanNr_Bm(6));
	f_ipa_tx(ts_RSL_EST_IND(chan_nr, valueof(ts_RslLinkID_DCCH(0)), l3));

	T.start;
	alt {
	[] BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) {
		setverdict(fail, "MSC received COMPL L3 for non-active lchan");
		}
	[] BSSAP.receive {}
	[] IPA_RSL[0][0].receive {}
	[] T.timeout {}
	}

	f_shutdown_helper();
}

/* Test behavior if RSL EST IND for invalid SAPI */
testcase TC_rll_est_ind_inval_sapi1() runs on test_CT {
	var RslChannelNr chan_nr;

	f_init(1);

	chan_nr := f_chreq_act_ack()

	var octetstring l3 := '00010203040506'O;
	f_ipa_tx(ts_RSL_EST_IND(chan_nr, valueof(ts_RslLinkID_DCCH(1)), l3));

	timer T := 2.0;
	T.start;
	alt {
	[] BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) {
		setverdict(fail, "MSC received COMPL L3 for invalid SAPI 1");
		}
	[] BSSAP.receive { repeat; }
	[] IPA_RSL[0][0].receive { repeat; }
	[] T.timeout {}
	}

	f_shutdown_helper();
}

/* Test behavior if RSL EST IND for invalid SAPI */
testcase TC_rll_est_ind_inval_sapi3() runs on test_CT {
	timer T := 2.0;

	f_init(1);

	var RslChannelNr chan_nr := f_chreq_act_ack();

	var octetstring l3 := '00010203040506'O;
	f_ipa_tx(ts_RSL_EST_IND(chan_nr, valueof(ts_RslLinkID_DCCH(3)), l3));

	T.start;
	alt {
	[] BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) {
		setverdict(fail, "MSC received COMPL L3 for invalid SAPI 3");
		}
	[] BSSAP.receive { repeat; }
	[] IPA_RSL[0][0].receive { repeat; }
	[] T.timeout {}
	}

	f_shutdown_helper();
}

/* Test behavior if RSL EST IND for invalid SACCH */
testcase TC_rll_est_ind_inval_sacch() runs on test_CT {
	timer T := 2.0;

	f_init(1);

	var RslChannelNr chan_nr := f_chreq_act_ack();

	var octetstring l3 := '00010203040506'O;
	f_ipa_tx(ts_RSL_EST_IND(chan_nr, valueof(ts_RslLinkID_SACCH(0)), l3));

	T.start;
	alt {
	[] BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) {
		setverdict(fail, "MSC received COMPL L3 for invalid Link SACCH");
		}
	[] BSSAP.receive { repeat; }
	[] IPA_RSL[0][0].receive { repeat; }
	[] T.timeout {}
	}

	f_shutdown_helper();
}

/* Verify DLCI / RSL Link ID conversion for MO/MT messages on SAPI0/SAPI3 */
private function f_TC_tch_dlci_link_id_sapi(charstring id) runs on MSC_ConnHdlr {
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();

	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));

	f_establish_fully(ass_cmd, exp_compl);

	/* SAPI0 has already been established by f_establish_fully(), establish SAPI3 */
	RSL.send(ts_RSL_EST_IND(g_chan_nr, ts_RslLinkID_SACCH(3), '0904'O));
	/* Expect BSSAP/DTAP on SAPI3 (DLCI IE) */
	BSSAP.receive(PDU_BSSAP:{
		discriminator := '1'B,
		spare := '0000000'B,
		dlci := 'C3'O,
		lengthIndicator := ?,
		pdu := { dtap := '0904'O }
	});

	/* Send messages on DCCH/SAPI0 and ACCH/SAPI3 */
	for (var integer i := 0; i < 32; i := i + 1) {
		var octetstring l3 := '09'O & f_rnd_octstring(14);
		var template (value) RslLinkId link_id;
		var template (value) OCT1 dlci;

		if (i mod 2 == 0) {
			/* SAPI0 on FACCH or SDCCH */
			link_id := ts_RslLinkID_DCCH(0);
			dlci := '80'O;
		} else {
			/* SAPI3 on SACCH */
			link_id := ts_RslLinkID_SACCH(3);
			dlci := 'C3'O;
		}

		/* Send MO message: RSL -> BSSAP */
		f_mo_l3_transceive(RSL, link_id, dlci, l3);
		/* Send MT message: BSSAP -> RSL */
		f_mt_l3_transceive(RSL, link_id, dlci, l3);
	}
	f_perform_clear();
}
testcase TC_tch_dlci_link_id_sapi() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	vc_conn := f_start_handler(refers(f_TC_tch_dlci_link_id_sapi), pars);
	vc_conn.done;

	f_shutdown_helper();
}

private function f_exp_sapi_n_reject(template (present) GsmSapi sapi := ?,
				     template (present) myBSSMAP_Cause cause := ?,
				     template (present) BIT2 cc := ?,
				     float T_val := 2.0)
runs on test_CT {
	var BSSAP_N_DATA_ind rx_di;
	timer T;

	var template (present) BSSMAP_IE_Cause tr_cause := tr_BSSMAP_IE_Cause(cause);
	var template (present) PDU_BSSAP tr_pdu := tr_BSSMAP_SAPInReject(sapi);

	T.start(T_val);
	alt {
	[] BSSAP.receive(tr_BSSAP_DATA_ind(?, tr_pdu)) -> value rx_di {
		var BSSMAP_IE_Cause rx_cause := rx_di.userData.pdu.bssmap.sAPInReject.cause;
		if (not match(rx_cause, tr_cause)) {
			setverdict(fail, "Rx unexpected Cause IE: ",
				   rx_cause, " vs expected ", tr_cause);
		}

		/* Who ever on the earth decided to define this field as two separate bits?!? */
		var BIT2 rx_cc := rx_di.userData.pdu.bssmap.sAPInReject.dLCI.c2
				& rx_di.userData.pdu.bssmap.sAPInReject.dLCI.c1;
		if (not match(rx_cc, cc)) {
			setverdict(fail, "Rx unexpected Control Channel type: ",
				   rx_cc, " vs expected ", cc);
		}

		setverdict(pass);
		}
	[] BSSAP.receive(BSSAP_N_DATA_ind:?) -> value rx_di {
		setverdict(fail, "Rx unexpected BSSAP PDU: ", rx_di);
		}
	[] T.timeout {
		setverdict(fail, "Timeout waiting for BSSMAP SAPI N Reject");
		}
	}
}

/* Check if we get SAPI N Reject on receipt of unexpected RLL RELease INDication */
testcase TC_rll_rel_ind_sapi_n_reject() runs on test_CT {
	var octetstring rnd_data := f_rnd_octstring(16);
	var RSL_Message rx_rsl;
	var DchanTuple dt;

	f_init(1);

	/* MS establishes a SAPI=0 link on DCCH */
	dt := f_est_dchan(f_rnd_ra_cs(), 23, rnd_data);

	/* MSC sends some data on (not yet established) SAPI=3 link */
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSAP_DTAP(rnd_data, '03'O)));
	/* BSC attempts to establish a SAPI=3 link on DCCH */
	rx_rsl := f_exp_ipa_rx(tr_RSL_EST_REQ(dt.rsl_chan_nr, tr_RslLinkID_DCCH(3)));

	/* MS sends unexpected RELease INDication on SAPI=3 */
	f_ipa_tx(ts_RSL_REL_IND(dt.rsl_chan_nr, ts_RslLinkID_DCCH(3)));
	/* We expect to receive BSSMAP SAPI N Reject message from the BSC */
	f_exp_sapi_n_reject(3, GSM0808_CAUSE_MS_NOT_EQUIPPED);

	/* Clean up the connection */
	BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));
	f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false);

	f_shutdown_helper();
}

/* Check if we get SAPI N Reject on receipt of unexpected RLL ERROR INDication */
testcase TC_rll_err_ind_sapi_n_reject() runs on test_CT {
	var octetstring rnd_data := f_rnd_octstring(16);
	var RSL_Message rx_rsl;
	var DchanTuple dt;

	f_init(1);

	/* MS establishes a SAPI=0 link on DCCH */
	dt := f_est_dchan(f_rnd_ra_cs(), 23, rnd_data);

	/* MSC sends some data on (not yet established) SAPI=3 link */
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSAP_DTAP(rnd_data, '03'O)));
	/* BSC attempts to establish a SAPI=3 link on DCCH */
	rx_rsl := f_exp_ipa_rx(tr_RSL_EST_REQ(dt.rsl_chan_nr, tr_RslLinkID_DCCH(3)));

	/* BTS sends unexpected ERROR INDication on SAPI=3 */
	f_ipa_tx(ts_RSL_ERROR_IND(dt.rsl_chan_nr, ts_RslLinkID_DCCH(3), ''O));
	/* We expect to receive BSSMAP SAPI N Reject message from the BSC */
	f_exp_sapi_n_reject(3, GSM0808_CAUSE_BSS_NOT_EQUIPPED);

	/* Clean up the connection */
	BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));
	f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false);

	f_shutdown_helper();
}

/* Check if we get SAPI N Reject due to a SAPI=3 link establishment timeout */
testcase TC_rll_timeout_sapi_n_reject() runs on test_CT {
	var octetstring rnd_data := f_rnd_octstring(16);
	var RSL_Message rx_rsl;
	var DchanTuple dt;

	f_init(1);

	/* MS establishes a SAPI=0 link on DCCH */
	dt := f_est_dchan(f_rnd_ra_cs(), 23, rnd_data);

	/* MSC sends some data on (not yet established) SAPI=3 link */
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSAP_DTAP(rnd_data, '03'O)));
	/* BSC attempts to establish a SAPI=3 link on DCCH */
	rx_rsl := f_exp_ipa_rx(tr_RSL_EST_REQ(dt.rsl_chan_nr, tr_RslLinkID_DCCH(3)));

	/* MS does not respond, so the link establishment timeout triggers SAPI N Reject */
	f_exp_sapi_n_reject(3, GSM0808_CAUSE_BSS_NOT_EQUIPPED, T_val := 8.0);

	/* Clean up the connection */
	BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));
	f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false);

	f_shutdown_helper();
}

/* Check DLCI CC (Control Channel type) bits in SAPI N Reject */
testcase TC_rll_sapi_n_reject_dlci_cc() runs on test_CT {
	var octetstring rnd_data := f_rnd_octstring(16);
	var RSL_Message rx_rsl;
	var DchanTuple dt;

	f_init(1);

	/* MS establishes a SAPI=0 link on DCCH */
	dt := f_est_dchan(f_rnd_ra_cs(), 23, rnd_data);

	/* MSC sends some data on (not yet established) SAPI=3 link */
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSAP_DTAP(rnd_data, '03'O)));
	/* BSC attempts to establish a SAPI=3 link on DCCH */
	rx_rsl := f_exp_ipa_rx(tr_RSL_EST_REQ(dt.rsl_chan_nr, tr_RslLinkID_DCCH(3)));

	/* MS sends unexpected ERROR INDication on DCCH/ACCH SAPI=3 */
	f_ipa_tx(ts_RSL_ERROR_IND(dt.rsl_chan_nr, ts_RslLinkID_DCCH(3), ''O));
	f_exp_sapi_n_reject(3, GSM0808_CAUSE_BSS_NOT_EQUIPPED, '10'B);

	/* Clean up the connection */
	BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));
	f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false);

	f_shutdown_helper();
}

testcase TC_si_default() runs on test_CT {
	f_init(0);
	f_init_bts_and_check_sysinfo(0, expect_si := SystemInformationConfig_default);
	f_shutdown_helper();
}

/* We're testing SI2quater with lists of EARFCNs. Instead of just incrementing EARFCNs, also pick some from the edges of
 * the entire value range. This function provides the same EARFCN numbers for the same earfcn_index  */
private function f_test_si2quater_earfcn_by_idx(integer earfcn_index) return uint16_t
{
	select (earfcn_index) {
	case (0) {
		/* E-ARFCN 111 is already added in the osmo-bsc.cfg */
		return 111;
	}
	case (1) {
		return 1;
	}
	case (2) {
		return 0;
	}
	case (3) {
		return 65535;
	}
	case else {
		return 23 * (earfcn_index - 3);
	}
	}
}

function f_test_si2quater(integer total_earfcns, template SystemInformationConfig expect_si,
			  template CellSelIndValue expect_cells := omit) runs on test_CT {

	f_init(0);

	/* E-ARFCN 111 is already added in the osmo-bsc.cfg, so only add more arfcns if total_earfcns > 1 */
	for (var integer i := 1; i < total_earfcns; i := i + 1) {
		f_bts_0_cfg(BSCVTY, {"si2quater neighbor-list add earfcn " & int2str(f_test_si2quater_earfcn_by_idx(i))
				     & " thresh-hi 20 thresh-lo 10 prio 3 qrxlv 22 meas 3"});
	}

	f_init_bts_and_check_sysinfo(0, expect_si := expect_si);

	if (not istemplatekind(expect_cells, "omit")) {
		/* Also check that RR Channel Release contains these EARFCNs.
		 * (copied code from TC_chan_rel_hard_clear_csfb) */
		var BSSAP_N_DATA_ind rx_di;
		var DchanTuple dt;

		dt := f_est_dchan('23'O, 23, '00010203040506'O);
		/* Send CommonID with some random PLMN (BSC doesn't take it into account
		 * yet when generating the EUTRAN neigh list in RR CHannel Release) */
		BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_CommonId('001019876543210'H, '323454'O)));

		/* Instruct BSC to clear channel */
		var BssmapCause cause := 0;
		BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommandCSFB(cause)));

		/* expect Clear Complete from BSC on A */
		BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_ClearComplete)) {
			/* release the SCCP connection */
			BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));
		}

		f_expect_chan_rel(dt.rsl_chan_nr, expect_rll_rel_req := false, expect_cells := expect_cells);
	}

	for (var integer i := 1; i < total_earfcns; i := i + 1) {
		f_bts_0_cfg(BSCVTY, {"si2quater neighbor-list del earfcn " & int2str(f_test_si2quater_earfcn_by_idx(i))});
	}
}

private function f_tr_si2quater_earfcns(integer count) return template SI2quaterRestOctetsList
{
	var template SI2quaterRestOctetsList si2quater := {};
	var integer si2quater_count := (count + 2) / 3;

	for (var integer i := 0; i < count; i := i + 1) {
		var integer earfcn := f_test_si2quater_earfcn_by_idx(i);
		var integer index := i / 3;
		var integer earfcn_index := i mod 3;
		if (index >= lengthof(si2quater)) {
			si2quater[index] := tr_SI2quaterRestOctets_EUTRAN(index := index, count := si2quater_count - 1);
		}
		si2quater[index].rel_additions.rel5.rel6.rel7.rel8.prio_eutran_params_desc.desc.eutran_params_desc.desc.repeated_neigh_cells[0].cell_desc_list[earfcn_index] := tr_EUTRAN_CellDesc_default(e_arfcn := earfcn);
	}

	return si2quater;
}

private function f_tr_rr_chan_rel_earfcns(integer count) return template CellSelIndValue
{
	var template CellSelIndValue_EUTRAN_Descrs cells := {};

	/* the lte neighbors must match the config & vty to pass this test */
	for (var integer i := 0; i < count; i := i + 1) {
		var integer earfcn := f_test_si2quater_earfcn_by_idx(i);
		cells[i] := tr_CellSelIndValue_EUTRAN_Descr(earfcn, '1'B, 3);
	}

	return tr_CellSelIndValue_EUTRAN(cells);
}

private function f_tc_si2quater_n_earfcns(integer n) runs on test_CT
{
	var template SystemInformationConfig sic := SystemInformationConfig_default;
	sic.si2quater := f_tr_si2quater_earfcns(n);
	var template CellSelIndValue cells := f_tr_rr_chan_rel_earfcns(n);
	f_test_si2quater(n, sic, cells);
}

testcase TC_si2quater_2_earfcns() runs on test_CT {
	f_tc_si2quater_n_earfcns(2);
	f_shutdown_helper();
}

testcase TC_si2quater_3_earfcns() runs on test_CT {
	f_tc_si2quater_n_earfcns(3);
	f_shutdown_helper();
}

testcase TC_si2quater_4_earfcns() runs on test_CT {
	f_tc_si2quater_n_earfcns(4);
	f_shutdown_helper();
}

testcase TC_si2quater_5_earfcns() runs on test_CT {
	f_tc_si2quater_n_earfcns(5);
	f_shutdown_helper();
}

testcase TC_si2quater_6_earfcns() runs on test_CT {
	f_tc_si2quater_n_earfcns(6);
	f_shutdown_helper();
}

testcase TC_si2quater_12_earfcns() runs on test_CT {
	f_tc_si2quater_n_earfcns(12);
	f_shutdown_helper();
}

testcase TC_si2quater_23_earfcns() runs on test_CT {
	f_tc_si2quater_n_earfcns(23);
	f_shutdown_helper();
}

testcase TC_si2quater_32_earfcns() runs on test_CT {
	f_tc_si2quater_n_earfcns(32);
	f_shutdown_helper();
}

testcase TC_si2quater_33_earfcns() runs on test_CT {
	f_tc_si2quater_n_earfcns(33);
	f_shutdown_helper();
}

testcase TC_si2quater_42_earfcns() runs on test_CT {
	f_tc_si2quater_n_earfcns(42);
	f_shutdown_helper();
}

testcase TC_si2quater_48_earfcns() runs on test_CT {
	f_tc_si2quater_n_earfcns(48);
	f_shutdown_helper();
}

/* verify the VTY error response when adding too many EARFCNs, and showing that osmo-bsc still sends 16 SI2quater with
 * 48 EARFCNs. */
testcase TC_si2quater_49_earfcns() runs on test_CT {
	var template SystemInformationConfig sic := SystemInformationConfig_default;
	sic.si2quater := f_tr_si2quater_earfcns(48); /* 48, not 49! */
	f_init(0);

	for (var integer i := 1; i < 48; i := i + 1) {
		f_bts_0_cfg(BSCVTY, {"si2quater neighbor-list add earfcn " & int2str(f_test_si2quater_earfcn_by_idx(i))
				     & " thresh-hi 20 thresh-lo 10 prio 3 qrxlv 22 meas 3"});
	}

	/* The 49th EARFCN no longer fits, expect VTY error */
	f_vty_enter_cfg_bts(BSCVTY, 0);
	var charstring vty_error;
	vty_error := f_vty_transceive_ret(BSCVTY,
		"si2quater neighbor-list add earfcn 70 thresh-hi 20 thresh-lo 10 prio 3 qrxlv 22 meas 3")
	f_vty_transceive(BSCVTY, "end");

	if (f_strstr(vty_error, "Unable to add ARFCN 70") >= 0) {
		log("Got expected VTY error: ", vty_error);
		setverdict(pass);
	} else {
		setverdict(fail, "Expected the 49th EUTRAN ARFCN to be rejected by vty config, got: ", vty_error);
	}

	f_init_bts_and_check_sysinfo(0, expect_si := sic);

	for (var integer i := 1; i < 48; i := i + 1) {
		f_bts_0_cfg(BSCVTY, {"si2quater neighbor-list del earfcn " & int2str(f_test_si2quater_earfcn_by_idx(i))});
	}
	f_shutdown_helper();
}

private function f_acc09_count_allowed(AccessControlClass acc) return uint8_t
{
	var uint8_t count := 0;
	for (var integer i := 5; i < 16; i := i + 1) {
		if (acc[i] == '0'B) { /* the list marks barred, we count allowed */
			count := count + 1;
		}
	}
	return count;
}

private function f_recv_next_si1(integer rsl_idx := 0) runs on test_CT return SystemInformationType1
{
	var ASP_RSL_Unitdata rx_rsl_ud;
	var SystemInformationType1 last_si1;

	timer T := 30.0;
	T.start;
	alt {
	[] IPA_RSL[rsl_idx][0].receive(tr_ASP_RSL_UD((tr_RSL_NO_BCCH_INFO,
						      tr_RSL_BCCH_INFO,
						      tr_RSL_NO_SACCH_FILL,
						      tr_RSL_SACCH_FILL))) -> value rx_rsl_ud {
		f_sysinfo_seen(rsl_idx, rx_rsl_ud.rsl);
		if (g_system_information[rsl_idx].si1 == omit) {
			repeat;
		}
		last_si1 := g_system_information[rsl_idx].si1;
		g_system_information[rsl_idx].si1 := omit;
		T.stop;
		}
	[] IPA_RSL[rsl_idx][0].receive { repeat; }
	[] T.timeout { setverdict(fail, "Timeout receiving next SI1"); }
	}
	return last_si1;
}

/* verify ACC rotate feature */
testcase TC_si_acc_rotate() runs on test_CT {
	var template SystemInformationConfig sic := SystemInformationConfig_default;
	var SystemInformationType1 last_si1;
	var AccessControlClass acc;
	var uint8_t count;
	var integer times_allowed[10] := { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

	f_init(0, guard_timeout := 60.0);

	f_bts_0_cfg(BSCVTY, {"rach access-control-class 5 barred",
			     "access-control-class-rotate 3",
			     "access-control-class-rotate-quantum 1"});

	/* Init and get first sysinfo */
	f_init_bts_and_check_sysinfo(0, expect_si := ?);

	for (var integer i:= 0; i < 20; i := i + 1) {
		last_si1 := f_recv_next_si1(0);
		acc := last_si1.rach_control.acc;
		count := f_acc09_count_allowed(acc);
		log("RSL: GOT SI1 ACC len=", count, ": ", acc);

		if (count != 3) {
			log("RSL: EXPECTED SI ACC len=3");
			setverdict(fail, "received SI does not match expectations");
			break;
		}

		for (var integer j := 0; j < 10; j := j + 1) {
			if (acc[16 - 1 - j] == '0'B) { /* the list marks barred, we count allowed */
				times_allowed[j] := times_allowed[j] + 1;
			}
		}
	}

	for (var integer j := 0; j < 10; j := j + 1) {
		log("ACC", j, " allowed ", times_allowed[j], " times" );
		if (j != 5 and times_allowed[j] < 3) {
			setverdict(fail, "ACC", j, " ERROR: allowed ", times_allowed[j], " < 1 times");
		} else if (j == 5 and times_allowed[j] > 0) {
			setverdict(fail, "ACC", j, " ERROR: allowed ", times_allowed[j], " > 0 times");
		}
	}

	f_bts_0_cfg(BSCVTY, {"access-control-class-rotate 10",
			     "rach access-control-class 5 allowed"});
	f_shutdown_helper();
}

/* verify ACC startup ramp+rotate feature */
testcase TC_si_acc_ramp_rotate() runs on test_CT {
	var template SystemInformationConfig sic := SystemInformationConfig_default;
	var SystemInformationType1 last_si1;
	var AccessControlClass acc;
	var ASP_RSL_Unitdata rx_rsl_ud;
	var uint8_t count;
	var uint8_t prev_count;
	var integer times_allowed[10] := { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

	f_init(0, guard_timeout := 80.0);

	f_bts_0_cfg(BSCVTY, {"rach access-control-class 4 barred",
			     "access-control-class-rotate 0",
			     "access-control-class-rotate-quantum 1",
			     "access-control-class-ramping",
			     "access-control-class-ramping-step-interval 5",
			     "access-control-class-ramping-step-size 5"});

	/* Init and get first sysinfo */
	f_init_bts_and_check_sysinfo(0, expect_si := ?);
	last_si1 := g_system_information[0].si1;
	acc := last_si1.rach_control.acc;
	count := f_acc09_count_allowed(acc);
	/* Adm subset size was set to 0 above, so wait until all ACC are barred */
	while (count > 0) {
		last_si1 := f_recv_next_si1(0);
		acc := last_si1.rach_control.acc;
		count := f_acc09_count_allowed(acc);
		log("RSL: wait len()=0: GOT SI1 ACC len=", count, ": ", acc);
	}

	/* Increase adm subset size, we should see ramping start up */
	f_bts_0_cfg(BSCVTY, {"access-control-class-rotate 10"});
	prev_count := 0;
	while (true) {
		last_si1 := f_recv_next_si1(0);
		acc := last_si1.rach_control.acc;
		count := f_acc09_count_allowed(acc);
		log("RSL: GOT SI1 ACC len=", count, ": ", acc);

		if (prev_count > count) {
			setverdict(fail, "ACC allowed count dropped while expecting grow: ", prev_count, " -> ", count);
			break;
		}

		if (count == 9) {
			break; /* Maximum reached (10 - 1 perm barred), done here */
		}

		prev_count := count;
	}

	setverdict(pass);

	f_bts_0_cfg(BSCVTY, {"access-control-class-rotate 10",
			     "rach access-control-class 4 allowed",
			     "no access-control-class-ramping"});
	f_shutdown_helper();
}

testcase TC_ctrl_msc_connection_status() runs on test_CT {
	var charstring ctrl_resp;

	f_init(1);

	/* See https://osmocom.org/issues/2729 */
	f_ctrl_get_exp(IPA_CTRL, "msc_connection_status", "connected");
	f_shutdown_helper();
}

testcase TC_ctrl_msc0_connection_status() runs on test_CT {
	var charstring ctrl_resp;

	f_init(1);

	f_ctrl_get_exp(IPA_CTRL, "msc.0.connection_status", "connected");
	f_shutdown_helper();
}

/* Verify correct stats on the number of configured and connected MSCs */
private function f_tc_stat_num_msc_connected_msc_connhdlr(integer expect_num_msc_connected) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var StatsDExpects expect := {
		{ name := "TTCN3.bsc.0.num_msc.connected", mtype := "g", min := expect_num_msc_connected, max := expect_num_msc_connected },
		{ name := "TTCN3.bsc.0.num_msc.total", mtype := "g", min := NUM_MSC, max := NUM_MSC }
	};
	f_statsd_expect(expect);
}

private function f_tc_stat_num_msc_connected_test_ct(void_fn tc_fn, integer nr_msc) runs on test_CT
{
	var MSC_ConnHdlr vc_conn;

	f_init(nr_bts := 1, handler_mode := true, nr_msc := nr_msc);
	f_sleep(1.0);
	vc_conn := f_start_handler(tc_fn);
	vc_conn.done;

	/* Also verify stat exposed on CTRL interface */
	f_ctrl_get_exp(IPA_CTRL, "stat_item.last.bsc.0.num_msc:connected", int2str(nr_msc));
	f_ctrl_get_exp(IPA_CTRL, "stat_item.last.bsc.0.num_msc:total", int2str(NUM_MSC));

	f_shutdown_helper();
}

/* Verify that when 1 MSC is active, that num_msc:connected reports 1. */
private function f_tc_stat_num_msc_connected_1(charstring id) runs on MSC_ConnHdlr {
	f_tc_stat_num_msc_connected_msc_connhdlr(1);
}
testcase TC_stat_num_msc_connected_1() runs on test_CT {
	f_tc_stat_num_msc_connected_test_ct(refers(f_tc_stat_num_msc_connected_1), 1);
}

/* Verify that when 2 MSCs are active, that num_msc:connected reports 2. */
private function f_tc_stat_num_msc_connected_2(charstring id) runs on MSC_ConnHdlr {
	f_tc_stat_num_msc_connected_msc_connhdlr(2);
}
testcase TC_stat_num_msc_connected_2() runs on test_CT {
	f_tc_stat_num_msc_connected_test_ct(refers(f_tc_stat_num_msc_connected_2), 2);
}

/* Verify that when 3 MSCs are active, that num_msc:connected reports 3. */
private function f_tc_stat_num_msc_connected_3(charstring id) runs on MSC_ConnHdlr {
	f_tc_stat_num_msc_connected_msc_connhdlr(3);
}
testcase TC_stat_num_msc_connected_3() runs on test_CT {
	f_tc_stat_num_msc_connected_test_ct(refers(f_tc_stat_num_msc_connected_3), 3);
}

/* Verify correct stats on the number of configured and connected MSCs */
private function f_tc_stat_num_bts_connected_msc_connhdlr(integer expect_num_bts_connected) runs on MSC_ConnHdlr {
	var integer num_trx_connected := 0;
	var integer num_trx_total := 0;

	for (var integer i := 0; i < lengthof(c_BtsParams); i := i + 1) {
		var integer trx_num := c_BtsParams[i].trx_num;
		num_trx_total := num_trx_total + trx_num;
		if (i < expect_num_bts_connected) {
			num_trx_connected := num_trx_connected + trx_num;
		}
	}

	var StatsDExpects expect := {
		{ name := "TTCN3.bsc.0.num_bts.oml_connected", mtype := "g", min := expect_num_bts_connected, max := NUM_BTS_CFG },
		{ name := "TTCN3.bsc.0.num_bts.all_trx_rsl_connected", mtype := "g", min := expect_num_bts_connected, max := expect_num_bts_connected },
		{ name := "TTCN3.bsc.0.num_bts.total", mtype := "g", min := NUM_BTS_CFG, max := NUM_BTS_CFG },
		{ name := "TTCN3.bsc.0.num_trx.rsl_connected", mtype := "g", min := num_trx_connected, max := num_trx_connected },
		{ name := "TTCN3.bsc.0.num_trx.total", mtype := "g", min := num_trx_total, max := num_trx_total }
	};

	g_pars := f_gen_test_hdlr_pars();
	f_statsd_expect(expect);
}

private function f_tc_stat_num_bts_connected_test_ct(void_fn tc_fn, integer nr_bts) runs on test_CT {
	var integer num_trx_connected := 0;
	var integer num_trx_total := 0;
	var MSC_ConnHdlr vc_conn;

	f_init(nr_bts := nr_bts, handler_mode := true, nr_msc := 1);
	f_sleep(1.0);
	vc_conn := f_start_handler(tc_fn);
	vc_conn.done;

	for (var integer i := 0; i < lengthof(c_BtsParams); i := i + 1) {
		var integer trx_num := c_BtsParams[i].trx_num;
		num_trx_total := num_trx_total + trx_num;
		if (i < nr_bts) {
			num_trx_connected := num_trx_connected + trx_num;
		}
	}

	/* Also verify stat exposed on CTRL interface */
	f_ctrl_get_exp(IPA_CTRL, "stat_item.last.bsc.0.num_bts:all_trx_rsl_connected", int2str(nr_bts));
	f_ctrl_get_exp(IPA_CTRL, "stat_item.last.bsc.0.num_bts:total", int2str(NUM_BTS_CFG));
	f_ctrl_get_exp(IPA_CTRL, "stat_item.last.bsc.0.num_trx:rsl_connected", int2str(num_trx_connected));
	f_ctrl_get_exp(IPA_CTRL, "stat_item.last.bsc.0.num_trx:total", int2str(num_trx_total));

	/* Verify rf_states exposed on CTRL interface */
	var charstring expect_net_rf_states := "";
	for (var integer i := 0; i < NUM_BTS_CFG; i := i + 1) {
		var charstring expect_bts_rf_states := "";

		for (var integer j := 0; j < c_BtsParams[i].trx_num; j := j + 1) {
			expect_bts_rf_states := expect_bts_rf_states &
						int2str(i) & "," & int2str(j) & ",";
			if (i < NUM_BTS) {
				/* In these tests, OML for the first NUM_BTS are always connected via osmo-bts-omldummy */
				expect_bts_rf_states := expect_bts_rf_states & "operational,unlocked,";
			} else {
				/* For remaining i < NUM_BTS_CFG, OML is not connected, i.e. inoperational */
				expect_bts_rf_states := expect_bts_rf_states & "inoperational,locked,";
			}
			/* The RF policy is still global in osmo-bsc, i.e. always "on" */
			expect_bts_rf_states := expect_bts_rf_states & "on,";
			if (i < nr_bts) {
				/* For BTS where RSL is connected, the RSL state will be "up" */
				expect_bts_rf_states := expect_bts_rf_states & "rsl-up;";
			} else {
				expect_bts_rf_states := expect_bts_rf_states & "rsl-down;";
			}
		}

		f_ctrl_get_exp(IPA_CTRL, "bts." & int2str(i) & ".rf_states", expect_bts_rf_states);
		expect_net_rf_states := expect_net_rf_states & expect_bts_rf_states;
	}
	f_ctrl_get_exp(IPA_CTRL, "rf_states", expect_net_rf_states);

	f_shutdown_helper();
}

/* Verify that when 1 BTS is connected, that num_{bts,trx}:*_connected reports 1. */
private function f_tc_stat_num_bts_connected_1(charstring id) runs on MSC_ConnHdlr {
	f_tc_stat_num_bts_connected_msc_connhdlr(1);
}
testcase TC_stat_num_bts_connected_1() runs on test_CT {
	f_tc_stat_num_bts_connected_test_ct(refers(f_tc_stat_num_bts_connected_1), 1);
}

/* Verify that when 2 BTS is connected, that num_{bts,trx}:*_connected reports 2. */
private function f_tc_stat_num_bts_connected_2(charstring id) runs on MSC_ConnHdlr {
	f_tc_stat_num_bts_connected_msc_connhdlr(2);
}
testcase TC_stat_num_bts_connected_2() runs on test_CT {
	f_tc_stat_num_bts_connected_test_ct(refers(f_tc_stat_num_bts_connected_2), 2);
}

/* Verify that when 3 BTS is connected, that num_{bts,trx}:*_connected reports 3. */
private function f_tc_stat_num_bts_connected_3(charstring id) runs on MSC_ConnHdlr {
	f_tc_stat_num_bts_connected_msc_connhdlr(3);
}
testcase TC_stat_num_bts_connected_3() runs on test_CT {
	f_tc_stat_num_bts_connected_test_ct(refers(f_tc_stat_num_bts_connected_3), 3);
}

testcase TC_ctrl() runs on test_CT {
	var charstring ctrl_resp;

	f_init(1);

	/* all below values must match the osmo-bsc.cfg config file used */

	f_ctrl_get_exp(IPA_CTRL, "mcc", "001");
	f_ctrl_get_exp(IPA_CTRL, "mnc", "01");
	f_ctrl_get_exp(IPA_CTRL, "number-of-bts", "4");

	var integer bts_nr := 0;
	f_ctrl_get_exp_bts(IPA_CTRL, bts_nr, "location-area-code", "1");
	f_ctrl_get_exp_bts(IPA_CTRL, bts_nr, "cell-identity", "0");
	f_ctrl_get_exp_bts(IPA_CTRL, bts_nr, "oml-connection-state", "connected");
	f_ctrl_get_exp_bts(IPA_CTRL, bts_nr, "gprs-mode", "gprs");
	f_ctrl_get_exp_bts(IPA_CTRL, bts_nr, "rf_state", "operational,unlocked,on");
	f_ctrl_get_exp_trx(IPA_CTRL, bts_nr, 0, "arfcn", "871");
	f_ctrl_get_exp_trx(IPA_CTRL, bts_nr, 0, "max-power-reduction", "20");

	var integer uptime := str2int(f_ctrl_get_bts(IPA_CTRL, bts_nr, "oml-uptime"));
	f_sleep(2.0);
	if (str2int(f_ctrl_get_bts(IPA_CTRL, bts_nr, "oml-uptime")) < uptime+1) {
		setverdict(fail, "oml-uptime not incrementing as expected");
	}
	/* TODO: Disconnect RSL, imply that OML is disconnected and check for uptime zero? */

	f_ctrl_get_exp_ratectr_abs(IPA_CTRL, "bsc", 0, "paging:attempted", 0);

	f_shutdown_helper();
}

/* Verify that Upon receival of SET "location", BSC forwards a TRAP
  "location-state" over the SCCPlite IPA conn */
testcase TC_ctrl_location() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var integer bts_nr := 0;

	f_init(1, true);
	f_sleep(1.0);

	f_ctrl_set_bts(IPA_CTRL, bts_nr, "location", "1234567,fix3d,0.340000,0.560000,0.780000");
	f_ctrl_exp_trap(SCCPLITE_IPA_CTRL, "bts." & int2str(bts_nr) & ".location-state",
			"1234567,fix3d,0.340000,0.560000,0.780000,operational,unlocked,on,001,01");

	f_ctrl_set(SCCPLITE_IPA_CTRL, "rf_locked", "1");
	f_sleep(2.0);

	f_ctrl_set_bts(IPA_CTRL, bts_nr, "location", "1234888,fix3d,0.350000,0.570000,0.790000");
	f_ctrl_exp_trap(SCCPLITE_IPA_CTRL, "bts." & int2str(bts_nr) & ".location-state",
			"1234888,fix3d,0.350000,0.570000,0.790000,operational,locked,off,001,01");

	/* should match the one from  config */
	f_ctrl_set(SCCPLITE_IPA_CTRL, "rf_locked", "0");

	f_shutdown_helper();
}


/***********************************************************************
 * Paging Testing
 ***********************************************************************/

type record Cell_Identity {
	GsmMcc		mcc,
	GsmMnc		mnc,
	GsmLac		lac,
	GsmCellId	ci
};
private const Cell_Identity cid := { '001'H, '01'H, 1, 0 };
private const Cell_Identity unknown_cid := { '678'H, 'f90'H, 1, 0 };

type set of integer BtsIdList;

private function f_bts_in_list(integer bts_id, BtsIdList bts_ids) return boolean {
	for (var integer j := 0; j < sizeof(bts_ids); j := j + 1) {
		if (bts_id == bts_ids[j]) {
			return true;
		}
	}
	return false;
}

/* core paging test helper function; used by most paging test cases */
private function f_pageing_helper(hexstring imsi,
				  template BSSMAP_FIELD_CellIdentificationList cid_list,
				  BtsIdList bts_ids := { 0 },
				  template RSL_ChanNeeded rsl_chneed := omit,
				  template (omit) OCT4 tmsi := omit) runs on test_CT
{
	var template BSSMAP_IE_ChannelNeeded bssmap_chneed;
	var template MobileIdentityV mi;
	var RSL_Message rx_rsl;
	var integer paging_group := hex2int(imsi[lengthof(imsi)-1]);
	var integer i;

	f_init();

	/* Clear the queue, it might still contain stuff like BCCH FILLING */
	for (i := 0; i < NUM_BTS; i := i + 1) {
		IPA_RSL[i][0].clear;
	}

	if (isvalue(rsl_chneed)) {
		/* The values of 08.08 3.2.2.36 and 08.58 9.3.40 are luckily identical */
		bssmap_chneed := ts_BSSMAP_IE_ChanNeeded(int2bit(enum2int(valueof(rsl_chneed)),2));
	} else {
		bssmap_chneed := omit;
	}

	BSSAP.send(ts_BSSAP_UNITDATA_req(g_bssap[0].sccp_addr_peer, g_bssap[0].sccp_addr_own,
					 ts_BSSMAP_Paging(imsi, cid_list, tmsi, bssmap_chneed)));

	if (not istemplatekind(tmsi, "omit")) {
		mi := t_MI_TMSI(tmsi);
	} else {
		mi := tr_MI_IMSI(imsi);
	}

	for (i := 0; i < sizeof(bts_ids); i := i + 1) {
		rx_rsl := f_exp_ipa_rx(tr_RSL_PAGING_CMD(mi), idx := {bts_ids[i], 0});
		/* check channel type, paging group */
		if (rx_rsl.ies[1].body.paging_group != paging_group) {
			setverdict(fail, "Paging for wrong paging group");
		}
		if (ispresent(rsl_chneed) and
		    rx_rsl.ies[3].body.chan_needed.chan_needed != valueof(rsl_chneed)) {
			setverdict(fail, "RSL Channel Needed != BSSMAP Channel Needed");
		}
	}
	f_sleep(2.0);
	/* do a quick check on all not-included BTSs if they received paging */
	for (i := 0; i < NUM_BTS; i := i + 1) {
		timer T := 0.1;
		if (f_bts_in_list(i, bts_ids)) {
			continue;
		}
		T.start;
		alt {
		[] IPA_RSL[i][0].receive(tr_ASP_RSL_UD(tr_RSL_PAGING_CMD(mi))) {
			setverdict(fail, "Paging on BTS ", i, " which is not part of ", bts_ids);
			}
		[] IPA_RSL[i][0].receive { repeat; }
		[] T.timeout { }
		}
	}

	setverdict(pass);
}

const BtsIdList c_BtsId_all := { 0, 1, 2 };
const BtsIdList c_BtsId_none := { };
const BtsIdList c_BtsId_LAC1 := { 0, 1 };
const BtsIdList c_BtsId_LAC2 := { 2 };

/* PAGING by IMSI + TMSI */
testcase TC_paging_imsi_nochan() runs on test_CT {
	var BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := valueof(ts_BSSMAP_CIL_noCell);
	f_pageing_helper('001010100000001'H, cid_list, c_BtsId_all, omit, omit);
	f_shutdown_helper();
}

/* PAGING by IMSI + TMSI */
testcase TC_paging_tmsi_nochan() runs on test_CT {
	var BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := valueof(ts_BSSMAP_CIL_noCell);
	f_pageing_helper('001010100000001'H, cid_list, c_BtsId_all, omit, 'A1B2C301'O);
	f_shutdown_helper();
}

/* Paging with different "channel needed' values */
testcase TC_paging_tmsi_any() runs on test_CT {
	var BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := valueof(ts_BSSMAP_CIL_noCell);
	f_pageing_helper('001010100000002'H, cid_list, c_BtsId_all, RSL_CHANNEED_ANY, 'A1B2C302'O);
	f_shutdown_helper();
}
testcase TC_paging_tmsi_sdcch() runs on test_CT {
	var BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := valueof(ts_BSSMAP_CIL_noCell);
	f_pageing_helper('001010100000003'H, cid_list, c_BtsId_all, RSL_CHANNEED_SDCCH, 'A1B2C303'O);
	f_shutdown_helper();
}
testcase TC_paging_tmsi_tch_f() runs on test_CT {
	var BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := valueof(ts_BSSMAP_CIL_noCell);
	f_pageing_helper('001010000000004'H, cid_list, c_BtsId_all, RSL_CHANNEED_TCH_F, 'A1B2C304'O);
	f_shutdown_helper();
}
testcase TC_paging_tmsi_tch_hf() runs on test_CT {
	var BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := valueof(ts_BSSMAP_CIL_noCell);
	f_pageing_helper('001010000000005'H, cid_list, c_BtsId_all, RSL_CHANNEED_TCH_ForH, 'A1B2C305'O);
	f_shutdown_helper();
}

/* Paging by CGI */
testcase TC_paging_imsi_nochan_cgi() runs on test_CT {
	var template BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := { cIl_CGI := { ts_BSSMAP_CI_CGI(cid.mcc, cid.mnc, cid.lac, cid.ci) } };
	f_pageing_helper('001010000000006'H, cid_list, { 0 });
	f_shutdown_helper();
}

/* Paging by LAC+CI */
testcase TC_paging_imsi_nochan_lac_ci() runs on test_CT {
	var template BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := { cIl_LAC_CI := { ts_BSSMAP_CI_LAC_CI(cid.lac, cid.ci) } };
	f_pageing_helper('001010000000007'H, cid_list, { 0 });
	f_shutdown_helper();
}

/* Paging by CI */
testcase TC_paging_imsi_nochan_ci() runs on test_CT {
	var template BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := { cIl_CI := { ts_BSSMAP_CI_CI(cid.ci) } };
	f_pageing_helper('001010000000008'H, cid_list, { 0 });
	f_shutdown_helper();
}

/* Paging by LAI */
testcase TC_paging_imsi_nochan_lai() runs on test_CT {
	var template BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := { cIl_LAI := { ts_BSSMAP_CI_LAI(cid.mcc, cid.mnc, cid.lac) } };
	f_pageing_helper('001010000000009'H, cid_list, c_BtsId_LAC1);
	f_shutdown_helper();
}

/* Paging by LAC */
testcase TC_paging_imsi_nochan_lac() runs on test_CT {
	var template BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := { cIl_LAC := { ts_BSSMAP_CI_LAC(cid.lac) } };
	f_pageing_helper('001010000000010'H, cid_list, c_BtsId_LAC1);
	f_shutdown_helper();
}

/* Paging by "all in BSS" */
testcase TC_paging_imsi_nochan_all() runs on test_CT {
	var template BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := { cIl_allInBSS := ''O };
	f_pageing_helper('001010000000011'H, cid_list, c_BtsId_all);
	f_shutdown_helper();
}

/* Paging by PLMN+LAC+RNC; We do not implement this; Verify nothing is paged */
testcase TC_paging_imsi_nochan_plmn_lac_rnc() runs on test_CT {
	var template BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := { cIl_PLMN_LAC_RNC := { ts_BSSMAP_CI_PLMN_LAC_RNC(cid.mcc, cid.mnc, cid.lac, 12) } };
	f_pageing_helper('001010000000012'H, cid_list, c_BtsId_none);
	f_shutdown_helper();
}

/* Paging by RNC; We do not implement this; Verify nothing is paged */
testcase TC_paging_imsi_nochan_rnc() runs on test_CT {
	var template BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := { cIl_RNC := { int2oct(13, 2) } };
	f_pageing_helper('001010000000013'H, cid_list, c_BtsId_none);
	f_shutdown_helper();
}

/* Paging by LAC+RNC; We do not implement; Verify nothing is paged */
testcase TC_paging_imsi_nochan_lac_rnc() runs on test_CT {
	var template BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := { cIl_LAC_RNC := { ts_BSSMAP_CI_LAC_RNC(cid.lac, 14) } };
	f_pageing_helper('001010000000014'H, cid_list, c_BtsId_none);
	f_shutdown_helper();
}

/* Paging on multiple cells (multiple entries in list): Verify all of them page */
testcase TC_paging_imsi_nochan_lacs() runs on test_CT {
	var template BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := { cIl_LAC := { ts_BSSMAP_CI_LAC(1), ts_BSSMAP_CI_LAC(2) } };
	f_pageing_helper('001010000000015'H, cid_list, c_BtsId_all);
	f_shutdown_helper();
}

/* Paging on empty list: Verify none of them page */
testcase TC_paging_imsi_nochan_lacs_empty() runs on test_CT {
	var template BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := { cIl_LAC := { } };
	f_pageing_helper('001010000000016'H, cid_list, c_BtsId_none);
	f_shutdown_helper();
}

/* Paging by CGI with unknown MCC/MNC: Verify nothing is paged. */
testcase TC_paging_imsi_nochan_cgi_unknown_cid() runs on test_CT {
	var template BSSMAP_FIELD_CellIdentificationList cid_list;
	cid_list := { cIl_CGI := { ts_BSSMAP_CI_CGI(unknown_cid.mcc, unknown_cid.mnc, unknown_cid.lac, unknown_cid.ci) } };
	f_pageing_helper('001010000000006'H, cid_list, c_BtsId_none);
	f_shutdown_helper();
}

/* Verify paging retransmission interval + count */
/* Verify paging stops after channel establishment */
/* Test behavior under paging overload */

/* Verify PCH load */
testcase TC_paging_imsi_load() runs on test_CT {
	var BSSMAP_FIELD_CellIdentificationList cid_list;
	timer T := 4.0;
	timer T_retrans := 1.0;
	cid_list := valueof(ts_BSSMAP_CIL_noCell);
	f_pageing_helper('001010123456789'H, cid_list, c_BtsId_all);

	/* tell BSC there is no paging space anymore */
	f_ipa_tx(ts_RSL_PAGING_LOAD_IND(0));
	f_sleep(0.2);
	IPA_RSL[0][0].clear;

	/* Wait for 4 seconds if any more PAGING CMD are received on RSL. Normally,
	 * there would be 8 retransmissions during 4 seconds */
	T.start;
	T_retrans.start;
	alt {
	[] IPA_RSL[0][0].receive(tr_ASP_RSL_UD(tr_RSL_PAGING_CMD(?))) {
		setverdict(fail, "Received PAGING after LOAD_IND(0)");
		mtc.stop;
		}
	[] T_retrans.timeout {
		/* re-trnsmit the zero-space LOAD IND to avoid BSC 'auto credit' */
		f_ipa_tx(ts_RSL_PAGING_LOAD_IND(0));
		T_retrans.start;
		repeat;
		}
	[] T.timeout {
		setverdict(pass);
		}
	}

	f_shutdown_helper();
}

/* Verify Paging Counter */
testcase TC_paging_counter() runs on test_CT {
	var BSSMAP_FIELD_CellIdentificationList cid_list;
	timer T := 4.0;
	var integer i;
	var integer paging_attempted_bsc;
	var integer paging_attempted_bts[NUM_BTS];
	var integer paging_expired_bsc;
	var integer paging_expired_bts[NUM_BTS];
	cid_list := valueof(ts_BSSMAP_CIL_noCell);

	f_init();

	/* read counters before paging */
	paging_attempted_bsc := f_ctrl_get_ratectr_abs(IPA_CTRL, "bsc", 0, "paging:attempted");
	if (Misc_Helpers.f_osmo_repo_is("nightly")) { /* osmo-bsc > 1.8.0 */
		paging_expired_bsc := f_ctrl_get_ratectr_abs(IPA_CTRL, "bsc", 0, "paging:expired");
	}
	for (i := 0; i < NUM_BTS; i := i+1) {
		paging_attempted_bts[i] := f_ctrl_get_ratectr_abs(IPA_CTRL, "bts", i, "paging:attempted");
		paging_expired_bts[i] := f_ctrl_get_ratectr_abs(IPA_CTRL, "bts", i, "paging:expired");
	}

	f_pageing_helper('001230000000001'H, cid_list, c_BtsId_all);

	/* expect the attempted pages on BSC and each BTSs to have incremented by one */
	f_ctrl_get_exp_ratectr_abs(IPA_CTRL, "bsc", 0, "paging:attempted", paging_attempted_bsc+1);
	for (i := 0; i < NUM_BTS; i := i+1) {
		f_ctrl_get_exp_ratectr_abs(IPA_CTRL, "bts", i, "paging:attempted",
						paging_attempted_bts[i]+1);
	}

	/* assume that 12s later the paging on all BTSs have expired and hence incremented by 1 */
	f_sleep(12.0);
	if (Misc_Helpers.f_osmo_repo_is("nightly")) { /* osmo-bsc > 1.8.0 */
		f_ctrl_get_exp_ratectr_abs(IPA_CTRL, "bsc", 0, "paging:expired", paging_expired_bsc+1);
	}
	for (i := 0; i < NUM_BTS; i := i+1) {
		f_ctrl_get_exp_ratectr_abs(IPA_CTRL, "bts", i, "paging:expired",
						paging_expired_bts[i]+1);
	}

	f_shutdown_helper();
}


/* Verify paging stops after A-RESET */
testcase TC_paging_imsi_a_reset() runs on test_CT {
	var BSSMAP_FIELD_CellIdentificationList cid_list;
	timer T := 3.0;
	cid_list := valueof(ts_BSSMAP_CIL_noCell);
	f_pageing_helper('001010123456789'H, cid_list, c_BtsId_all);

	/* Perform a BSSMAP Reset and wait for ACK */
	BSSAP.send(ts_BSSAP_UNITDATA_req(g_bssap[0].sccp_addr_peer, g_bssap[0].sccp_addr_own, ts_BSSMAP_Reset(0, g_osmux_enabled)));
	alt {
	[] BSSAP.receive(tr_BSSAP_UNITDATA_ind(g_bssap[0].sccp_addr_own, g_bssap[0].sccp_addr_peer, tr_BSSMAP_ResetAck(g_osmux_enabled))) { }
	[] BSSAP.receive { repeat; }
	}

	/* Wait to avoid a possible race condition if a paging message is
	 * received right before the reset ACK. */
	f_sleep(0.2);

	/* Clear the queue, it might still contain stuff like BCCH FILLING */
	for (var integer i := 0; i < sizeof(IPA_RSL); i := i+1) {
		IPA_RSL[i][0].clear;
	}

	/* Wait for 3 seconds if any more PAGING CMD are received on RSL */
	T.start;
	alt {
	[] IPA_RSL[0][0].receive(tr_ASP_RSL_UD(tr_RSL_PAGING_CMD(?))) {
		setverdict(fail, "Received PAGING after A-RESET");
		mtc.stop;
		}
	[] IPA_RSL[1][0].receive(tr_ASP_RSL_UD(tr_RSL_PAGING_CMD(?))) {
		setverdict(fail, "Received PAGING after A-RESET");
		mtc.stop;
		}
	[] IPA_RSL[2][0].receive(tr_ASP_RSL_UD(tr_RSL_PAGING_CMD(?))) {
		setverdict(fail, "Received PAGING after A-RESET");
		mtc.stop;
		}
	[] T.timeout {
		setverdict(pass);
		}
	}

	f_shutdown_helper();
}

/* Verify how we handle unsolicited Paging Response. In case of an unsolicit
 * paging response we can not know which MSC is in charge, so we will blindly
 * pick the first configured MSC. This behavior is required in order to make
 * MT-CSFB calls working because in those cases the BSC can not know that the
 * MSC has already paged the subscriver via SGs. So any MT-CSFB call will look
 * like an unsolicited Paging Response to the MSC.
 */
testcase TC_paging_resp_unsol() runs on test_CT {

	f_init(1);
	timer T := 5.0;

	var BSSAP_N_CONNECT_ind rx_c_ind;
	var DchanTuple dt;
	var PDU_ML3_MS_NW l3 := valueof(ts_PAG_RESP(valueof(ts_MI_IMSI_LV('001010008880018'H))));
	var octetstring rr_pag_resp := enc_PDU_ML3_MS_NW(l3);

	/* Send CHAN RQD and wait for allocation; acknowledge it */
	dt.rsl_chan_nr := f_chreq_act_ack();
	dt.idx := {0, 0};

	/* Send unsolicited Paging response (no matching Paging CMD stored in BSC) */
	f_ipa_tx(ts_RSL_EST_IND(dt.rsl_chan_nr, valueof(ts_RslLinkID_DCCH(0)), enc_PDU_ML3_MS_NW(l3)));


	/* Expevct a CR with a matching Paging response on the A-Interface */
	T.start;
	alt {
	[] BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(rr_pag_resp))) -> value rx_c_ind {
		setverdict(pass);
		dt.sccp_conn_id := rx_c_ind.connectionId;
		BSSAP.send(ts_BSSAP_CONNECT_res(dt.sccp_conn_id));
		}
	[] BSSAP.receive {
		setverdict(fail, "Received unexpected message on A-Interface!");
		}
	[] T.timeout {
		setverdict(fail, "Received nothing on A-Interface!");
		}
	}

	f_perform_clear_test_ct(dt);
	f_shutdown_helper();
}

/* Verify BSC can schedule N paging requests under one minute if BTS buffer is good enough */
function f_TC_paging_Nreq(integer num_subscribers, boolean send_pag_load_ind) runs on test_CT {
	var ASP_RSL_Unitdata rx_rsl_ud;
	var Hexstrings imsis := {};
	var Booleans rx_paging_done := {};
	var integer rx_paging_num := 0;
	var integer i;
	timer T_rx := 60.0;
	timer T_load_ind := 1.0;

	for (i := 0; i < num_subscribers; i := i + 1) {
		imsis := imsis & {f_gen_imsi(i)};
		rx_paging_done := rx_paging_done & { false };
	}

	f_init(1, guard_timeout := 100.0);

	/* Clear the queue, it might still contain stuff like BCCH FILLING */
	IPA_RSL[0][0].clear;
	if (send_pag_load_ind) {
		/* Tell there's plenty of space at the BTS (UINT16_MAX): */
		f_ipa_tx(ts_RSL_PAGING_LOAD_IND(65535));
	}

	for (i := 0; i < num_subscribers; i := i + 1) {
		/* Page on LAC-CI of BTS0: */
		BSSAP.send(ts_BSSAP_UNITDATA_req(g_bssap[0].sccp_addr_peer, g_bssap[0].sccp_addr_own,
			   ts_BSSMAP_Paging(imsis[i], valueof(ts_BSSMAP_CIL_LAC_CI({ts_BSSMAP_CI_LAC_CI(1, 0)})),
			   omit, omit)));
	}

	T_rx.start;
	T_load_ind.start;
	alt {
	[] IPA_RSL[0][0].receive(tr_ASP_RSL_UD(tr_RSL_PAGING_CMD(?), IPAC_PROTO_RSL_TRX0)) -> value rx_rsl_ud {
		var hexstring imsi := rx_rsl_ud.rsl.ies[2].body.ms_identity.mobileIdentityV.oddEvenInd_identity.imsi.digits;
		var hexstring imsi_suffix := substr(imsi, lengthof(imsi)-6, 6);
		var charstring imsi_str := hex2str(imsi_suffix);
		var integer imsi_idx := str2int(imsi_str);
		if (rx_paging_done[imsi_idx] == false) {
			rx_paging_done[imsi_idx] := true;
			rx_paging_num := rx_paging_num + 1;
		} else {
			setverdict(fail, "Retrans of ", imsi_str, " happened before Rx initial trans for all reqs. rx_paging_num=", rx_paging_num);
			mtc.stop;
		}
		if (rx_paging_num < num_subscribers) {
			repeat;
		}
		}
	[] IPA_RSL[0][0].receive { repeat; }
	[] T_load_ind.timeout {
		log("[CCH Load Ind timer] received paging requests so far: ", rx_paging_num);
		if (send_pag_load_ind) {
			f_ipa_tx(ts_RSL_PAGING_LOAD_IND(40));
		}
		T_load_ind.start;
		repeat;
		}
	[] T_rx.timeout {
		setverdict(fail, "Timeout expecting paging requests, so far ", rx_paging_num);
		mtc.stop;
		}
	}

	/* Drop OML connection to have all paging requests flushed: */
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_shutdown_helper();
}
/* Verify BSC can schedule 500 paging requests under one minute if BTS buffer is good enough */
testcase TC_paging_500req() runs on test_CT {
	f_TC_paging_Nreq(500, true);
}
/* Same as TC_paging_500req, but without sending CCCH Load Indication, which
 * means BTS is always under CCH Load Threshold, aka capable of sending tons of requests.
 * Since No CCCH Load Ind, BSC uses a conservative estimation of BTS load, which
 * for current config yields ~8req/sec, so 480req/min maximum. */
testcase TC_paging_450req_no_paging_load_ind() runs on test_CT {
	f_TC_paging_Nreq(450, false);
}

/* Test RSL link drop causes counter increment */
testcase TC_rsl_drop_counter() runs on test_CT {
	var integer rsl_fail;

	f_init(1);

	rsl_fail := f_ctrl_get_ratectr_abs(IPA_CTRL, "bts", 0, "rsl_fail");

	f_ipa_rsl_stop(bts[0][0].rsl);

	f_ctrl_get_exp_ratectr_abs(IPA_CTRL, "bts", 0, "rsl_fail", rsl_fail+1);

	f_shutdown_helper();
}

/* TODO: Test OML link drop causes counter increment */

/* The body of TC_rsl_unknown_unit_id() and TC_oml_unknown_unit_id() tests. */
function f_ipa_unknown_unit_id(integer mp_bsc_ipa_port) runs on test_CT return boolean {
	var IPA_Client client;
	timer T := 10.0;

	client.id := "IPA-BTS0-TRX0-RSL";
	client.vc_IPA := IPA_Emulation_CT.create(client.id & "-IPA") alive;
	client.ccm_pars := c_IPA_default_ccm_pars;
	client.ccm_pars.name := "Osmocom TTCN-3 BTS Simulator";
	client.ccm_pars.unit_id := "99/0/0"; /* value which is unknown at BTS */

	f_ipa_ctrl_start_client(mp_bsc_ip, mp_bsc_ctrl_port);

	f_init_mgcp("VirtMSC");

	/* start RSL/OML connection (XXX re-uses RSL port/protocol definitions for OML) */
	map(client.vc_IPA:IPA_PORT, system:IPA);
	connect(client.vc_IPA:IPA_RSL_PORT, self:IPA_RSL[0][0]);
	client.vc_IPA.start(IPA_Emulation.main_client(mp_bsc_ip, mp_bsc_ipa_port, "", 10000, client.ccm_pars));

	/* wait for IPA OML link to connect and then disconnect */
	T.start;
	alt {
	[] IPA_RSL[0][0].receive(tr_ASP_IPA_EV(ASP_IPA_EVENT_DOWN)) {
		T.stop;
		return true;
	}
	[] IPA_RSL[0][0].receive { repeat }
	[] T.timeout {
		return false;
		}
	}
	return false;
}

/* BSC should close an RSL connection from a BTS with unknown unit ID (OS#2714). */
testcase TC_rsl_unknown_unit_id() runs on test_CT {
	if (f_ipa_unknown_unit_id(mp_bsc_rsl_port)) {
		setverdict(pass);
	} else {
		setverdict(fail, "Timeout RSL waiting for connection to close");
	}
	f_shutdown_helper();
}


/* BSC should close an RSL connection from a BTS with unknown unit ID (OS#2714). */
testcase TC_oml_unknown_unit_id() runs on test_CT {
	if (f_ipa_unknown_unit_id(mp_bsc_oml_port)) {
		setverdict(pass);
	} else {
		setverdict(fail, "Timeout OML waiting for connection to close");
	}
	f_shutdown_helper();
}


/***********************************************************************
 * "New world" test cases using RSL_Emulation + RAN_Emulation
 ***********************************************************************/

import from RAN_Emulation all;
import from BSSAP_LE_Emulation all;
import from RSL_Emulation all;
import from MSC_ConnectionHandler all;

type function void_fn(charstring id) runs on MSC_ConnHdlr;

/* helper function to create and connect a MSC_ConnHdlr component
 * TODO: allow connecting to TRX1..N, not only TRX0 */
private function f_connect_handler(inout MSC_ConnHdlr vc_conn, integer bssap_idx := 0) runs on test_CT {
	connect(vc_conn:RAN, g_bssap[bssap_idx].vc_RAN:PROC);
	connect(vc_conn:MGCP_PROC, vc_MGCP:MGCP_PROC);
	connect(vc_conn:RSL, bts[0][0].rsl.vc_RSL:CLIENT_PT);
	connect(vc_conn:RSL_PROC, bts[0][0].rsl.vc_RSL:RSL_PROC);
	if (isvalue(bts[1][0])) {
		connect(vc_conn:RSL1, bts[1][0].rsl.vc_RSL:CLIENT_PT);
		connect(vc_conn:RSL1_PROC, bts[1][0].rsl.vc_RSL:RSL_PROC);
	}
	if (isvalue(bts[2][0])) {
		connect(vc_conn:RSL2, bts[2][0].rsl.vc_RSL:CLIENT_PT);
		connect(vc_conn:RSL2_PROC, bts[2][0].rsl.vc_RSL:RSL_PROC);
	}
	connect(vc_conn:BSSAP, g_bssap[bssap_idx].vc_RAN:CLIENT);
	if (mp_enable_lcs_tests) {
		connect(vc_conn:BSSAP_LE, g_bssap_le.vc_BSSAP_LE:CLIENT);
		connect(vc_conn:BSSAP_LE_PROC, g_bssap_le.vc_BSSAP_LE:PROC);
	}
	connect(vc_conn:MGCP, vc_MGCP:MGCP_CLIENT);
	connect(vc_conn:MGCP_MULTI, vc_MGCP:MGCP_CLIENT_MULTI);
	connect(vc_conn:STATSD_PROC, vc_STATSD:STATSD_PROC);
}

function f_start_handler_create(template (omit) TestHdlrParams pars := omit)
runs on test_CT return MSC_ConnHdlr {
	var charstring id := testcasename();
	var MSC_ConnHdlr vc_conn;
	var integer bssap_idx := 0;
	if (isvalue(pars)) {
		bssap_idx := valueof(pars).mscpool.bssap_idx;
	}
	vc_conn := MSC_ConnHdlr.create(id);
	f_connect_handler(vc_conn, bssap_idx);
	return vc_conn;
}

function f_start_handler_run(MSC_ConnHdlr vc_conn, void_fn fn, template (omit) TestHdlrParams pars := omit)
runs on test_CT return MSC_ConnHdlr {
	var charstring id := testcasename();
	vc_conn.start(f_handler_init(fn, id, pars));
	return vc_conn;
}

function f_start_handler(void_fn fn, template (omit) TestHdlrParams pars := omit)
runs on test_CT return MSC_ConnHdlr {
	return f_start_handler_run(f_start_handler_create(pars), fn, pars);
}

/* first function inside ConnHdlr component; sets g_pars + starts function */
private function f_handler_init(void_fn fn, charstring id, template (omit) TestHdlrParams pars := omit)
runs on MSC_ConnHdlr {
	if (isvalue(pars)) {
		g_pars := valueof(pars);
	}
	fn.apply(id);
}

private function f_vty_encryption_a5(charstring options) runs on test_CT {
	f_vty_transceive(BSCVTY, "configure terminal");
	f_vty_transceive(BSCVTY, "network");
	f_vty_transceive(BSCVTY, "encryption a5 " & options);
	f_vty_transceive(BSCVTY, "exit");
	f_vty_transceive(BSCVTY, "exit");
}

const charstring VTY_A5_DEFAULT := "0 1 3";

private function f_vty_encryption_a5_reset() runs on test_CT {
	/* keep in sync with docker-playground.git ttcn3-bsc-test/osmo-bsc.cfg */
	f_vty_encryption_a5(VTY_A5_DEFAULT);
}

/* Establish signalling channel (non-assignment case) followed by cipher mode */
private function f_tc_ciph_mode_a5(charstring id) runs on MSC_ConnHdlr {
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelTypeSIGNAL);
	ass_cmd.pdu.bssmap.assignmentRequest.circuitIdentityCode := omit;
	ass_cmd.pdu.bssmap.assignmentRequest.aoIPTransportLayer := omit;
	exp_compl.pdu.bssmap.assignmentComplete.circuitIdentityCode := omit;
	exp_compl.pdu.bssmap.assignmentComplete.aoIPTransportLayer := omit;

	f_establish_fully(ass_cmd, exp_compl);
	f_perform_clear();
}
testcase TC_ciph_mode_a5_0() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.encr := valueof(t_EncrParams('01'O, f_rnd_octstring(8)));

	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_ciph_mode_a5), pars);
	vc_conn.done;
	f_shutdown_helper();
}
testcase TC_ciph_mode_a5_1() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.encr := valueof(t_EncrParams('02'O, f_rnd_octstring(8)));

	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_ciph_mode_a5), pars);
	vc_conn.done;
	f_shutdown_helper();
}
/* OS#4975: verify that A5/2 is preferred over A5/0 */
testcase TC_ciph_mode_a5_2_0() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	pars.encr := f_encr_params('05'O, '04'O); /* A5/0 and A5/2 (0x01|0x04)*/

	f_init(1, true);
	f_vty_encryption_a5("0 1 2 3");
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_ciph_mode_a5), pars);
	vc_conn.done;
	f_vty_encryption_a5_reset();
	f_shutdown_helper();
}
/* OS#4975: verify that A5/1 is preferred over A5/2 */
testcase TC_ciph_mode_a5_2_1() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	pars.encr := f_encr_params('06'O, '02'O); /* A5/1 and A5/2 (0x02|0x04)*/

	f_init(1, true);
	f_vty_encryption_a5("1 2");
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_ciph_mode_a5), pars);
	vc_conn.done;
	f_vty_encryption_a5_reset();
	f_shutdown_helper();
}
testcase TC_ciph_mode_a5_3() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.encr := valueof(t_EncrParams('08'O, f_rnd_octstring(8)));

	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_ciph_mode_a5), pars);
	vc_conn.done;
	f_shutdown_helper();
}
/* Establish a Signalling channel with A5/4 encryption. */
testcase TC_ciph_mode_a5_4() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.encr := valueof(t_EncrParams('10'O, f_rnd_octstring(8), f_rnd_octstring(16)));

	f_init(1, true);
	f_vty_encryption_a5("0 1 3 4");
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_ciph_mode_a5), pars);
	vc_conn.done;
	f_vty_encryption_a5_reset();
	f_shutdown_helper();
}
/* establish initial channel, enable ciphering followed by assignment to ciphered channel */
private function f_tc_assignment_aoip_tla_v6(charstring id) runs on MSC_ConnHdlr {
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	var PDU_BSSAP ass_cmd := f_gen_ass_req(aoip_tla := "::3");
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));

	f_establish_fully(ass_cmd, exp_compl);
	f_perform_clear();
}
testcase TC_assignment_aoip_tla_v6() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_assignment_aoip_tla_v6), pars);
	vc_conn.done;
	f_shutdown_helper();
}


/* establish initial channel, enable ciphering followed by assignment to ciphered channel */
private function f_tc_assignment_fr_a5(charstring id) runs on MSC_ConnHdlr {
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();

	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));

	f_establish_fully(ass_cmd, exp_compl);
	f_perform_clear();
}
testcase TC_assignment_fr_a5_0() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.encr := valueof(t_EncrParams('01'O, f_rnd_octstring(8)));

	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_assignment_fr_a5), pars);
	vc_conn.done;
	f_shutdown_helper();
}
testcase TC_assignment_fr_a5_1() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.encr := valueof(t_EncrParams('02'O, f_rnd_octstring(8)));

	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_assignment_fr_a5), pars);
	vc_conn.done;
	f_shutdown_helper();
}
testcase TC_assignment_fr_a5_3() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.encr := valueof(t_EncrParams('08'O, f_rnd_octstring(8)));

	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_assignment_fr_a5), pars);
	vc_conn.done;
	f_shutdown_helper();
}
/* Establish a Signalling channel and re-assign to TCH/F with A5/4 encryption. */
testcase TC_assignment_fr_a5_4() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.encr := valueof(t_EncrParams('10'O, f_rnd_octstring(8), f_rnd_octstring(16)));

	f_init(1, true);
	f_vty_encryption_a5("0 1 3 4");
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_assignment_fr_a5), pars);
	vc_conn.done;
	f_vty_encryption_a5_reset();
	f_shutdown_helper();
}

/* Allow only A5/4, but omit the Kc128 IE from MSC's msg. Expect Cipher Mode Reject. */
testcase TC_assignment_fr_a5_4_fail() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	pars.encr := valueof(t_EncrParams('10'O, f_rnd_octstring(8))); // A5/4 support, but Kc128 missing!
	vc_conn := f_start_handler(refers(f_TC_assignment_a5_not_sup), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* Expect ASSIGNMENT FAIL if mandatory IE is missing */
private function f_tc_assignment_fr_a5_1_codec_missing(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var template PDU_BSSAP exp_fail := tr_BSSMAP_AssignmentFail;
	var PDU_BSSAP ass_cmd := f_gen_ass_req();

	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	/* Omit: ass_cmd.pdu.bssmap.assignmentRequest.codecList */

	f_establish_fully(ass_cmd, exp_fail);
	f_perform_clear();
}
testcase TC_assignment_fr_a5_1_codec_missing() runs on test_CT {
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	vc_conn := f_start_handler(refers(f_tc_assignment_fr_a5_1_codec_missing));
	vc_conn.done;
	f_shutdown_helper();
}

private function f_TC_assignment_a5_not_sup(charstring id) runs on MSC_ConnHdlr {
	var template PDU_BSSAP exp_ass_cpl := f_gen_exp_compl();
	var PDU_BSSAP exp_ass_req := f_gen_ass_req();

	exp_ass_req.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	exp_ass_req.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));

	/* this is like the beginning of f_establish_fully(), but only up to ciphering reject */

	var BSSMAP_FIELD_CodecType codecType;

	codecType := exp_ass_req.pdu.bssmap.assignmentRequest.codecList.codecElements[0].codecType;
	f_MscConnHdlr_init(g_pars.media_nr, host_bts, host_mgw_mgcp, codecType);

	f_create_chan_and_exp();
	/* we should now have a COMPL_L3 at the MSC */

	/* Start ciphering, expect Cipher Mode Reject */
	f_cipher_mode(g_pars.encr, exp_fail := true);
	f_perform_clear();
}
testcase TC_assignment_fr_a5_not_sup() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	pars.encr := valueof(t_EncrParams('20'O, f_rnd_octstring(8), f_rnd_octstring(16)));
	vc_conn := f_start_handler(refers(f_TC_assignment_a5_not_sup), pars);
	vc_conn.done;
	f_shutdown_helper();
}


private function f_tc_assignment_sign(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var template PDU_BSSAP exp_compl := tr_BSSMAP_AssignmentComplete(omit, omit);
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelTypeSIGNAL);

	f_statsd_reset();
	f_establish_fully(ass_cmd, exp_compl);

	var StatsDExpects expect := {
		{ name := "TTCN3.bts.0.chreq.total", mtype := "c", min := 1, max := 1},
		{ name := "TTCN3.bts.0.chreq.successful", mtype := "c", min := 1, max := 1},
		{ name := "TTCN3.bsc.0.assignment.attempted", mtype := "c", min := 1, max := 1},
		{ name := "TTCN3.bsc.0.assignment.completed", mtype := "c", min := 1, max := 1}
	};
	f_statsd_expect(expect);
	f_perform_clear();
}

testcase TC_assignment_sign() runs on test_CT {
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	vc_conn := f_start_handler(refers(f_tc_assignment_sign));
	vc_conn.done;
	f_shutdown_helper();
}

/***********************************************************************
 * Codec (list) testing
 ***********************************************************************/

/* check if the given rsl_mode is compatible with the a_elem */
private function f_match_codec(BSSMAP_FIELD_CodecElement a_elem, RSL_IE_ChannelMode rsl_mode)
return boolean {
	select (a_elem.codecType) {
	case (GSM_FR) {
		if (match(rsl_mode, tr_RSL_ChanMode(RSL_CHRT_TCH_F, RSL_CMOD_SP_GSM1))) {
			return true;
		}
	}
	case (GSM_HR) {
		if (match(rsl_mode, tr_RSL_ChanMode(RSL_CHRT_TCH_H, RSL_CMOD_SP_GSM1))) {
			return true;
		}
	}
	case (GSM_EFR) {
		if (match(rsl_mode, tr_RSL_ChanMode(RSL_CHRT_TCH_F, RSL_CMOD_SP_GSM2))) {
			return true;
		}
	}
	case (FR_AMR) {
		if (match(rsl_mode, tr_RSL_ChanMode(RSL_CHRT_TCH_F, RSL_CMOD_SP_GSM3))) {
			return true;
		}
	}
	case (HR_AMR) {
		if (match(rsl_mode, tr_RSL_ChanMode(RSL_CHRT_TCH_H, RSL_CMOD_SP_GSM3))) {
			return true;
		}
	}
	case else { }
	}
	return false;
}

/* check if the given rsl_mode is compatible with the a_list */
private function f_match_codecs(BSSMAP_IE_SpeechCodecList a_list, RSL_IE_ChannelMode rsl_mode)
return boolean {
	for (var integer i := 0; i < sizeof(a_list); i := i+1) {
		if (f_match_codec(a_list.codecElements[i], rsl_mode)) {
			return true;
		}
	}
	return false;
}

/* determine BSSMAP_IE_ChannelType from *first* element of BSSMAP_FIELD_CodecElement */
function f_BSSMAP_chtype_from_codec(BSSMAP_FIELD_CodecElement a_elem)
return BSSMAP_IE_ChannelType {
	/* FIXME: actually look at all elements of BSSMAP_IE_SpeechCodecList */
	var BSSMAP_IE_ChannelType ret := valueof(ts_BSSMAP_IE_ChannelType);
	select (a_elem.codecType) {
	case (GSM_FR) {
		ret.channelRateAndType := ChRate_TCHF;
		ret.speechId_DataIndicator := Spdi_TCHF_FR;
	}
	case (GSM_HR) {
		ret.channelRateAndType := ChRate_TCHH;
		ret.speechId_DataIndicator := Spdi_TCHH_HR;
	}
	case (GSM_EFR) {
		ret.channelRateAndType := ChRate_TCHF;
		ret.speechId_DataIndicator := Spdi_TCHF_EFR;
	}
	case (FR_AMR) {
		ret.channelRateAndType := ChRate_TCHF;
		ret.speechId_DataIndicator := Spdi_TCHF_AMR;
	}
	case (HR_AMR) {
		ret.channelRateAndType := ChRate_TCHH;
		ret.speechId_DataIndicator := Spdi_TCHH_AMR;
	}
	case else {
		setverdict(fail, "Unsupported codec ", a_elem);
		mtc.stop;
	}
	}
	return ret;
}

private function f_rsl_chmod_tmpl_from_codec(BSSMAP_FIELD_CodecElement a_elem)
return template RSL_IE_Body {
	var template RSL_IE_Body mode_ie := {
		chan_mode := {
			len := ?,
			reserved := ?,
			dtx_d := ?,
			dtx_u := ?,
			spd_ind := RSL_SPDI_SPEECH,
			ch_rate_type := -,
			coding_alg_rate := -
		}
	}

	select (a_elem.codecType) {
	case (GSM_FR) {
		mode_ie.chan_mode.ch_rate_type := RSL_CHRT_TCH_F;
		mode_ie.chan_mode.coding_alg_rate := RSL_CMOD_SP_GSM1;
	}
	case (GSM_HR) {
		mode_ie.chan_mode.ch_rate_type := RSL_CHRT_TCH_H;
		mode_ie.chan_mode.coding_alg_rate := RSL_CMOD_SP_GSM1;
	}
	case (GSM_EFR) {
		mode_ie.chan_mode.ch_rate_type := RSL_CHRT_TCH_F;
		mode_ie.chan_mode.coding_alg_rate := RSL_CMOD_SP_GSM2;
	}
	case (FR_AMR) {
		mode_ie.chan_mode.ch_rate_type := RSL_CHRT_TCH_F;
		mode_ie.chan_mode.coding_alg_rate := RSL_CMOD_SP_GSM3;
	}
	case (HR_AMR) {
		mode_ie.chan_mode.ch_rate_type := RSL_CHRT_TCH_H;
		mode_ie.chan_mode.coding_alg_rate := RSL_CMOD_SP_GSM3;
	}
	}
	return mode_ie;
}

type record CodecListTest {
	BSSMAP_IE_SpeechCodecList codec_list,
	charstring id
}
type record of CodecListTest CodecListTests

private function f_TC_assignment_codec(charstring id) runs on MSC_ConnHdlr {
	f_assignment_codec(id);
}

private function f_assignment_codec(charstring id, boolean do_perform_clear := true) runs on MSC_ConnHdlr {
	var PDU_BSSAP ass_cmd := f_gen_ass_req(g_pars.use_osmux);
	var template PDU_BSSAP exp_compl := f_gen_exp_compl(g_pars.use_osmux);

	/* puzzle together the ASSIGNMENT REQ for given codec[s] */
	if (mp_bssap_cfg[0].transport == BSSAP_TRANSPORT_AoIP) {
		ass_cmd.pdu.bssmap.assignmentRequest.codecList := g_pars.ass_codec_list;
		exp_compl.pdu.bssmap.assignmentComplete.speechCodec.codecElements[0] :=
								g_pars.ass_codec_list.codecElements[0];
		if (isvalue(g_pars.expect_mr_s0_s7)) {
			exp_compl.pdu.bssmap.assignmentComplete.speechCodec.codecElements[0].s0_7 :=
								g_pars.expect_mr_s0_s7;
		}
	}
	ass_cmd.pdu.bssmap.assignmentRequest.channelType :=
				f_BSSMAP_chtype_from_codec(g_pars.ass_codec_list.codecElements[0]);
	log("expecting ASS COMPL like this: ", exp_compl);

	f_establish_fully(ass_cmd, exp_compl);

	if (not g_pars.expect_channel_mode_modify) {
		/* Verify that the RSL-side activation actually matches our expectations */
		var RSL_Message rsl := f_rslem_get_last_act(RSL_PROC, 0, g_chan_nr);

		var RSL_IE_Body mode_ie;
		if (f_rsl_find_ie(rsl, RSL_IE_CHAN_MODE, mode_ie) == false) {
			setverdict(fail, "Couldn't find CHAN_MODE IE");
			mtc.stop;
		}
		var template RSL_IE_Body t_mode_ie := f_rsl_chmod_tmpl_from_codec(g_pars.ass_codec_list.codecElements[0]);
		if (not match(mode_ie, t_mode_ie)) {
			log("mode_ie ", mode_ie, " != t_mode_ie ", t_mode_ie);
			setverdict(fail, "RSL Channel Mode IE doesn't match expectation");
		}

		var RSL_IE_Body mr_conf;
		if (g_pars.expect_mr_conf_ie != omit) {
			if (f_rsl_find_ie(rsl, RSL_IE_MR_CONFIG, mr_conf) == false) {
				setverdict(fail, "Missing MR CONFIG IE in RSL Chan Activ");
				mtc.stop;
			}
			log("found RSL MR CONFIG IE: ", mr_conf);

			if (not match(mr_conf, g_pars.expect_mr_conf_ie)) {
				setverdict(fail, "RSL MR CONFIG IE does not match expectation. Expected: ",
					g_pars.expect_mr_conf_ie);
			}
		} else {
			if (f_rsl_find_ie(rsl, RSL_IE_MR_CONFIG, mr_conf) == true) {
				log("found RSL MR CONFIG IE: ", mr_conf);
				setverdict(fail, "Found MR CONFIG IE in RSL Chan Activ, expecting omit");
				mtc.stop;
			}
		}
	}

	if (do_perform_clear) {
		f_perform_clear();
	}
}

private function f_TC_assignment_codec_fail(charstring id) runs on MSC_ConnHdlr {

	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	var template PDU_BSSAP exp_fail := tr_BSSMAP_AssignmentFail;

	/* puzzle together the ASSIGNMENT REQ for given codec[s] */
	if (mp_bssap_cfg[0].transport == BSSAP_TRANSPORT_AoIP) {
		ass_cmd.pdu.bssmap.assignmentRequest.codecList := g_pars.ass_codec_list;
	}
	ass_cmd.pdu.bssmap.assignmentRequest.channelType :=
				f_BSSMAP_chtype_from_codec(g_pars.ass_codec_list.codecElements[0]);
	log("expecting ASS FAIL like this: ", exp_fail);

	f_establish_fully(ass_cmd, exp_fail);
	f_perform_clear();
}

const CounterNameVals counternames_bsc_bts_assignment := {
	{ "assignment:attempted", 0 },
	{ "assignment:completed", 0 },
	{ "assignment:stopped", 0 },
	{ "assignment:no_channel", 0 },
	{ "assignment:timeout", 0 },
	{ "assignment:failed", 0 },
	{ "assignment:error", 0 }
};

const CounterNameVals counternames_bts_assignment := {
	{ "assignment:attempted_sign", 0 },
	{ "assignment:attempted_speech", 0 },
	{ "assignment:completed_sign", 0 },
	{ "assignment:completed_speech", 0 },
	{ "assignment:stopped_sign", 0 },
	{ "assignment:stopped_speech", 0 },
	{ "assignment:no_channel_sign", 0 },
	{ "assignment:no_channel_speech", 0 },
	{ "assignment:timeout_sign", 0 },
	{ "assignment:timeout_speech", 0 },
	{ "assignment:failed_sign", 0 },
	{ "assignment:failed_speech", 0 },
	{ "assignment:error_sign", 0 },
	{ "assignment:error_speech", 0 }
};

function f_ctrs_bsc_and_bts_assignment_init(integer bts_count := NUM_BTS) runs on test_CT {
	var CounterNameVals bts_names := counternames_bsc_bts_assignment & counternames_bts_assignment;
	f_ctrs_bts_init(bts_count, bts_names);
	f_ctrs_bsc_init(counternames_bsc_bts_assignment);
}

testcase TC_assignment_codec_fr() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);
	f_ctrs_bsc_and_bts_assignment_init(1);

	pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));
	vc_conn := f_start_handler(refers(f_TC_assignment_codec), pars);
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "assignment:attempted", 1);
	f_ctrs_bts_add(0, "assignment:attempted_speech", 1);
	f_ctrs_bsc_and_bts_add(0, "assignment:completed", 1);
	f_ctrs_bts_add(0, "assignment:completed_speech", 1);
	f_ctrs_bts_verify();

	f_shutdown_helper();
}

testcase TC_assignment_codec_hr() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);
	f_ctrs_bsc_and_bts_assignment_init(1);

	pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecHR}));
	vc_conn := f_start_handler(refers(f_TC_assignment_codec), pars);
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "assignment:attempted", 1);
	f_ctrs_bts_add(0, "assignment:attempted_speech", 1);
	f_ctrs_bsc_and_bts_add(0, "assignment:completed", 1);
	f_ctrs_bts_add(0, "assignment:completed_speech", 1);
	f_ctrs_bts_verify();

	f_shutdown_helper();
}

testcase TC_assignment_codec_efr() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecEFR}));
	vc_conn := f_start_handler(refers(f_TC_assignment_codec), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* Allow 5,90k only (current default config) */
private function f_allow_amr_rate_5_90k() runs on test_CT {
	f_vty_cfg_msc(BSCVTY, 0, {
		"amr-config 12_2k forbidden",
		"amr-config 10_2k forbidden",
		"amr-config 7_95k forbidden",
		"amr-config 7_40k forbidden",
		"amr-config 6_70k forbidden",
		"amr-config 5_90k allowed",
		"amr-config 5_15k forbidden",
		"amr-config 4_75k forbidden"
		});
}

/* Allow 4,75k, 5,90k, 4,70k and 12,2k, which are the most common rates
 * ("Config-NB-Code = 1") */
private function f_allow_amr_rate_4_75k_5_90k_7_40k_12_20k() runs on test_CT {
	f_vty_cfg_msc(BSCVTY, 0, {
		"amr-config 12_2k allowed",
		"amr-config 10_2k forbidden",
		"amr-config 7_95k forbidden",
		"amr-config 7_40k allowed",
		"amr-config 6_70k forbidden",
		"amr-config 5_90k allowed",
		"amr-config 5_15k forbidden",
		"amr-config 4_75k allowed"
		});
}

private function f_vty_amr_start_mode_set(boolean fr, charstring startmode) runs on test_CT {
	var charstring tch;
	if (fr) {
		tch := "tch-f";
	} else {
		tch := "tch-h";
	}
	f_vty_cfg_bts(BSCVTY, 0, { "amr " & tch & " start-mode " & startmode });
}

/* Set the AMR start-mode for this TCH back to the default configuration. */
private function f_vty_amr_start_mode_restore(boolean fr) runs on test_CT {
	f_vty_amr_start_mode_set(fr, "auto");
}

testcase TC_assignment_codec_amr_f() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	/* Note: This setups the codec configuration. The parameter payload in
	 * mr_conf must be consistant with the parameter codecElements in pars
	 * and also must match the amr-config in osmo-bsc.cfg! */
	var RSL_IE_Body mr_conf := {
		other := {
			len := 2,
			payload := '2804'O
		}
	};

	pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecAMR_F}));
	pars.ass_codec_list.codecElements[0].s0_7 := '00000100'B; /* 5,90k */
	pars.ass_codec_list.codecElements[0].s8_15 := '01010111'B;
	pars.expect_mr_conf_ie := mr_conf;

	f_init(1, true);
	f_sleep(1.0);
	f_vty_amr_start_mode_set(true, "1");
	f_ctrs_bsc_and_bts_assignment_init(1);

	vc_conn := f_start_handler(refers(f_TC_assignment_codec), pars);
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "assignment:attempted", 1);
	f_ctrs_bts_add(0, "assignment:attempted_speech", 1);
	f_ctrs_bsc_and_bts_add(0, "assignment:completed", 1);
	f_ctrs_bts_add(0, "assignment:completed_speech", 1);
	f_ctrs_bts_verify();

	f_vty_amr_start_mode_restore(true);
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_h() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	/* See note above */
	var RSL_IE_Body mr_conf := {
		other := {
			len := 2,
			payload := '2804'O
		}
	};

	pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecAMR_H}));
	pars.ass_codec_list.codecElements[0].s0_7 := '00000100'B; /* 5,90k */
	pars.ass_codec_list.codecElements[0].s8_15 := '00000111'B;
	pars.expect_mr_conf_ie := mr_conf;

	f_init(1, true);
	f_sleep(1.0);
	f_vty_amr_start_mode_set(false, "1");
	f_ctrs_bsc_and_bts_assignment_init(1);

	vc_conn := f_start_handler(refers(f_TC_assignment_codec), pars);
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "assignment:attempted", 1);
	f_ctrs_bts_add(0, "assignment:attempted_speech", 1);
	f_ctrs_bsc_and_bts_add(0, "assignment:completed", 1);
	f_ctrs_bts_add(0, "assignment:completed_speech", 1);
	f_ctrs_bts_verify();

	f_vty_amr_start_mode_restore(false);
	f_shutdown_helper();
}

/* Establish signalling on a TCH/F lchan, and then switch to speech mode without a new Assignment. */
testcase TC_assignment_codec_fr_by_mode_modify() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	/* By disabling all SDCCH, the MS should be given a TCH/F for signalling. Then activating an FR codec should
	 * merely do a Channel Mode Modify, and not assign to a new lchan. f_establish_fully() already accounts for
	 * expecting a Channel Mode Modify if the channel type is compatible. */
	f_disable_all_sdcch();
	f_disable_all_tch_h();

	pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));
	pars.expect_channel_mode_modify := true;
	vc_conn := f_start_handler(refers(f_TC_assignment_codec), pars);
	vc_conn.done;

	f_enable_all_sdcch();
	f_enable_all_tch();
	f_shutdown_helper();
}

/* 'amr start-mode auto' should not keep the (unused) 'smod' bits from previous configuration */
testcase TC_assignment_codec_amr_startmode_cruft() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	var RSL_IE_Body mr_conf := {
		other := {
			len := 2,
			payload := '2004'O /* <- expect ICMI=0, smod=00 */
		}
	};

	pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecAMR_F}));
	pars.ass_codec_list.codecElements[0].s0_7 := '00000100'B; /* 5,90k */
	pars.ass_codec_list.codecElements[0].s8_15 := '01010111'B;
	pars.expect_mr_conf_ie := mr_conf;

	f_init(1, true);
	f_sleep(1.0);

	/* First set nonzero start mode bits */
	f_vty_amr_start_mode_set(true, "4");
	/* Now set to auto, and expect the startmode bits to be zero in the message, i.e. ensure that osmo-bsc does not
	 * let the startmode bits stick around and has deterministic MultiRate config for 'start-mode auto'; that is
	 * ensured by above '2004'O, where 'x0xx'O indicates ICMI = 0, spare = 0, smod = 00. */
	f_vty_amr_start_mode_set(true, "auto");

	vc_conn := f_start_handler(refers(f_TC_assignment_codec), pars);
	vc_conn.done;

	/* Clear the startmode bits to not affect subsequent tests, in case the bits should indeed stick around. */
	f_vty_amr_start_mode_set(true, "1");
	f_vty_amr_start_mode_restore(true);
	f_shutdown_helper();
}

function f_TC_assignment_codec_amr(boolean fr, octetstring mrconf, bitstring s8_s0, bitstring exp_s8_s0,
	charstring start_mode := "1")
runs on test_CT {

	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	/* See note above */
	var RSL_IE_Body mr_conf := {
		other := {
			len := lengthof(mrconf),
			payload := mrconf
		}
	};

	if (fr) {
		pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecAMR_F}));
	} else {
		pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecAMR_H}));
	}
	pars.ass_codec_list.codecElements[0].s0_7 := s8_s0;
	pars.ass_codec_list.codecElements[0].s8_15 := '00000111'B;
	pars.expect_mr_conf_ie := mr_conf;
	pars.expect_mr_s0_s7 := exp_s8_s0;

	f_init(1, true);
	f_allow_amr_rate_4_75k_5_90k_7_40k_12_20k();
	f_vty_amr_start_mode_set(fr, start_mode);
	f_sleep(1.0);

	vc_conn := f_start_handler(refers(f_TC_assignment_codec), pars);
	vc_conn.done;
	f_allow_amr_rate_5_90k();
	f_vty_amr_start_mode_restore(fr);
}

function f_TC_assignment_codec_amr_fail(boolean fr, bitstring s8_s0)
runs on test_CT {

	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	if (fr) {
		pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecAMR_F}));
	} else {
		pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecAMR_H}));
	}
	pars.ass_codec_list.codecElements[0].s0_7 := s8_s0;
	pars.ass_codec_list.codecElements[0].s8_15 := '00000111'B;

	f_init(1, true);
	f_allow_amr_rate_4_75k_5_90k_7_40k_12_20k();
	f_vty_amr_start_mode_set(fr, "1");
	f_sleep(1.0);

	vc_conn := f_start_handler(refers(f_TC_assignment_codec_fail), pars);
	vc_conn.done;
	f_allow_amr_rate_5_90k();
	f_vty_amr_start_mode_restore(fr);
}


/* Set S1, we expect an AMR multirate configuration IE with all four rates
 * set. */
testcase TC_assignment_codec_amr_f_S1() runs on test_CT {
	f_TC_assignment_codec_amr(true, '289520882208'O, '00000010'B, '00000010'B);
	f_shutdown_helper();
}

/* Set S1, we expect an AMR multirate configuration IE with the lower three
 * rates set. */
testcase TC_assignment_codec_amr_h_S1() runs on test_CT {
	f_TC_assignment_codec_amr(false, '2815208820'O, '00000010'B, '00000010'B);
	f_shutdown_helper();
}

/* Set S1 and two other rates, we expect an AMR MULTIRATE CONFIGURATION IE with
 * all four rates (and only S1 set in the ASSIGNMENT COMPLETE) */
testcase TC_assignment_codec_amr_f_S124() runs on test_CT {
	f_TC_assignment_codec_amr(true, '289520882208'O, '00010110'B, '00000010'B);
	f_shutdown_helper();
}

/* Set S1 and two other rates, we expect an AMR MULTIRATE CONFIGURATION IE with
 * all four rates (and only S1 set in the ASSIGNMENT COMPLETE) */
testcase TC_assignment_codec_amr_h_S124() runs on test_CT {
	f_TC_assignment_codec_amr(false, '2815208820'O, '00010110'B, '00000010'B);
	f_shutdown_helper();
}

/* The following block of tests selects more and more rates until all four
 * possible rates are in the active set (full rate) */
testcase TC_assignment_codec_amr_f_S0() runs on test_CT {
	f_TC_assignment_codec_amr(true, '2801'O, '00000001'B, '00000001'B);
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_f_S02() runs on test_CT {
	f_TC_assignment_codec_amr(true, '28052080'O, '00000101'B, '00000101'B);
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_f_S024() runs on test_CT {
	f_TC_assignment_codec_amr(true, '2815208820'O, '00010101'B, '00010101'B);
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_f_S0247() runs on test_CT {
	f_TC_assignment_codec_amr(true, '289520882208'O, '10010101'B, '10010101'B);
	f_shutdown_helper();
}

/* The following block of tests selects more and more rates until all three
 * possible rates are in the active set (half rate) */
testcase TC_assignment_codec_amr_h_S0() runs on test_CT {
	f_TC_assignment_codec_amr(false, '2801'O, '00000001'B, '00000001'B);
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_h_S02() runs on test_CT {
	f_TC_assignment_codec_amr(false, '28052080'O, '00000101'B, '00000101'B);
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_h_S024() runs on test_CT {
	f_TC_assignment_codec_amr(false, '2815208820'O, '00010101'B, '00010101'B);
	f_shutdown_helper();
}

/* The following block tests what happens when the MSC does offer rate
 * configurations that are not supported by the BSC. Normally such situations
 * should not happen because the MSC gets informed by the BSC in advance via
 * the L3 COMPLETE message which rates are applicable. The MSC should not try
 * to offer rates that are not applicable anyway. */

testcase TC_assignment_codec_amr_h_S0247() runs on test_CT {
	/* Try to include 12,2k in into the active set even though the channel
	* is half rate only. The BSC is expected to remove the 12,0k */
	f_TC_assignment_codec_amr(false, '2815208820'O, '10010101'B, '00010101'B);
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_f_S01234567() runs on test_CT {
	/* See what happens when all rates are selected at once. Since then
	* Also S1 is selected, this setting will be prefered and we should
	* get 12.2k, 7,40k, 5,90k, and 4,75k in the active set. */
	f_TC_assignment_codec_amr(true, '289520882208'O, '11111111'B, '00000010'B);
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_f_S0234567() runs on test_CT {
	/* Same as above, but with S1 missing, the MSC is then expected to
	* select the currently supported rates, which are also 12.2k, 7,40k,
	* 5,90k, and 4,75k, into the active set. */
	f_TC_assignment_codec_amr(true, '289520882208'O, '11111101'B, '10010101'B);
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_f_zero() runs on test_CT {
	/* Try to select no rates at all */
	f_TC_assignment_codec_amr_fail(true, '00000000'B);
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_f_unsupp() runs on test_CT {
	/* Try to select only unsupported rates */
	f_TC_assignment_codec_amr_fail(true, '01101000'B);
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_h_S7() runs on test_CT {
	/* Try to select 12,2k for half rate */
	f_TC_assignment_codec_amr_fail(false, '10000000'B);
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_f_start_mode_auto() runs on test_CT {
	f_TC_assignment_codec_amr(true, '209520882208'O, '11111111'B, '00000010'B,
		start_mode := "auto");
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_h_start_mode_auto() runs on test_CT {
	f_TC_assignment_codec_amr(false, '2015208820'O, '10010101'B, '00010101'B,
		start_mode := "auto");
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_f_start_mode_4() runs on test_CT {
	/* "amr tch-f modes 0 2 4 7" => total 4 modes and start mode 4 => '11'B on the wire */
	f_TC_assignment_codec_amr(true, '2b9520882208'O, '11111111'B, '00000010'B,
		start_mode := "4");
	f_shutdown_helper();
}

testcase TC_assignment_codec_amr_h_start_mode_4() runs on test_CT {
	/* "amr tch-h modes 0 2 4" => total 3 modes and start mode 4 => '10'B on the wire */
	f_TC_assignment_codec_amr(false, '2a15208820'O, '10010101'B, '00010101'B,
		start_mode := "4");
	f_shutdown_helper();
}

private function f_disable_all_tch_f() runs on test_CT {
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 1 sub-slot 0 borken");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 2 sub-slot 0 borken");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 3 sub-slot 0 borken");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 4 sub-slot 0 borken");
}

private function f_disable_all_tch_h() runs on test_CT {
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 5 sub-slot 0 borken");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 5 sub-slot 1 borken");
}

private function f_enable_all_tch() runs on test_CT {
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 1 sub-slot 0 unused");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 2 sub-slot 0 unused");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 3 sub-slot 0 unused");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 4 sub-slot 0 unused");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 5 sub-slot 0 unused");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 5 sub-slot 1 unused");
}

private function f_disable_all_sdcch() runs on test_CT {
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 0 sub-slot 0 borken");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 0 sub-slot 1 borken");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 0 sub-slot 2 borken");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 0 sub-slot 3 borken");
}

private function f_enable_all_sdcch() runs on test_CT {
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 0 sub-slot 0 unused");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 0 sub-slot 1 unused");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 0 sub-slot 2 unused");
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 0 sub-slot 3 unused");
}

/* Allow HR only */
private function f_TC_assignment_codec_xr_exhausted_req_hr(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.channelRateAndType := '09'O;
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.speechId_DataIndicator := '05'O;
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecHR}));
	f_establish_fully(ass_cmd, exp_compl);
	f_perform_clear();
}

/* Allow FR only */
private function f_TC_assignment_codec_xr_exhausted_req_fr(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.channelRateAndType := '08'O;
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.speechId_DataIndicator := '01'O;
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));
	f_establish_fully(ass_cmd, exp_compl);
	f_perform_clear();
}

/* Allow HR only (expect assignment failure) */
private function f_TC_assignment_codec_xr_exhausted_req_hr_fail(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	var template PDU_BSSAP exp_fail := tr_BSSMAP_AssignmentFail;
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.channelRateAndType := '09'O;
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.speechId_DataIndicator := '05'O;
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecHR}));
	f_establish_fully(ass_cmd, exp_fail);
	f_perform_clear();
}

/* Allow FR only (expect assignment failure) */
private function f_TC_assignment_codec_xr_exhausted_req_fr_fail(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	var template PDU_BSSAP exp_fail := tr_BSSMAP_AssignmentFail;
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.channelRateAndType := '08'O;
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.speechId_DataIndicator := '01'O;
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));
	f_establish_fully(ass_cmd, exp_fail);
	f_perform_clear();
}

/* Allow FR and HR, but prefer FR */
private function f_TC_assignment_codec_fr_exhausted_req_fr_hr(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.channelRateAndType := '0A'O; /* Prefer FR */
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.speechId_DataIndicator := '8105'O;
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR, ts_CodecHR}));
	exp_compl.pdu.bssmap.assignmentComplete.speechVersion.speechVersionIdentifier := '0000101'B; /* Expect HR */
	f_establish_fully(ass_cmd, exp_compl);
	f_perform_clear();
}

/* Allow FR and HR, but prefer HR */
private function f_TC_assignment_codec_fr_exhausted_req_hr_fr(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.channelRateAndType := '0B'O; /* Prefer HR */
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.speechId_DataIndicator := '8501'O;
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecHR, ts_CodecFR}));
	exp_compl.pdu.bssmap.assignmentComplete.speechVersion.speechVersionIdentifier := '0000101'B; /* Expect HR */
	f_establish_fully(ass_cmd, exp_compl);
	f_perform_clear();
}

/* Allow FR and HR, but prefer FR */
private function f_TC_assignment_codec_hr_exhausted_req_fr_hr(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.channelRateAndType := '0A'O; /* Prefer FR */
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.speechId_DataIndicator := '8105'O;
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR, ts_CodecHR}));
	exp_compl.pdu.bssmap.assignmentComplete.speechVersion.speechVersionIdentifier := '0000001'B; /* Expect FR */
	f_establish_fully(ass_cmd, exp_compl);
	f_perform_clear();
}

/* Allow FR and HR, but prefer HR */
private function f_TC_assignment_codec_hr_exhausted_req_hr_fr(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.channelRateAndType := '0B'O; /* Prefer HR */
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.speechId_DataIndicator := '8501'O;
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecHR, ts_CodecFR}));
	exp_compl.pdu.bssmap.assignmentComplete.speechVersion.speechVersionIdentifier := '0000001'B; /* Expect FR */
	f_establish_fully(ass_cmd, exp_compl);
	f_perform_clear();
}

/* Request a HR channel while all FR channels are exhausted, this is expected
 * to work without conflicts */
testcase TC_assignment_codec_fr_exhausted_req_hr() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	f_enable_all_tch();
	f_disable_all_tch_f();
	vc_conn := f_start_handler(refers(f_TC_assignment_codec_xr_exhausted_req_hr));
	vc_conn.done;
	f_enable_all_tch();
	f_shutdown_helper();
}

/* Request a FR channel while all FR channels are exhausted, this is expected
 * to fail. */
testcase TC_assignment_codec_fr_exhausted_req_fr() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	f_enable_all_tch();
	f_disable_all_tch_f();
	vc_conn := f_start_handler(refers(f_TC_assignment_codec_xr_exhausted_req_fr_fail));
	vc_conn.done;
	f_enable_all_tch();
	f_shutdown_helper();
}

/* Request a FR (prefered) or alternatively a HR channel while all FR channels
 * are exhausted, this is expected to be resolved by selecting a HR channel. */
testcase TC_assignment_codec_fr_exhausted_req_fr_hr() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	f_enable_all_tch();
	f_disable_all_tch_f();
	vc_conn := f_start_handler(refers(f_TC_assignment_codec_fr_exhausted_req_fr_hr));
	vc_conn.done;
	f_enable_all_tch();
	f_shutdown_helper();
}

/* Request a HR (prefered) or alternatively a FR channel while all FR channels
 * are exhausted, this is expected to work without conflicts. */
testcase TC_assignment_codec_fr_exhausted_req_hr_fr() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	f_enable_all_tch();
	f_disable_all_tch_f();
	vc_conn := f_start_handler(refers(f_TC_assignment_codec_fr_exhausted_req_hr_fr));
	vc_conn.done;
	f_enable_all_tch();
	f_shutdown_helper();
}

/* Request a FR channel while all HR channels are exhausted, this is expected
 * to work without conflicts */
testcase TC_assignment_codec_hr_exhausted_req_fr() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	f_enable_all_tch();
	f_disable_all_tch_h();
	vc_conn := f_start_handler(refers(f_TC_assignment_codec_xr_exhausted_req_fr));
	vc_conn.done;
	f_enable_all_tch();
	f_shutdown_helper();
}

/* Request a HR channel while all HR channels are exhausted, this is expected
 * to fail. */
testcase TC_assignment_codec_hr_exhausted_req_hr() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	f_enable_all_tch();
	f_disable_all_tch_h();
	vc_conn := f_start_handler(refers(f_TC_assignment_codec_xr_exhausted_req_hr_fail));
	vc_conn.done;
	f_enable_all_tch();
	f_shutdown_helper();
}

/* Request a HR (prefered) or alternatively a FR channel while all HR channels
 * are exhausted, this is expected to be resolved by selecting a FR channel. */
testcase TC_assignment_codec_hr_exhausted_req_hr_fr() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	f_enable_all_tch();
	f_disable_all_tch_h();
	vc_conn := f_start_handler(refers(f_TC_assignment_codec_hr_exhausted_req_hr_fr));
	vc_conn.done;
	f_enable_all_tch();
	f_shutdown_helper();
}

/* Request a FR (prefered) or alternatively a HR channel while all HR channels
 * are exhausted, this is expected to work without conflicts. */
testcase TC_assignment_codec_hr_exhausted_req_fr_hr() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	f_enable_all_tch();
	f_disable_all_tch_h();
	vc_conn := f_start_handler(refers(f_TC_assignment_codec_hr_exhausted_req_fr_hr));
	vc_conn.done;
	f_enable_all_tch();
	f_shutdown_helper();
}

/* Allow FR and HR, but prefer HR */
private function f_TC_assignment_codec_req_hr_fr(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.channelRateAndType := '0B'O; /* Prefer HR */
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.speechId_DataIndicator := '8501'O;
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecHR, ts_CodecFR}));
	exp_compl.pdu.bssmap.assignmentComplete.speechVersion.speechVersionIdentifier := '0000101'B; /* Expect HR */
	f_establish_fully(ass_cmd, exp_compl);
	f_perform_clear();
}

/* Allow FR and HR, but prefer FR */
private function f_TC_assignment_codec_req_fr_hr(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.channelRateAndType := '0A'O; /* Prefer FR */
	ass_cmd.pdu.bssmap.assignmentRequest.channelType.speechId_DataIndicator := '8105'O;
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR, ts_CodecHR}));
	exp_compl.pdu.bssmap.assignmentComplete.speechVersion.speechVersionIdentifier := '0000001'B; /* Expect FR */
	f_establish_fully(ass_cmd, exp_compl);
	f_perform_clear();
}

/* Request a HR (prefered) or alternatively a FR channel, it is expected that
 * HR, which is the prefered type, is selected. */
testcase TC_assignment_codec_req_hr_fr() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	f_enable_all_tch();
	vc_conn := f_start_handler(refers(f_TC_assignment_codec_req_hr_fr));
	vc_conn.done;
	f_shutdown_helper();
}

/* Request a FR (prefered) or alternatively a HR channel, it is expected that
 * FR, which is the prefered type, is selected. */
testcase TC_assignment_codec_req_fr_hr() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	f_enable_all_tch();
	vc_conn := f_start_handler(refers(f_TC_assignment_codec_req_fr_hr));
	vc_conn.done;
	f_shutdown_helper();
}

/* request a signalling channel with all SDCCH exhausted, it is expected that a TCH will be selected */
private function f_TC_assignment_sdcch_exhausted_req_signalling(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	g_pars.ra := '02'O; /* RA containing reason=LU */

	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
	var PDU_ML3_MS_NW l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_MO_CALL, mi));
	var octetstring l3_enc := enc_PDU_ML3_MS_NW(l3_info);
	var template uint3_t tsc := ?;

	f_MscConnHdlr_init(g_pars.media_nr, host_bts, host_mgw_mgcp, FR_AMR);
	f_create_bssmap_exp(l3_enc);
	/* call helper function for CHAN_RQD -> IMM ASS ->EST_IND */
	RSL_Emulation.f_chan_est(g_pars.ra, l3_enc, g_pars.link_id, g_pars.fn, tsc);

	/* we should now have a COMPL_L3 at the MSC */
	timer T := 10.0;
	T.start;
	alt {
	[] BSSAP.receive(tr_BSSMAP_ComplL3);
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for COMPLETE LAYER 3 INFORMATION");
		}
	}

	f_perform_clear();
}
testcase TC_assignment_sdcch_exhausted_req_signalling() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	f_disable_all_sdcch();
	vc_conn := f_start_handler(refers(f_TC_assignment_sdcch_exhausted_req_signalling));
	vc_conn.done;
	f_enable_all_sdcch();
	f_shutdown_helper();
}

/* Request a signalling channel with all SDCCH exhausted, it is
   expected that no TCH will be selected for signalling and assigment will fail
   because it's dictated by VTY config */
testcase TC_assignment_sdcch_exhausted_req_signalling_tch_forbidden() runs on test_CT {
	var RSL_Message rsl_unused, rsl_msg;
	var GsmRrMessage rr;
	f_init(1, false);
	f_sleep(1.0);
	f_vty_allow_tch_for_signalling(false, 0);
	f_disable_all_sdcch();

	/* RA containing reason=LU */
	f_ipa_tx(ts_RSL_CHAN_RQD('02'O, 2342));
	rsl_msg := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0));
	rr := dec_GsmRrMessage(rsl_msg.ies[1].body.full_imm_ass_info.payload);
	if (rr.header.message_type != IMMEDIATE_ASSIGNMENT_REJECT) {
		setverdict(fail, "Expected reject");
	}

	f_vty_allow_tch_for_signalling(true, 0);
	f_enable_all_sdcch();
	f_shutdown_helper();
}

/* Request a voice channel with all SDCCH exhausted, it is
 * expected that TCH channel will be allocated since the VTY option is only
 * aimed at signalling requests */
private function f_TC_assignment_sdcch_exhausted_req_voice_tch_forbidden(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	g_pars.ra := '43'O; /* RA containing reason=originating speech call*/

	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
	var PDU_ML3_MS_NW l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_MO_CALL, mi));
	var octetstring l3_enc := enc_PDU_ML3_MS_NW(l3_info);
	var template uint3_t tsc := ?;

	f_MscConnHdlr_init(g_pars.media_nr, host_bts, host_mgw_mgcp, FR_AMR);
	f_create_bssmap_exp(l3_enc);
	/* call helper function for CHAN_RQD -> IMM ASS ->EST_IND */
	RSL_Emulation.f_chan_est(g_pars.ra, l3_enc, g_pars.link_id, g_pars.fn, tsc);

	/* we should now have a COMPL_L3 at the MSC */
	timer T := 10.0;
	T.start;
	alt {
	[] BSSAP.receive(tr_BSSMAP_ComplL3);
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for COMPLETE LAYER 3 INFORMATION");
		}
	}
	f_perform_clear();
}
testcase TC_assignment_sdcch_exhausted_req_voice_tch_forbidden() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	f_vty_allow_tch_for_signalling(false, 0);
	f_disable_all_sdcch();

	vc_conn := f_start_handler(refers(f_TC_assignment_sdcch_exhausted_req_voice_tch_forbidden));
	vc_conn.done;

	f_vty_allow_tch_for_signalling(true, 0);
	f_enable_all_sdcch();
	f_shutdown_helper();
}

testcase TC_assignment_osmux() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	/* See note above */
	var RSL_IE_Body mr_conf := {
		other := {
			len := 2,
			payload := '2804'O
		}
	};

	pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecAMR_H}));
	pars.ass_codec_list.codecElements[0].s0_7 := '00000100'B; /* 5,90k */
	pars.ass_codec_list.codecElements[0].s8_15 := '00000111'B;
	pars.expect_mr_conf_ie := mr_conf;
	pars.use_osmux := true;

	f_init(1, true, true);
	f_sleep(1.0);
	f_vty_amr_start_mode_set(false, "1");

	vc_conn := f_start_handler(refers(f_TC_assignment_codec), pars);
	vc_conn.done;

	f_vty_amr_start_mode_restore(false);
	f_shutdown_helper();
}

/* test the procedure of the MSC requesting a Classmark Update:
 * a) BSSMAP Classmark Request should result in RR CLASSMARK ENQUIRY,
 * b) L3 RR CLASSMARK CHANGE should result in BSSMAP CLASSMARK UPDATE */
private function f_tc_classmark(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();

	f_create_chan_and_exp();
	/* we should now have a COMPL_L3 at the MSC */

	BSSAP.send(ts_BSSMAP_ClassmarkRequest);
	RSL.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, decmatch tr_RRM_CM_ENQUIRY));

	f_rsl_send_l3(ts_RRM_CM_CHG(valueof(ts_CM2)));
	BSSAP.receive(tr_BSSMAP_ClassmarkUpd(?, omit));
	setverdict(pass);

	f_perform_clear();
}
testcase TC_classmark() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_classmark));
	vc_conn.done;
	f_shutdown_helper();
}

/* Send a CommonID from the simulated MSC and verify that the information is used to
 * fill BSC-internal data structures (specifically, bsc_subscr associated with subscr_conn) */
private function f_tc_common_id(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	f_MscConnHdlr_init_vty();

	f_create_chan_and_exp();
	/* we should now have a COMPL_L3 at the MSC */

	/* Send CommonID */
	BSSAP.send(ts_BSSMAP_CommonId(g_pars.imsi));

	/* Use VTY to verify that the IMSI of the subscr_conn is set */
	var charstring regex := "*(IMSI: " & hex2str(g_pars.imsi) & ")*";
	f_vty_transceive_match_regexp_retry(BSCVTY, "show conns", regex, 0, 4, 1.0);

	setverdict(pass);

	f_perform_clear();
}
testcase TC_common_id() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_common_id));
	vc_conn.done;
	f_shutdown_helper();
}

private function f_est_single_l3(template PDU_ML3_MS_NW l3) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	f_create_chan_and_exp();
	/* we should now have a COMPL_L3 at the MSC */

	/* send the single message we want to send */
	f_rsl_send_l3(l3);
}

private function f_bssap_expect_nothing(float sec := 5.00) runs on MSC_ConnHdlr {
	timer T := sec;
	var PDU_BSSAP bssap;
	T.start;
	alt {
	[] BSSAP.receive(PDU_BSSAP:?) -> value bssap {
		setverdict(fail, "Unexpected BSSMAP ", bssap);
		mtc.stop;
		}
	[] T.timeout {
		setverdict(pass);
		}
	}
}

/* unsolicited ASSIGNMENT FAIL (without ASSIGN) from MS shouldn't bring BSC down */
private function f_tc_unsol_ass_fail(charstring id) runs on MSC_ConnHdlr {
	f_est_single_l3(ts_RRM_AssignmentFailure('00'O));
	f_bssap_expect_nothing();
	f_perform_clear();
}
testcase TC_unsol_ass_fail() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_unsol_ass_fail));
	vc_conn.done;
	f_shutdown_helper();
}


/* unsolicited ASSIGNMENT COMPLETE (without ASSIGN) from MS shouldn't bring BSC down */
private function f_tc_unsol_ass_compl(charstring id) runs on MSC_ConnHdlr {
	f_est_single_l3(ts_RRM_AssignmentComplete('00'O));
	f_bssap_expect_nothing();
	f_perform_clear();
}
testcase TC_unsol_ass_compl() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_unsol_ass_compl));
	vc_conn.done;
	f_shutdown_helper();
}


/* unsolicited HANDOVER FAIL (without ASSIGN) from MS shouldn't bring BSC down */
private function f_tc_unsol_ho_fail(charstring id) runs on MSC_ConnHdlr {
	f_est_single_l3(ts_RRM_HandoverFailure('00'O));
	f_bssap_expect_nothing();
	f_perform_clear();
}
testcase TC_unsol_ho_fail() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_unsol_ho_fail));
	vc_conn.done;
	f_shutdown_helper();
}


/* short message from MS should be ignored */
private function f_tc_err_82_short_msg(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	f_create_chan_and_exp();
	/* we should now have a COMPL_L3 at the MSC */

	/* send short message */
	RSL.send(ts_RSL_DATA_IND(g_chan_nr, valueof(ts_RslLinkID_DCCH(0)), ''O));
	f_bssap_expect_nothing();
	f_perform_clear();
}
testcase TC_err_82_short_msg() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_err_82_short_msg));
	vc_conn.done;
	f_shutdown_helper();
}


/* 24.008 8.4 Unknown message must trigger RR STATUS */
private function f_tc_err_84_unknown_msg(charstring id) runs on MSC_ConnHdlr {
	f_est_single_l3(ts_RRM_UL_REL('00'O));
	timer T := 3.0
	alt {
	[] RSL.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, decmatch tr_RRM_RR_STATUS)) {
		setverdict(pass);
		}
	[] BSSAP.receive { setverdict(fail, "unexpected BSSAP"); }
	[] T.timeout { setverdict(fail, "Timeout waiting for RR STATUS"); }
	}
	f_perform_clear();
}
testcase TC_err_84_unknown_msg() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_err_84_unknown_msg));
	vc_conn.done;
	f_shutdown_helper();
}

/***********************************************************************
 * Handover
 ***********************************************************************/

/* execute a "bts <0-255> trx <0-255> timeslot <0-7> " command on given Dchan */
private function f_vty_ts_action(charstring suffix, integer bts_nr, integer trx_nr, integer ts_nr)
runs on test_CT {
	var charstring cmd := "bts "&int2str(bts_nr)&" trx "&int2str(trx_nr)&
				" timeslot "&int2str(ts_nr)&" ";
	f_vty_transceive(BSCVTY, cmd & suffix);
}

/* execute a "bts <0-255> trx <0-255> timeslot <0-7> sub-slot <0-7>" command on given Dchan */
private function f_vty_ss_action(TELNETasp_PT pt, charstring suffix,
				 uint8_t bts_nr, uint8_t trx_nr,
				 in RslChannelNr chan_nr)
{
	/* FIXME: resolve those from component-global state */
	var integer ts_nr := chan_nr.tn;
	var integer ss_nr;
	if (ischosen(chan_nr.u.ch0)) {
		ss_nr := 0;
	} else if (ischosen(chan_nr.u.lm)) {
		ss_nr := chan_nr.u.lm.sub_chan;
	} else if (ischosen(chan_nr.u.sdcch4)) {
		ss_nr := chan_nr.u.sdcch4.sub_chan;
	} else if (ischosen(chan_nr.u.sdcch8)) {
		ss_nr := chan_nr.u.sdcch8.sub_chan;
	} else {
		setverdict(fail, "Invalid ChanNr ", chan_nr);
		mtc.stop;
	}

	var charstring cmd := "bts "&int2str(bts_nr)&" trx "&int2str(trx_nr)&
				" timeslot "&int2str(ts_nr)&" sub-slot "&int2str(ss_nr)&" ";
	f_vty_transceive(pt, cmd & suffix);
}

/* Even though the VTY command to trigger handover takes a new BTS number as argument, behind the scenes osmo-bsc always
 * translates that to a target ARFCN+BSIC first. See bsc_vty.c trigger_ho_or_as(), which puts the selected BTS' neighbor
 * ident key (ARFCN + BSIC) in the struct passed on to handover_request(). handover_start() then resolves that to a
 * viable actual neighbor cell. So from the internal osmo-bsc perspective, we always request handover to an ARFCN + BSIC
 * pair, not really to a specific BTS number. */
private function f_vty_handover(TELNETasp_PT pt, uint8_t bts_nr, uint8_t trx_nr,
				in RslChannelNr chan_nr, uint8_t new_bts_nr)
{
	f_vty_ss_action(pt, "handover " & int2str(new_bts_nr), bts_nr, trx_nr, chan_nr);
}

/* intra-BSC hand-over between BTS0 and BTS1 */
private function f_tc_ho_int(charstring id) runs on MSC_ConnHdlr {
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();

	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));

	f_establish_fully(ass_cmd, exp_compl);
	f_bts_0_cfg(BSCVTY, {"neighbor bts 1"});

	var HandoverState hs := {
		rr_ho_cmpl_seen := false,
		handover_done := false,
		old_chan_nr := -,
		expect_target_tsc := c_BtsParams[1].tsc
	};
	/* issue hand-over command on VTY, from BTS 0 to BTS 1 */
	f_vty_handover(BSCVTY, 0, 0, g_chan_nr, 1);
	/* temporarily suspend DChan processing on BTS1 to avoid race with RSLEM_register */
	f_rslem_suspend(RSL1_PROC);

	/* From the MGW perspective, a handover is is characterized by
	 * performing one MDCX operation with the MGW. So we expect to see
	 * one more MDCX during handover. */
	g_media.mgcp_conn[0].mdcx_seen_exp := g_media.mgcp_conn[0].crcx_seen_exp + 1;

	alt {
	[] as_handover(hs);
	}

	/* Since this is an internal handover we expect the BSC to inform the
	 * MSC about the event */
	BSSAP.receive(tr_BSSMAP_HandoverPerformed);

	/* Check the amount of MGCP transactions is still consistant with the
	 * test expectation */
	f_check_mgcp_expectations()

	var RSL_Message chan_act := f_rslem_get_last_act(RSL1_PROC, 0, g_chan_nr);

	/* Ensure the Channel Activation for the new channel contained the right encryption params. as_handover() set
	 * g_chan_nr to the new lchan that was handed over to. It lives in bts 1, so look it up at RSL1_PROC. */
	f_verify_encr_info(chan_act);

	f_chan_act_verify_tsc(chan_act, c_BtsParams[1].tsc);

	f_perform_clear(RSL1, RSL1_PROC);

	f_sleep(0.5);
}

testcase TC_ho_int() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;
	f_init(2, true);
	f_sleep(1.0);

	pars.expect_tsc := c_BtsParams[0].tsc;

	f_ctrs_bsc_and_bts_handover_init();

	vc_conn := f_start_handler(refers(f_tc_ho_int), pars);
	vc_conn.done;

	/* from f_establish_fully() */
	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");
	/* from handover */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:completed");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:attempted");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:completed");
	f_ctrs_bts_add(1, "incoming_intra_bsc_ho:attempted");
	f_ctrs_bts_add(1, "incoming_intra_bsc_ho:completed");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

function f_tc_ho_int_a5(OCT1 encr_alg, charstring enc_a5 := "0 1 3") runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.encr := valueof(t_EncrParams(encr_alg, f_rnd_octstring(8), f_rnd_octstring(16)));

	f_init(2, true);
	f_vty_encryption_a5(enc_a5);
	f_sleep(1.0);

	f_ctrs_bsc_and_bts_handover_init();

	vc_conn := f_start_handler(refers(f_tc_ho_int), pars);
	vc_conn.done;

	/* from f_establish_fully() */
	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");
	/* from handover */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:completed");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:attempted");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:completed");
	f_ctrs_bts_add(1, "incoming_intra_bsc_ho:attempted");
	f_ctrs_bts_add(1, "incoming_intra_bsc_ho:completed");
	f_ctrs_bsc_and_bts_verify();
	f_vty_encryption_a5_reset();
	f_shutdown_helper();
}

testcase TC_ho_int_a5_0() runs on test_CT {
	f_tc_ho_int_a5('01'O);
}

testcase TC_ho_int_a5_1() runs on test_CT {
	f_tc_ho_int_a5('02'O);
}

testcase TC_ho_int_a5_3() runs on test_CT {
	f_tc_ho_int_a5('08'O);
}

testcase TC_ho_int_a5_4() runs on test_CT {
	f_tc_ho_int_a5('10'O, "0 1 3 4");
}

/* intra-BSC hand-over with CONNection FAILure and cause Radio Link Failure: check RR release cause */
private function f_tc_ho_int_radio_link_failure(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();

	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));

	f_establish_fully(ass_cmd, exp_compl);
	f_bts_0_cfg(BSCVTY, {"neighbor bts 1"});

	var HandoverState hs := {
		rr_ho_cmpl_seen := false,
		handover_done := false,
		old_chan_nr := -,
		expect_target_tsc := c_BtsParams[1].tsc
	};
	/* issue hand-over command on VTY */
	f_vty_handover(BSCVTY, 0, 0, g_chan_nr, 1);
	/* temporarily suspend DChan processing on BTS1 to avoid race with RSLEM_register */
	f_rslem_suspend(RSL1_PROC);

	/* From the MGW perspective, a handover is is characterized by
	 * performing one MDCX operation with the MGW. So we expect to see
	 * one more MDCX during handover. */
	g_media.mgcp_conn[0].mdcx_seen_exp := g_media.mgcp_conn[0].crcx_seen_exp + 1;

	var RSL_Message rsl;
	var PDU_ML3_NW_MS l3;
	var RslChannelNr new_chan_nr;
	var GsmArfcn arfcn;
	RSL.receive(tr_RSL_DATA_REQ(g_chan_nr)) -> value rsl {
		l3 := dec_PDU_ML3_NW_MS(rsl.ies[2].body.l3_info.payload);
		if (not ischosen(l3.msgs.rrm.handoverCommand)) {
			setverdict(fail, "Expected handoverCommand");
			mtc.stop;
		}
	}
	f_ChDesc2RslChanNr(l3.msgs.rrm.handoverCommand.channelDescription2,
			   new_chan_nr, arfcn);

	f_rslem_register(0, new_chan_nr, RSL1_PROC);

	/* resume processing of RSL DChan messages, which was temporarily suspended
	 * before performing a hand-over */
	f_rslem_resume(RSL1_PROC);
	RSL1.receive(tr_RSL_IPA_CRCX(new_chan_nr));

	f_sleep(1.0);

	/* Handover fails because no HANDO DET appears on the new lchan,
	 * and the old lchan reports a Radio Link Failure. */
	RSL.send(ts_RSL_CONN_FAIL_IND(g_chan_nr, RSL_ERR_RADIO_LINK_FAIL));

	var PDU_BSSAP rx_clear_request;
	BSSAP.receive(tr_BSSMAP_ClearRequest) -> value rx_clear_request;
	var BssmapCause cause := bit2int(rx_clear_request.pdu.bssmap.clearRequest.cause.causeValue);
	BSSAP.send(ts_BSSMAP_ClearCommand(cause));

	var RR_Cause rr_cause := GSM48_RR_CAUSE_ABNORMAL_UNSPEC;

	var MgcpCommand mgcp;
	interleave {
	[] RSL.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, decmatch tr_RRM_RR_RELEASE(int2oct(enum2int(rr_cause), 1)))) {}
	[] RSL.receive(tr_RSL_DEACT_SACCH(g_chan_nr)) {}
	[] RSL.receive(tr_RSL_RF_CHAN_REL(g_chan_nr)) {
			RSL.send(ts_RSL_RF_CHAN_REL_ACK(g_chan_nr));
			f_rslem_unregister(0, g_chan_nr);
		}
	[] RSL1.receive(tr_RSL_DEACT_SACCH(new_chan_nr)) {}
	[] RSL1.receive(tr_RSL_RF_CHAN_REL(new_chan_nr)) {
			RSL1.send(ts_RSL_RF_CHAN_REL_ACK(new_chan_nr));
			f_rslem_unregister(0, g_chan_nr, PT := RSL1_PROC);
		}
	[] BSSAP.receive(tr_BSSMAP_ClearComplete) {
			BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);
		}
	}

	f_sleep(0.5);
	setverdict(pass);
}
testcase TC_ho_int_radio_link_failure() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(2, true);
	f_sleep(1.0);

	f_ctrs_bsc_and_bts_handover_init();

	vc_conn := f_start_handler(refers(f_tc_ho_int_radio_link_failure));
	vc_conn.done;

	/* from f_establish_fully() */
	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");
	/* from handover */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:stopped");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:attempted");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:stopped");
	f_ctrs_bts_add(1, "incoming_intra_bsc_ho:attempted");
	f_ctrs_bts_add(1, "incoming_intra_bsc_ho:stopped");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

/* Expecting MGCP to DLCX the endpoint's two connections: towards BTS and towards MSC */
private function f_expect_dlcx_conns() runs on MSC_ConnHdlr {
	var MgcpCommand mgcp;
	var template MgcpResponse mgcp_resp;
	var MGCP_RecvFrom mrf;
	var template MgcpMessage msg_resp;
	var template MgcpMessage msg_dlcx := {
		command := tr_DLCX()
	}

	if (g_pars.aoip) {
		MGCP.receive(tr_DLCX()) -> value mgcp {
				log("Got first DLCX: ", mgcp);
				MGCP.send(ts_DLCX_ACK2(mgcp.line.trans_id));
			};

		MGCP.receive(tr_DLCX()) -> value mgcp {
				log("Got second DLCX: ", mgcp);
				MGCP.send(ts_DLCX_ACK2(mgcp.line.trans_id));
			};
	} else  {
		/* For SCCPLite, BSC doesn't handle the MSC-side */
		MGCP_MULTI.receive(tr_MGCP_RecvFrom_any(msg_dlcx)) -> value mrf {
			log("Got first DLCX: ", mrf.msg.command);
			msg_resp := {
				response := ts_DLCX_ACK2(mrf.msg.command.line.trans_id)
			}
			MGCP_MULTI.send(t_MGCP_SendToMrf(mrf, msg_resp));
		};
	}
}

private function f_ho_out_of_this_bsc(template (omit) BSSMAP_oldToNewBSSIEs exp_oldToNewBSSIEs := omit) runs on MSC_ConnHdlr {

	var NcellReports neighbor_rep := {
		{ rxlev := 20, bcch_freq := 0, bsic := 11 }
	};
	var octetstring l3_mr := enc_GsmRrL3Message(valueof(ts_MEAS_REP(true, 8, 8, reps := neighbor_rep)));
	RSL.send(ts_RSL_MEAS_RES(g_chan_nr, 0, ts_RSL_IE_UplinkMeas, ts_RSL_IE_BS_Power(0), ts_RSL_IE_L1Info,
				 l3_mr, 0));

	BSSAP.receive(tr_BSSMAP_HandoverRequired(exp_oldToNewBSSIEs));

	f_sleep(0.5);
	/* The MSC negotiates Handover Request and Handover Request Ack with
	 * the other BSS and comes back with a BSSMAP Handover Command
	 * containing an RR Handover Command coming from the target BSS... */

	var PDU_ML3_NW_MS rr_ho_cmd := valueof(ts_RR_HandoverCommand);
	log("Remote cell's RR Handover Command passed through as L3 Info: ", rr_ho_cmd);
	var octetstring rr_ho_cmd_enc := enc_PDU_ML3_NW_MS(rr_ho_cmd);
	log("Remote cell's RR Handover Command passed through as L3 Info, encoded: ", rr_ho_cmd_enc);
	BSSAP.send(ts_BSSMAP_HandoverCommand(rr_ho_cmd_enc));

	/* expect the Handover Command to go out on RR */
	var RSL_Message rsl_ho_cmd
	RSL.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, ?)) -> value rsl_ho_cmd;
	log("RSL Data Req went out to first BTS: ", rsl_ho_cmd);
	var RSL_IE_Body rsl_ho_cmd_l3;
	if (not f_rsl_find_ie(rsl_ho_cmd, RSL_IE_L3_INFO, rsl_ho_cmd_l3)) {
		log("RSL message contains no L3 Info IE, expected RR Handover Command");
		setverdict(fail);
	} else {
		log("Found L3 Info: ", rsl_ho_cmd_l3);
		if (rsl_ho_cmd_l3.l3_info.payload != rr_ho_cmd_enc) {
			log("FAIL: the BSC sent out a different L3 Info, not matching the RR Handover Command the other BSS forwarded.");
			setverdict(fail);
		} else {
			log("Success: the BSC sent out the same RR Handover Command the other BSS forwarded.");
			setverdict(pass);
		}
	}

	/* When the other BSS has reported a completed handover, this side is
	 * torn down. */

	var myBSSMAP_Cause cause_val := GSM0808_CAUSE_HANDOVER_SUCCESSFUL;
	var BssmapCause cause := enum2int(cause_val);
	BSSAP.send(ts_BSSMAP_ClearCommand(cause));

	f_expect_dlcx_conns();

	interleave {
	[] RSL.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, decmatch tr_RRM_RR_RELEASE));
	[] RSL.receive(tr_RSL_DEACT_SACCH(g_chan_nr));
	[] RSL.receive(tr_RSL_RF_CHAN_REL(g_chan_nr));
	[] BSSAP.receive(tr_BSSMAP_ClearComplete) {
			BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);
		}
	}
	setverdict(pass);
}

private function f_tc_ho_out_of_this_bsc(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var PDU_BSSAP ass_req := f_gen_ass_req();
	ass_req.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_req.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	f_establish_fully(ass_req, exp_compl);

	f_ho_out_of_this_bsc();
}
testcase TC_ho_out_of_this_bsc() runs on test_CT {
	var MSC_ConnHdlr vc_conn;

	f_init_vty();
	f_bts_0_cfg(BSCVTY,
		    {"neighbor-list mode automatic",
		     "handover 1",
		     "handover algorithm 2",
		     "handover2 window rxlev averaging 1",
		     "no neighbors",
		     "neighbor lac 99 arfcn 123 bsic any"});
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1, true);
	f_sleep(1.0);

	f_ctrs_bsc_and_bts_handover_init();

	vc_conn := f_start_handler(refers(f_tc_ho_out_of_this_bsc));
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:completed");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:attempted");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:completed");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

private function f_mo_l3_transceive(RSL_DCHAN_PT rsl := RSL,
				    template (value) RslLinkId link_id := ts_RslLinkID_DCCH(0),
				    template (present) OCT1 dlci := ?,
				    octetstring l3 := '0123456789'O)
runs on MSC_ConnHdlr {
	/* The old lchan and conn should still be active. See that arbitrary L3
	 * is still going through. */
	rsl.send(ts_RSL_DATA_IND(g_chan_nr, link_id, l3));
	var template PDU_BSSAP exp_data := {
		    discriminator := '1'B,
		    spare := '0000000'B,
		    dlci := dlci,
		    lengthIndicator := lengthof(l3),
		    pdu := {
			dtap := l3
		    }
		};
	BSSAP.receive(exp_data);
	setverdict(pass);
}

private function f_mt_l3_transceive(RSL_DCHAN_PT rsl := RSL,
				    template (present) RslLinkId link_id := tr_RslLinkID_DCCH(0),
				    template (value) OCT1 dlci := '00'O,
				    octetstring l3 := '0123456789'O)
runs on MSC_ConnHdlr {
	BSSAP.send(PDU_BSSAP:{
		discriminator := '1'B,
		spare := '0000000'B,
		dlci := dlci,
		lengthIndicator := lengthof(l3),
		pdu := {
			dtap := l3
		}
	});
	rsl.receive(tr_RSL_DATA_REQ(g_chan_nr, link_id, l3));
	setverdict(pass);
}

/* BSC asks for inter-BSC HO, but the MSC decides that it won't happen and
 * simply never sends a BSSMAP Handover Command. */
private function f_tc_ho_out_fail_no_msc_response(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();

	var PDU_BSSAP ass_req := f_gen_ass_req();
	ass_req.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_req.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	f_establish_fully(ass_req, exp_compl);

	f_bts_0_cfg(BSCVTY, {"no neighbor lac 99", "neighbor lac 99 arfcn 123 bsic any"});
	f_vty_transceive(BSCVTY, "handover any to arfcn 123 bsic any");

	BSSAP.receive(tr_BSSMAP_HandoverRequired);

	/* osmo-bsc should time out 10 seconds after the handover started.
	 * Let's give it a bit extra. */
	f_sleep(15.0);

	f_mo_l3_transceive();
	f_sleep(1.0);
	f_perform_clear();
}
testcase TC_ho_out_fail_no_msc_response() runs on test_CT {
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	f_ctrs_bsc_and_bts_handover_init();

	vc_conn := f_start_handler(refers(f_tc_ho_out_fail_no_msc_response));
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:timeout");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:attempted");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:timeout");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

/* BSC asks for inter-BSC HO, receives BSSMAP Handover Command, but MS reports
 * RR Handover Failure. */
private function f_tc_ho_out_fail_rr_ho_failure(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();

	var PDU_BSSAP ass_req := f_gen_ass_req();
	ass_req.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_req.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	f_establish_fully(ass_req, exp_compl);

	f_bts_0_cfg(BSCVTY, {"no neighbor lac 99", "neighbor lac 99 arfcn 123 bsic any"});
	f_vty_transceive(BSCVTY, "handover any to arfcn 123 bsic any");

	BSSAP.receive(tr_BSSMAP_HandoverRequired);

	f_sleep(0.5);
	/* The MSC negotiates Handover Request and Handover Request Ack with
	 * the other BSS and comes back with a BSSMAP Handover Command
	 * containing an RR Handover Command coming from the target BSS... */

	var PDU_ML3_NW_MS rr_ho_cmd := valueof(ts_RR_HandoverCommand);
	log("Remote cell's RR Handover Command passed through as L3 Info: ", rr_ho_cmd);
	var octetstring rr_ho_cmd_enc := enc_PDU_ML3_NW_MS(rr_ho_cmd);
	log("Remote cell's RR Handover Command passed through as L3 Info, encoded: ", rr_ho_cmd_enc);
	BSSAP.send(ts_BSSMAP_HandoverCommand(rr_ho_cmd_enc));

	/* expect the Handover Command to go out on RR */
	var RSL_Message rsl_ho_cmd
	RSL.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, ?)) -> value rsl_ho_cmd;
	log("RSL Data Req went out to first BTS: ", rsl_ho_cmd);
	var RSL_IE_Body rsl_ho_cmd_l3;
	if (not f_rsl_find_ie(rsl_ho_cmd, RSL_IE_L3_INFO, rsl_ho_cmd_l3)) {
		log("RSL message contains no L3 Info IE, expected RR Handover Command");
		setverdict(fail);
	} else {
		log("Found L3 Info: ", rsl_ho_cmd_l3);
		if (rsl_ho_cmd_l3.l3_info.payload != rr_ho_cmd_enc) {
			log("FAIL: the BSC sent out a different L3 Info, not matching the RR Handover Command the other BSS forwarded.");
			setverdict(fail);
		} else {
			log("Success: the BSC sent out the same RR Handover Command the other BSS forwarded.");
			setverdict(pass);
		}
	}

	f_sleep(0.2);
	f_rsl_send_l3(ts_RRM_HandoverFailure('00'O));

	/* Should tell the MSC about the failure */
	BSSAP.receive(tr_BSSMAP_HandoverFailure);

	f_sleep(1.0);

	f_mo_l3_transceive();
	f_sleep(1.0);

	setverdict(pass);
	f_sleep(1.0);
	f_perform_clear();
}
testcase TC_ho_out_fail_rr_ho_failure() runs on test_CT {
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	f_ctrs_bsc_and_bts_handover_init();

	vc_conn := f_start_handler(refers(f_tc_ho_out_fail_rr_ho_failure));
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:failed");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:attempted");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:failed");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

/* BSC asks for inter-BSC-out HO, receives BSSMAP Handover Command, but then no reply is received about HO outcome
 * (neither BSSMAP Clear Command for success nor RR Handover Failure). 48.008 3.1.5.3.3 "Abnormal Conditions" applies
 * and the lchan is released. */
private function f_tc_ho_out_fail_no_result_after_ho_cmd(charstring id) runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();

	var PDU_BSSAP ass_req := f_gen_ass_req();
	ass_req.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_req.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	f_establish_fully(ass_req, exp_compl);

	f_bts_0_cfg(BSCVTY, {"no neighbor lac 99", "neighbor lac 99 arfcn 123 bsic any"});
	f_vty_transceive(BSCVTY, "handover any to arfcn 123 bsic any");

	BSSAP.receive(tr_BSSMAP_HandoverRequired);

	f_sleep(0.5);
	/* The MSC negotiates Handover Request and Handover Request Ack with
	 * the other BSS and comes back with a BSSMAP Handover Command
	 * containing an RR Handover Command coming from the target BSS... */

	var PDU_ML3_NW_MS rr_ho_cmd := valueof(ts_RR_HandoverCommand);
	log("Remote cell's RR Handover Command passed through as L3 Info: ", rr_ho_cmd);
	var octetstring rr_ho_cmd_enc := enc_PDU_ML3_NW_MS(rr_ho_cmd);
	log("Remote cell's RR Handover Command passed through as L3 Info, encoded: ", rr_ho_cmd_enc);
	BSSAP.send(ts_BSSMAP_HandoverCommand(rr_ho_cmd_enc));

	/* expect the Handover Command to go out on RR */
	var RSL_Message rsl_ho_cmd
	RSL.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, ?)) -> value rsl_ho_cmd;
	log("RSL Data Req went out to first BTS: ", rsl_ho_cmd);
	var RSL_IE_Body rsl_ho_cmd_l3;
	if (not f_rsl_find_ie(rsl_ho_cmd, RSL_IE_L3_INFO, rsl_ho_cmd_l3)) {
		log("RSL message contains no L3 Info IE, expected RR Handover Command");
		setverdict(fail);
	} else {
		log("Found L3 Info: ", rsl_ho_cmd_l3);
		if (rsl_ho_cmd_l3.l3_info.payload != rr_ho_cmd_enc) {
			log("FAIL: the BSC sent out a different L3 Info, not matching the RR Handover Command the other BSS forwarded.");
			setverdict(fail);
		} else {
			log("Success: the BSC sent out the same RR Handover Command the other BSS forwarded.");
			setverdict(pass);
		}
	}

	/* We get neither success nor failure report from the remote BSS.  Eventually T8 times out and we run into 3GPP
	 * TS 48.008 3.1.5.3.3 "Abnormal Conditions": Clear Request should go to the MSC, and RR should be released
	 * after Clear Command */

	var PDU_BSSAP rx_clear_request;
	BSSAP.receive(tr_BSSMAP_ClearRequest) -> value rx_clear_request;
	log("Got BSSMAP Clear Request");
	/* Instruct BSC to clear channel */
	var BssmapCause cause := bit2int(rx_clear_request.pdu.bssmap.clearRequest.cause.causeValue);
	BSSAP.send(ts_BSSMAP_ClearCommand(cause));

	var MgcpCommand mgcp;
	interleave {
	[] RSL.receive(tr_RSL_DEACT_SACCH(g_chan_nr)) {
			log("Got Deact SACCH");
		}
	[] RSL.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, decmatch tr_RRM_RR_RELEASE)) {
			log("Got RR Release");
		}
	[] RSL.receive(tr_RSL_RF_CHAN_REL(g_chan_nr)) {
			log("Got RF Chan Rel");
			RSL.send(ts_RSL_RF_CHAN_REL_ACK(g_chan_nr));
			f_rslem_unregister(0, g_chan_nr);
		}
	}

	f_expect_dlcx_conns();
	BSSAP.receive(tr_BSSMAP_ClearComplete);
	BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);

	setverdict(pass);
	f_sleep(1.0);
}
testcase TC_ho_out_fail_no_result_after_ho_cmd() runs on test_CT {
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	f_ctrs_bsc_and_bts_handover_init();

	vc_conn := f_start_handler(refers(f_tc_ho_out_fail_no_result_after_ho_cmd));
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:timeout");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:attempted");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:timeout");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

private function f_ho_into_this_bsc(charstring id, template (omit) BSSMAP_oldToNewBSSIEs oldToNewBSSIEs := omit) runs on MSC_ConnHdlr {
	var PDU_BSSAP rx_bssap;
	/* Hack: the proper way would be to wait for the BSSMAP Handover Request ACK and extract the
	 * actual assigned chan_nr from its L3 (RR Handover Command) message. But osmo-bsc starts acting
	 * on the lchan even before we get a chance to evaluate the BSSMAP Handover Request ACK. So we
	 * need to assume that osmo-bsc will activate TS 1 and already set up this lchan's RSL emulation
	 * before we get started. */
	var RslChannelNr new_chan_nr := valueof(t_RslChanNr0(1, RSL_CHAN_NR_Bm_ACCH));
	f_rslem_register(0, new_chan_nr);
	g_chan_nr := new_chan_nr;
	var uint3_t expect_target_tsc := c_BtsParams[0].tsc;
	f_sleep(1.0);

	f_create_mgcp_expect(ExpectCriteria:{omit,omit,omit});
	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);
	var default as_media := activate(as_Media());

	var PDU_BSSAP ho_req := f_gen_handover_req(aoip_tla := g_pars.host_aoip_tla,
						   cell_id_source := g_pars.cell_id_source,
						   oldToNewBSSIEs := oldToNewBSSIEs,
						   enc := g_pars.encr);
	if (g_pars.inter_bsc_ho_in__ho_req_in_initial_sccp_cr) {
		BSSAP.send(ts_BSSAP_Conn_Req(g_pars.sccp_addr_bsc, g_pars.sccp_addr_msc, ho_req));
		BSSAP.receive(RAN_Conn_Prim:MSC_CONN_PRIM_CONF_IND);
	} else {
		BSSAP.send(ts_BSSAP_Conn_Req(g_pars.sccp_addr_bsc, g_pars.sccp_addr_msc, omit));
		BSSAP.receive(RAN_Conn_Prim:MSC_CONN_PRIM_CONF_IND);
		BSSAP.send(ho_req);
	}

	alt {
	[] BSSAP.receive(tr_BSSMAP_HandoverRequestAcknowledge(?)) -> value rx_bssap {
		if (g_pars.expect_ho_fail) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						"Expected Handover Request to fail, but got Handover Request Ack")
		}
		}
	[] BSSAP.receive(tr_BSSMAP_HandoverFailure) -> value rx_bssap {
		if (not g_pars.expect_ho_fail) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						"Expected Handover Request to succeed, but got Handover Failure")
		}
		// TODO: evaluate correct cause value. But osmo-bsc doesn't seem to send meaningful causes yet!
		// For now just accept any cause.
		BSSAP.receive(tr_BSSMAP_ClearRequest);
		setverdict(pass);
		return;
		}
	}

	/* The RSL Emulation magically accepts the Chan Activ behind the scenes. */

	/* we're sure that the channel activation is done now, verify the parameters in it */
	var RSL_Message chan_act := f_rslem_get_last_act(RSL_PROC, 0, g_chan_nr);
	f_verify_encr_info(chan_act);
	f_chan_act_verify_tsc(chan_act, expect_target_tsc);

	if (ispresent(rx_bssap.pdu.bssmap.handoverRequestAck.codecList)) {
		if (not g_pars.aoip) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						"handoverRequestAck: Expected no Speech Codec List (BSS Supported), because this is not AoIP");
		}
		/* TODO: check actual codecs? */
	} else {
		if (g_pars.aoip) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						"handoverRequestAck: Expected Speech Codec List (BSS Supported), but none found");
		}
	}

	if (ispresent(rx_bssap.pdu.bssmap.handoverRequestAck.speechCodec)) {
		if (not g_pars.aoip) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						"handoverRequestAck: Expected no Speech Codec (Chosen), because this is not AoIP");
		}
		/* TODO: check actual codec? */
	} else {
		if (g_pars.aoip) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						"handoverRequestAck: Expected Speech Codec (Chosen), but none found");
		}
	}

	var octetstring ho_command_str;
	ho_command_str := rx_bssap.pdu.bssmap.handoverRequestAck.layer3Information.layer3info;
	log("Received L3 Info in HO Request Ack: ", ho_command_str);
	var PDU_ML3_NW_MS ho_command := dec_PDU_ML3_NW_MS(ho_command_str);
	log("L3 Info in HO Request Ack is ", ho_command);

	var GsmArfcn arfcn;
	var RslChannelNr actual_new_chan_nr;
	f_ChDesc2RslChanNr(ho_command.msgs.rrm.handoverCommand.channelDescription2,
			actual_new_chan_nr, arfcn);

	if (actual_new_chan_nr != new_chan_nr) {
		log("ERROR: osmo-bsc assigned a different lchan than we assumed above -- this test will fail now.",
		    " Assumed: ", new_chan_nr, " Assigned: ", actual_new_chan_nr);
		setverdict(fail);
		return;
	}
	log("Handover Command chan_nr is", actual_new_chan_nr);

	var uint3_t got_tsc := rr_chan_desc_tsc(ho_command.msgs.rrm.handoverCommand.channelDescription2);
	if (not match(got_tsc, expect_target_tsc)) {
		setverdict(fail, "RR Handover Command: unexpected TSC in Channel Description: expected ",
			   expect_target_tsc, " got ", got_tsc);
		mtc.stop;
	} else {
		log("handoverCommand: verified TSC = ", got_tsc);
	}

	/* Check the Cipher Mode Setting IE (shall be present during inter-RAT handover) */
	if (ispresent(ho_command.msgs.rrm.handoverCommand.cipherModeSetting)) {
		var CipherModeSetting_TV cms := ho_command.msgs.rrm.handoverCommand.cipherModeSetting;
		var template (present) CipherModeSetting_TV tr_cms := {
			sC := '0'B, /* no ciphering by default */
			algorithmIdentifier := '000'B,
			elementIdentifier := ?
		};
		if (ispresent(g_pars.encr) and g_pars.encr.enc_alg_expect != '01'O) { /* A5/N */
			tr_cms.algorithmIdentifier := f_cipher_mode_bssmap_to_rr(g_pars.encr.enc_alg_expect);
			tr_cms.sC := '1'B;
		}
		if (not match(cms, tr_cms)) {
			setverdict(fail, "RR Handover Command: unexpected Cipher Mode Setting IE: ",
				   cms, ", expected: ", tr_cms);
		}
	} else {
		setverdict(fail, "RR Handover Command: Cipher Mode Setting IE is not present");
	}

	/* Now the MSC forwards the RR Handover Command to the other BSC, which
	 * tells the MS to handover to the new lchan. Here comes the new MS on
	 * the new lchan with a Handover RACH: */

	/* send handover detect */

	RSL.send(ts_RSL_HANDO_DET(new_chan_nr));

	BSSAP.receive(tr_BSSMAP_HandoverDetect);

	/* send handover complete over the new channel */

	var PDU_ML3_MS_NW l3_tx := valueof(ts_RRM_HandoverComplete('00'O));
	RSL.send(ts_RSL_EST_IND(new_chan_nr, valueof(ts_RslLinkID_DCCH(0)),
				enc_PDU_ML3_MS_NW(l3_tx)));

	BSSAP.receive(tr_BSSMAP_HandoverComplete);
	deactivate(as_media);
	setverdict(pass);
}

private function f_tc_ho_into_this_bsc(charstring id) runs on MSC_ConnHdlr {
	var template PDU_ML3_NW_MS exp_rr_rel_tmpl;
	var template (omit) BSSMAP_oldToNewBSSIEs oldToNewBSSIEs := omit;
	if (not istemplatekind(g_pars.last_used_eutran_plmn, "omit")) {
		oldToNewBSSIEs := f_ts_BSSMAP_oldToNewBSSIEs(ts_BSSMAP_LastUsedEUTRANPLMNId(g_pars.last_used_eutran_plmn));
	}
	if (g_pars.exp_fast_return) {
		exp_rr_rel_tmpl := tr_RRM_RR_RELEASE_CellSelectInd;
	} else {
		exp_rr_rel_tmpl := tr_RRM_RR_RELEASE;
	}
	f_ho_into_this_bsc(id, oldToNewBSSIEs);
	if (g_pars.expect_ho_fail) {
		f_perform_clear_no_lchan();
	} else {
		f_perform_clear(exp_rr_rel_tmpl := exp_rr_rel_tmpl);
	}
	setverdict(pass);
}
function f_tc_ho_into_this_bsc_main(TestHdlrParams pars, charstring vty_a5_cfg := VTY_A5_DEFAULT) runs on test_CT {
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	f_vty_encryption_a5(vty_a5_cfg);
	f_ctrs_bsc_and_bts_handover_init();

	pars.sccp_addr_msc := g_bssap[0].sccp_addr_own;
	pars.sccp_addr_bsc := g_bssap[0].sccp_addr_peer;

	vc_conn := f_start_handler(refers(f_tc_ho_into_this_bsc), pars);
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:attempted");
	if (pars.expect_ho_fail) {
		f_ctrs_bsc_and_bts_add(0, "handover:failed");
		f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:failed");
	} else {
		f_ctrs_bsc_and_bts_add(0, "handover:completed");
		f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:completed");
	}
	f_ctrs_bsc_and_bts_verify();

	f_vty_encryption_a5_reset();
}

testcase TC_ho_into_this_bsc() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	f_tc_ho_into_this_bsc_main(pars);
	f_shutdown_helper();
}

function f_tc_ho_into_this_bsc_a5(TestHdlrEncrParams encr, charstring vty_a5_cfg := VTY_A5_DEFAULT,
				  boolean expect_fail := false) runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.encr := encr;
	pars.expect_ho_fail := expect_fail;
	f_tc_ho_into_this_bsc_main(pars, vty_a5_cfg);
	f_shutdown_helper();
}

testcase TC_ho_into_this_bsc_a5_0() runs on test_CT {
	f_tc_ho_into_this_bsc_a5(f_encr_params('01'O));
}

testcase TC_ho_into_this_bsc_a5_1() runs on test_CT {
	f_tc_ho_into_this_bsc_a5(f_encr_params('02'O));
}

testcase TC_ho_into_this_bsc_a5_3() runs on test_CT {
	f_tc_ho_into_this_bsc_a5(f_encr_params('08'O));
}

testcase TC_ho_into_this_bsc_a5_4() runs on test_CT {
	f_tc_ho_into_this_bsc_a5(f_encr_params('10'O, kc128 := true), "3 4");
}

/* Report: in inter-BSC incoming handover, when the MSC omits the Chosen Encryption Algorithm IE in the Handover Request
 * message, then osmo-bsc starts an unencrypted lchan even if A5/0 is not permitted.
 *
 * This test verifies that the Encryption Information is present in the Channel Activation when the Chosen Enc Alg is
 * omitted.
 *
 * Related: SYS#5839
 */
testcase TC_ho_into_this_bsc_a5_1_3_no_chosen_enc_alg() runs on test_CT {
	f_tc_ho_into_this_bsc_a5(f_encr_params(alg_permitted := '0a'O, alg_expect := '08'O, alg_chosen := omit));
}

testcase TC_ho_into_this_bsc_a5_1_3() runs on test_CT {
	f_tc_ho_into_this_bsc_a5(f_encr_params(alg_permitted := '0a'O, alg_expect := '08'O));
}

/* Send a permitted algo mask that does not intersect with osmo-bsc.cfg */
testcase TC_ho_into_this_bsc_a5_mismatch() runs on test_CT {
	f_tc_ho_into_this_bsc_a5(f_encr_params(alg_permitted := '18'O, alg_expect := '10'O), "0 1",
				 expect_fail := true); // 0x18 = A5/3 and A5/4
}

testcase TC_ho_into_this_bsc_tla_v6() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.host_aoip_tla := "::6";
	f_tc_ho_into_this_bsc_main(pars);
	f_shutdown_helper();
}

/* Similar to TC_ho_into_this_bsc, but when in SRVCC, HO Req contains "Old BSS
   to New BSS Information" IE with "Last Used E-UTRAN PLMN Id", which, when the
   channel is later released (RR CHannel Release), should trigger inclusion of
   IE "Cell Selection Indicator after Release of all TCH and SDCCH" with E-UTRAN
   neighbors. */
testcase TC_srvcc_eutran_to_geran() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.last_used_eutran_plmn := '323454'O;
	pars.exp_fast_return := true;
	f_tc_ho_into_this_bsc_main(pars);

	f_ctrs_bsc_and_bts_add(0, "srvcc:attempted");
	f_ctrs_bsc_and_bts_add(0, "srvcc:completed");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

/* Same as TC_srvcc_eutran_to_geran, but enables ciphering on the target channel. */
testcase TC_srvcc_eutran_to_geran_a5_3() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.encr := f_encr_params('08'O); /* only A5/3 */
	pars.last_used_eutran_plmn := '323454'O;
	pars.exp_fast_return := true;
	f_tc_ho_into_this_bsc_main(pars);

	f_ctrs_bsc_and_bts_add(0, "srvcc:attempted");
	f_ctrs_bsc_and_bts_add(0, "srvcc:completed");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

/* Same as TC_srvcc_eutran_to_geran, but test explicitly forbiding fast return
   on the BTS. As a result, RR Release shouldn't contain the EUTRAN neighbor
   list when the channel is released. */
testcase TC_srvcc_eutran_to_geran_forbid_fast_return() runs on test_CT {
	f_init_vty();
	f_vty_allow_srvcc_fast_return(true, 0)

	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.last_used_eutran_plmn := '323454'O;
	pars.exp_fast_return := false;
	f_tc_ho_into_this_bsc_main(pars);
	f_vty_allow_srvcc_fast_return(false, 0);
	f_shutdown_helper();
}

/* Same as TC_srvcc_eutran_to_geran, but using SAI as serving Cell Identifier. SYS#5838 */
testcase TC_srvcc_eutran_to_geran_src_sai() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.last_used_eutran_plmn := '323454'O;
	pars.cell_id_source := valueof(ts_CellID_SAI('123456'O, 300, 444));
	f_tc_ho_into_this_bsc_main(pars);

	f_ctrs_bsc_and_bts_add(0, "srvcc:attempted");
	f_ctrs_bsc_and_bts_add(0, "srvcc:completed");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

private function f_tc_srvcc_eutran_to_geran_ho_out(charstring id) runs on MSC_ConnHdlr {
	var template (omit) BSSMAP_oldToNewBSSIEs oldToNewBSSIEs;
	oldToNewBSSIEs := f_ts_BSSMAP_oldToNewBSSIEs(ts_BSSMAP_LastUsedEUTRANPLMNId(g_pars.last_used_eutran_plmn));
	f_ho_into_this_bsc(id, oldToNewBSSIEs);
	f_ho_out_of_this_bsc(oldToNewBSSIEs);
	setverdict(pass);
}

private function f_tc_srvcc_eutran_to_geran_ho_out_main(boolean disable_fast_return)
	runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init_vty();
	f_bts_0_cfg(BSCVTY,
		    {"neighbor-list mode automatic",
		     "handover 1",
		     "handover algorithm 2",
		     "handover2 window rxlev averaging 1",
		     "no neighbors",
		     "neighbor lac 99 arfcn 123 bsic any"});
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1, true);
	if (disable_fast_return) {
		f_vty_allow_srvcc_fast_return(true, 0);
	}
	f_sleep(1.0);

	f_ctrs_bsc_and_bts_handover_init();

	pars.last_used_eutran_plmn := '323454'O;
	pars.sccp_addr_msc := g_bssap[0].sccp_addr_own;
	pars.sccp_addr_bsc := g_bssap[0].sccp_addr_peer;

	vc_conn := f_start_handler(refers(f_tc_srvcc_eutran_to_geran_ho_out), pars);
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "handover:attempted", 2);
	f_ctrs_bsc_and_bts_add(0, "handover:completed", 2);
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:attempted", 1);
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:completed", 1);
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:attempted", 1);
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:completed", 1);

	f_ctrs_bsc_and_bts_add(0, "srvcc:attempted", 1);
	f_ctrs_bsc_and_bts_add(0, "srvcc:completed", 1);
	f_ctrs_bsc_and_bts_verify();

	if (disable_fast_return) {
		f_vty_allow_srvcc_fast_return(false, 0);
	}
	f_shutdown_helper();
}

/* First, HO into BSC from EUTRAN (SRVCC): HO Request contains "Old BSS to New
   BSS Information" IE with "Last Used E-UTRAN PLMN Id".
   Second, HO to another BSC: HO Required contains "Old BSS to New BSS Information"
   IE with "Last Used E-UTRAN PLMN Id" from first step. */
testcase TC_srvcc_eutran_to_geran_ho_out() runs on test_CT {
	f_tc_srvcc_eutran_to_geran_ho_out_main(false);
}
/* Validate subsequent intra-GSM-HO works the same (with OldBSSToNewBSSInfo IE)
 * independently of fast-reture allowed/forbidden in local BTS */
testcase TC_srvcc_eutran_to_geran_ho_out_forbid_fast_return() runs on test_CT {
	f_tc_srvcc_eutran_to_geran_ho_out_main(true);
}

private function f_tc_ho_in_fail_msc_clears(charstring id) runs on MSC_ConnHdlr {
	var RslChannelNr new_chan_nr := valueof(t_RslChanNr0(1, RSL_CHAN_NR_Bm_ACCH));
	f_rslem_register(0, new_chan_nr);
	g_chan_nr := new_chan_nr;
	f_sleep(1.0);

	f_create_mgcp_expect(ExpectCriteria:{omit,omit,omit});
	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);
	activate(as_Media());

	BSSAP.send(ts_BSSAP_Conn_Req(g_pars.sccp_addr_bsc, g_pars.sccp_addr_msc,
				     f_gen_handover_req()));
	BSSAP.receive(RAN_Conn_Prim:MSC_CONN_PRIM_CONF_IND);

	/* The RSL Emulation magically accepts the Chan Activ behind the scenes. */

	var PDU_BSSAP rx_bssap;
	var octetstring ho_command_str;

	BSSAP.receive(tr_BSSMAP_HandoverRequestAcknowledge(?)) -> value rx_bssap;

	ho_command_str := rx_bssap.pdu.bssmap.handoverRequestAck.layer3Information.layer3info;
	log("Received L3 Info in HO Request Ack: ", ho_command_str);
	var PDU_ML3_NW_MS ho_command := dec_PDU_ML3_NW_MS(ho_command_str);
	log("L3 Info in HO Request Ack is ", ho_command);

	var GsmArfcn arfcn;
	var RslChannelNr actual_new_chan_nr;
	f_ChDesc2RslChanNr(ho_command.msgs.rrm.handoverCommand.channelDescription2,
			actual_new_chan_nr, arfcn);

	if (actual_new_chan_nr != new_chan_nr) {
		log("ERROR: osmo-bsc assigned a different lchan than we assumed above -- this test will fail now.",
		    " Assumed: ", new_chan_nr, " Assigned: ", actual_new_chan_nr);
		setverdict(fail);
		return;
	}
	log("Handover Command chan_nr is", actual_new_chan_nr);

	/* For deterministic test results, give some time for the MGW endpoint to be configured */
	f_sleep(1.0);

	/* Now the MSC forwards the RR Handover Command to the other BSC, which
	 * tells the MS to handover to the new lchan. In this case, the MS
	 * reports a Handover Failure to the old BSS, which forwards a BSSMAP
	 * Handover Failure to the MSC. The procedure according to 3GPP TS
	 * 48.008 3.1.5.3.2 "Handover Failure" is then that the MSC sends a
	 * BSSMAP Clear Command: */

	var myBSSMAP_Cause cause_val := GSM0808_CAUSE_RADIO_INTERFACE_FAILURE_REVERSION;
	var BssmapCause cause := enum2int(cause_val);
	BSSAP.send(ts_BSSMAP_ClearCommand(cause));

	f_expect_dlcx_conns();
	BSSAP.receive(tr_BSSMAP_ClearComplete);
	BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);

	setverdict(pass);
	f_sleep(1.0);

	setverdict(pass);
}
testcase TC_ho_in_fail_msc_clears() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);

	f_ctrs_bsc_and_bts_handover_init();

	pars.sccp_addr_msc := g_bssap[0].sccp_addr_own;
	pars.sccp_addr_bsc := g_bssap[0].sccp_addr_peer;

	vc_conn := f_start_handler(refers(f_tc_ho_in_fail_msc_clears), pars);
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:stopped");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:attempted");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:stopped");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

private function f_tc_ho_in_fail_msc_clears_after_ho_detect(charstring id) runs on MSC_ConnHdlr {
	/* Hack: the proper way would be to wait for the BSSMAP Handover Request ACK and extract the
	 * actual assigned chan_nr from its L3 (RR Handover Command) message. But osmo-bsc starts acting
	 * on the lchan even before we get a chance to evaluate the BSSMAP Handover Request ACK. So we
	 * need to assume that osmo-bsc will activate TS 1 and already set up this lchan's RSL emulation
	 * before we get started. */
	var RslChannelNr new_chan_nr := valueof(t_RslChanNr0(1, RSL_CHAN_NR_Bm_ACCH));
	f_rslem_register(0, new_chan_nr);
	g_chan_nr := new_chan_nr;
	f_sleep(1.0);

	f_create_mgcp_expect(ExpectCriteria:{omit,omit,omit});
	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);
	activate(as_Media());

	BSSAP.send(ts_BSSAP_Conn_Req(g_pars.sccp_addr_bsc, g_pars.sccp_addr_msc,
				     f_gen_handover_req()));
	BSSAP.receive(RAN_Conn_Prim:MSC_CONN_PRIM_CONF_IND);

	/* The RSL Emulation magically accepts the Chan Activ behind the scenes. */

	var PDU_BSSAP rx_bssap;
	var octetstring ho_command_str;

	BSSAP.receive(tr_BSSMAP_HandoverRequestAcknowledge(?)) -> value rx_bssap;

	ho_command_str := rx_bssap.pdu.bssmap.handoverRequestAck.layer3Information.layer3info;
	log("Received L3 Info in HO Request Ack: ", ho_command_str);
	var PDU_ML3_NW_MS ho_command := dec_PDU_ML3_NW_MS(ho_command_str);
	log("L3 Info in HO Request Ack is ", ho_command);

	var GsmArfcn arfcn;
	var RslChannelNr actual_new_chan_nr;
	f_ChDesc2RslChanNr(ho_command.msgs.rrm.handoverCommand.channelDescription2,
			actual_new_chan_nr, arfcn);

	if (actual_new_chan_nr != new_chan_nr) {
		log("ERROR: osmo-bsc assigned a different lchan than we assumed above -- this test will fail now.",
		    " Assumed: ", new_chan_nr, " Assigned: ", actual_new_chan_nr);
		setverdict(fail);
		return;
	}
	log("Handover Command chan_nr is", actual_new_chan_nr);

	/* Now the MSC forwards the RR Handover Command to the other BSC, which
	 * tells the MS to handover to the new lchan. Here comes the new MS on
	 * the new lchan with a Handover RACH: */

	/* send handover detect */

	RSL.send(ts_RSL_HANDO_DET(new_chan_nr));

	BSSAP.receive(tr_BSSMAP_HandoverDetect);

	/* The MSC chooses to clear the connection now, maybe we got the
	 * Handover RACH on the new cell but the MS still signaled Handover
	 * Failure to the old BSS? */

	var myBSSMAP_Cause cause_val := GSM0808_CAUSE_RADIO_INTERFACE_FAILURE_REVERSION;
	var BssmapCause cause := enum2int(cause_val);
	BSSAP.send(ts_BSSMAP_ClearCommand(cause));

	f_expect_dlcx_conns();
	BSSAP.receive(tr_BSSMAP_ClearComplete);
	BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);

	f_sleep(1.0);
}
testcase TC_ho_in_fail_msc_clears_after_ho_detect() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);

	f_ctrs_bsc_and_bts_handover_init();

	pars.sccp_addr_msc := g_bssap[0].sccp_addr_own;
	pars.sccp_addr_bsc := g_bssap[0].sccp_addr_peer;

	vc_conn := f_start_handler(refers(f_tc_ho_in_fail_msc_clears_after_ho_detect), pars);
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:stopped");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:attempted");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:stopped");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

/* The new BSS's lchan times out before the MSC decides that handover failed. */
private function f_tc_ho_in_fail_no_detect(charstring id) runs on MSC_ConnHdlr {
	var RslChannelNr new_chan_nr := valueof(t_RslChanNr0(1, RSL_CHAN_NR_Bm_ACCH));
	f_rslem_register(0, new_chan_nr);
	g_chan_nr := new_chan_nr;
	f_sleep(1.0);

	f_create_mgcp_expect(ExpectCriteria:{omit,omit,omit});
	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);
	activate(as_Media(fail_on_dlcx := false));

	BSSAP.send(ts_BSSAP_Conn_Req(g_pars.sccp_addr_bsc, g_pars.sccp_addr_msc,
				     f_gen_handover_req()));
	BSSAP.receive(RAN_Conn_Prim:MSC_CONN_PRIM_CONF_IND);

	/* The RSL Emulation magically accepts the Chan Activ behind the scenes. */

	var PDU_BSSAP rx_bssap;
	var octetstring ho_command_str;

	BSSAP.receive(tr_BSSMAP_HandoverRequestAcknowledge(?)) -> value rx_bssap;

	ho_command_str := rx_bssap.pdu.bssmap.handoverRequestAck.layer3Information.layer3info;
	log("Received L3 Info in HO Request Ack: ", ho_command_str);
	var PDU_ML3_NW_MS ho_command := dec_PDU_ML3_NW_MS(ho_command_str);
	log("L3 Info in HO Request Ack is ", ho_command);

	var GsmArfcn arfcn;
	var RslChannelNr actual_new_chan_nr;
	f_ChDesc2RslChanNr(ho_command.msgs.rrm.handoverCommand.channelDescription2,
			actual_new_chan_nr, arfcn);

	if (actual_new_chan_nr != new_chan_nr) {
		log("ERROR: osmo-bsc assigned a different lchan than we assumed above -- this test will fail now.",
		    " Assumed: ", new_chan_nr, " Assigned: ", actual_new_chan_nr);
		setverdict(fail);
		return;
	}
	log("Handover Command chan_nr is", actual_new_chan_nr);

	/* Now the MSC forwards the RR Handover Command to the other BSC, which
	 * tells the MS to handover to the new lchan. But the MS never shows up
	 * on the new lchan. */

	BSSAP.receive(tr_BSSMAP_HandoverFailure);

	/* Did osmo-bsc also send a Clear Request? */
	timer T := 0.5;
	T.start;
	alt {
	[] BSSAP.receive(tr_BSSMAP_ClearRequest);
	[] T.timeout { }
	}

	/* MSC plays along with a Clear Command (no matter whether osmo-bsc
	 * asked for it, this is a Handover Failure after all). */

	var myBSSMAP_Cause cause_val := GSM0808_CAUSE_RADIO_INTERFACE_FAILURE_REVERSION;
	var BssmapCause cause := enum2int(cause_val);
	BSSAP.send(ts_BSSMAP_ClearCommand(cause));

	f_expect_dlcx_conns();
	BSSAP.receive(tr_BSSMAP_ClearComplete);
	BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);

	f_sleep(1.0);
}
testcase TC_ho_in_fail_no_detect() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);

	f_ctrs_bsc_and_bts_handover_init();

	pars.sccp_addr_msc := g_bssap[0].sccp_addr_own;
	pars.sccp_addr_bsc := g_bssap[0].sccp_addr_peer;

	vc_conn := f_start_handler(refers(f_tc_ho_in_fail_no_detect), pars);
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:error");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:attempted");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:error");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

/* Same as f_tc_ho_in_fail_no_detect, but MSC fails to send a Clear Command */
private function f_tc_ho_in_fail_no_detect2(charstring id) runs on MSC_ConnHdlr {
	var RslChannelNr new_chan_nr := valueof(t_RslChanNr0(1, RSL_CHAN_NR_Bm_ACCH));
	f_rslem_register(0, new_chan_nr);
	g_chan_nr := new_chan_nr;
	f_sleep(1.0);

	f_create_mgcp_expect(ExpectCriteria:{omit,omit,omit});
	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);
	activate(as_Media(fail_on_dlcx := false));

	BSSAP.send(ts_BSSAP_Conn_Req(g_pars.sccp_addr_bsc, g_pars.sccp_addr_msc,
				     f_gen_handover_req()));
	BSSAP.receive(RAN_Conn_Prim:MSC_CONN_PRIM_CONF_IND);

	/* The RSL Emulation magically accepts the Chan Activ behind the scenes. */

	var PDU_BSSAP rx_bssap;
	var octetstring ho_command_str;

	BSSAP.receive(tr_BSSMAP_HandoverRequestAcknowledge(?)) -> value rx_bssap;

	ho_command_str := rx_bssap.pdu.bssmap.handoverRequestAck.layer3Information.layer3info;
	log("Received L3 Info in HO Request Ack: ", ho_command_str);
	var PDU_ML3_NW_MS ho_command := dec_PDU_ML3_NW_MS(ho_command_str);
	log("L3 Info in HO Request Ack is ", ho_command);

	var GsmArfcn arfcn;
	var RslChannelNr actual_new_chan_nr;
	f_ChDesc2RslChanNr(ho_command.msgs.rrm.handoverCommand.channelDescription2,
			actual_new_chan_nr, arfcn);

	if (actual_new_chan_nr != new_chan_nr) {
		log("ERROR: osmo-bsc assigned a different lchan than we assumed above -- this test will fail now.",
		    " Assumed: ", new_chan_nr, " Assigned: ", actual_new_chan_nr);
		setverdict(fail);
		return;
	}
	log("Handover Command chan_nr is", actual_new_chan_nr);

	/* Now the MSC forwards the RR Handover Command to the other BSC, which
	 * tells the MS to handover to the new lchan. But the MS never shows up
	 * on the new lchan. */

	BSSAP.receive(tr_BSSMAP_HandoverFailure);

	/* MSC plays dumb and sends no Clear Command */
	var PDU_BSSAP rx_clear_request;

	BSSAP.receive(tr_BSSMAP_ClearRequest) -> value rx_clear_request {
		var BssmapCause cause := bit2int(rx_clear_request.pdu.bssmap.clearRequest.cause.causeValue);
		BSSAP.send(ts_BSSMAP_ClearCommand(cause));
	};
	f_expect_dlcx_conns();
	BSSAP.receive(tr_BSSMAP_ClearComplete);
	BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);

	f_sleep(1.0);
}
testcase TC_ho_in_fail_no_detect2() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);

	f_ctrs_bsc_and_bts_handover_init();

	pars.sccp_addr_msc := g_bssap[0].sccp_addr_own;
	pars.sccp_addr_bsc := g_bssap[0].sccp_addr_peer;

	vc_conn := f_start_handler(refers(f_tc_ho_in_fail_no_detect2), pars);
	vc_conn.done;

	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:error");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:attempted");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_in:error");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

/* An incoming inter-BSC HO can either issue the Handover Request message attached to the initial SCCP N-Connect (as in
 * the other tests we have so far), or the first CR can be "empty" with the BSSAP request following later. Test the
 * empty N-Connect case. */
testcase TC_ho_into_this_bsc_sccp_cr_without_bssap() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	pars.inter_bsc_ho_in__ho_req_in_initial_sccp_cr := false;
	f_tc_ho_into_this_bsc_main(pars);
	f_shutdown_helper();
}

type record of charstring Commands;

private function f_bts_0_cfg(TELNETasp_PT pt, Commands cmds := {})
{
	f_vty_enter_cfg_bts(pt, 0);
	for (var integer i := 0; i < sizeof(cmds); i := i+1) {
		f_vty_transceive(pt, cmds[i]);
	}
	f_vty_transceive(pt, "end");
}

private function f_cs7_inst_0_cfg(TELNETasp_PT pt, Commands cmds := {})
{
	f_vty_enter_cfg_cs7_inst(pt, 0);
	for (var integer i := 0; i < sizeof(cmds); i := i+1) {
		f_vty_transceive(pt, cmds[i]);
	}
	f_vty_transceive(pt, "end");
}

private function f_probe_for_handover(charstring log_label,
				      charstring log_descr,
				      charstring handover_vty_cmd,
				      boolean expect_handover,
				      boolean is_inter_bsc_handover := false,
				      template uint3_t expect_target_tsc := ?)
runs on MSC_ConnHdlr
{
	/* We're going to thwart any and all handover attempts, just be ready to handle (and ignore) handover target
	 * lchans to be established on bts 1 or bts 2. */
	f_rslem_suspend(RSL1_PROC);
	f_rslem_suspend(RSL2_PROC);

	var RSL_Message rsl;

	var charstring log_msg := " (expecting handover)"
	if (not expect_handover) {
		log_msg := " (expecting NO handover)";
	}
	log("f_probe_for_handover starting: " & log_label & ": " & log_descr & log_msg);
	f_vty_transceive(BSCVTY, handover_vty_cmd);

	timer T := 2.0;
	T.start;

	alt {
	[] RSL.receive(tr_RSL_DATA_REQ(g_chan_nr)) -> value rsl {
		var PDU_ML3_NW_MS l3 := dec_PDU_ML3_NW_MS(rsl.ies[2].body.l3_info.payload);
		log("Rx L3 from net: ", l3);
		if (ischosen(l3.msgs.rrm.handoverCommand)) {
			var RslChannelNr new_chan_nr;
			var GsmArfcn arfcn;
			f_ChDesc2RslChanNr(l3.msgs.rrm.handoverCommand.channelDescription2,
					   new_chan_nr, arfcn);
			log("Handover to new chan ", new_chan_nr, " on ARFCN ", arfcn);
			log(l3.msgs.rrm.handoverCommand);

			/* Verify correct TSC in handoverCommand */
			var uint3_t got_tsc := rr_chan_desc_tsc(l3.msgs.rrm.handoverCommand.channelDescription2);
			if (not match(got_tsc, expect_target_tsc)) {
				setverdict(fail, "RR Handover Command: unexpected TSC in Channel Description: expected ",
					   expect_target_tsc, " got ", got_tsc);
				mtc.stop;
			} else {
				log("handoverCommand: verified TSC = ", got_tsc, " (matches ",
				    expect_target_tsc, ")");
			}

			/* Need to register for new lchan on new BTS -- it's either bts 1 or bts 2.  It doesn't really
			 * matter on which BTS it really is, we're not going to follow through an entire handover
			 * anyway. */
			f_rslem_register(0, new_chan_nr, RSL1_PROC);
			f_rslem_resume(RSL1_PROC);
			f_rslem_register(0, new_chan_nr, RSL2_PROC);
			f_rslem_resume(RSL2_PROC);

			if (expect_handover and not is_inter_bsc_handover) {
				setverdict(pass);
				log("f_probe_for_handover(" & log_label & "): Got RSL Handover Command as expected.");
			} else {
				setverdict(fail, "f_probe_for_handover(" & log_label & "): Expected none, but got RSL Handover Command. "
						 & log_label & ": " & log_descr);
			}

			log("f_probe_for_handover(" & log_label & "): Ending the test: Handover Failure stops the procedure.");
			/* osmo-bsc has triggered Handover. That's all we need to know for this test, reply with
			 * Handover Failure. */
			f_rsl_send_l3(ts_RRM_HandoverFailure('00'O));

			/* target BTS is told to release lchan again; don't care which BTS nor what messages. */
			f_sleep(0.5);
			RSL1.clear;
			RSL2.clear;
			log("f_probe_for_handover(" & log_label & "): done (got RSL Handover Command)");
			break;
		} else {
			repeat;
		}
		}
	[] BSSAP.receive(tr_BSSMAP_HandoverRequired) {
			if (expect_handover and is_inter_bsc_handover) {
				setverdict(pass);
				log("f_probe_for_handover(" & log_label & "): Got BSSMAP Handover Required as expected.");
			} else {
				setverdict(fail, "f_probe_for_handover(" & log_label & "): Expected none, but got BSSMAP Handover Required. "
						 & log_label & ": " & log_descr);
			}

			log("f_probe_for_handover(" & log_label & "): done (got BSSMAP Handover Required)");

			/* Note: f_tc_ho_neighbor_config_start() sets T7, the timeout for BSSMAP Handover Required, to
			 * 1 second. There is no legal way to quickly abort a handover after a BSSMAP Handover Required,
			 * setting a short timeout and waiting is the only way. */
			log("f_probe_for_handover(" & log_label & "): waiting for inter-BSC HO to time out...");
			f_sleep(1.5);
			log("f_probe_for_handover(" & log_label & "): ...done");

			break;
		}
	[] T.timeout {
		if (expect_handover) {
			setverdict(fail, "f_probe_for_handover(" & log_label & "): Expected Handover, but got none. "
					 & log_label & ": " & log_descr);
		} else {
			setverdict(pass);
			log("f_probe_for_handover(" & log_label & "): Got no Handover, as expected.");
		}
		log("f_probe_for_handover(" & log_label & "): done (got no Handover)");
		break;
		}
	}

	f_rslem_resume(RSL1_PROC);
	f_rslem_resume(RSL2_PROC);
	f_sleep(3.0);
	RSL.clear;

	log("f_probe_for_handover(" & log_label & "): done clearing");
}

/* Test the effect of various neighbor configuration scenarios:
 *
 * To avoid complexity, block off any actual handover operation, and always remain on the lchan at bts 0.
 * Reconfigure the neighbors for bts 0, trigger a Handover, and probe whether osmo-bsc does or doesn't start HO.
 */
private function f_tc_ho_neighbor_config_start() runs on MSC_ConnHdlr {
	g_pars := f_gen_test_hdlr_pars();
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();

	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));

	/* Establish lchan at bts 0 */
	f_establish_fully(ass_cmd, exp_compl);

	/* Shorten the inter-BSC Handover timeout, to not wait so long for inter-BSC Handovers */
	f_vty_enter_cfg_network(BSCVTY);
	f_vty_transceive(BSCVTY, "timer T7 1");
	f_vty_transceive(BSCVTY, "end");
}

private function f_tc_ho_neighbor_config_1(charstring id) runs on MSC_ConnHdlr {
	f_tc_ho_neighbor_config_start();

	/*
	 * bts 0 ARFCN 871 BSIC 10
	 * bts 1 ARFCN 871 BSIC 11
	 * bts 2 ARFCN 871 BSIC 12
	 * bts 3 ARFCN 871 BSIC 12  serves as ambiguity for bts 2, re-using the ARFCN+BSIC
	 */

	log("f_tc_ho_neighbor_config: 1. No 'neighbor' config");
	f_bts_0_cfg(BSCVTY, {"no neighbors"});
	f_probe_for_handover("1.a", "HO to bts 1 works, implicitly listed as neighbor (legacy behavior when none are configured)",
			"handover any to arfcn 871 bsic 11",
			true, expect_target_tsc := c_BtsParams[1].tsc);

	f_probe_for_handover("1.b", "HO to unknown cell does not start",
			"handover any to arfcn 13 bsic 39",
			false);

	f_probe_for_handover("1.c", "HO to 871-12 is ambiguous = error",
			"handover any to arfcn 871 bsic 12",
			false);

	f_probe_for_handover("1.d", "HO to 871-11 still works (verify that this test properly cleans up)",
			"handover any to arfcn 871 bsic 11",
			true, expect_target_tsc := c_BtsParams[1].tsc);

	f_perform_clear();
}
testcase TC_ho_neighbor_config_1() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(3, true, guard_timeout := 60.0);
	f_sleep(1.0);
	f_ctrs_bsc_and_bts_handover_init();
	vc_conn := f_start_handler(refers(f_tc_ho_neighbor_config_1));
	vc_conn.done;

	/* f_tc_ho_neighbor_config_start() */
	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");

	/* 1.a */
	/* "failed" means a handover was triggered and started (which is all this test aims for) and the test ended the
	 * handover quickly by sending a Handover Failure message. */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:failed");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:attempted");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:failed");
	f_ctrs_bts_add(1, "incoming_intra_bsc_ho:attempted");
	f_ctrs_bts_add(1, "incoming_intra_bsc_ho:failed");

	/* 1.b */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:error");

	/* 1.c */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:error");

	/* 1.d */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:failed");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:attempted");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:failed");
	f_ctrs_bts_add(1, "incoming_intra_bsc_ho:attempted");
	f_ctrs_bts_add(1, "incoming_intra_bsc_ho:failed");

	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

private function f_tc_ho_neighbor_config_2(charstring id) runs on MSC_ConnHdlr {
	f_tc_ho_neighbor_config_start();

	/*
	 * bts 0 ARFCN 871 BSIC 10
	 * bts 1 ARFCN 871 BSIC 11
	 * bts 2 ARFCN 871 BSIC 12
	 * bts 3 ARFCN 871 BSIC 12  serves as ambiguity for bts 2, re-using the ARFCN+BSIC
	 */

	log("f_tc_ho_neighbor_config: 2. explicit local neighbor: 'neighbor bts 1'");
	f_bts_0_cfg(BSCVTY, {"neighbor bts 1"});
	f_sleep(0.5);

	f_probe_for_handover("2.a", "HO to bts 1 works, explicitly listed as neighbor",
			"handover any to arfcn 871 bsic 11",
			true, expect_target_tsc := c_BtsParams[1].tsc);

	f_probe_for_handover("2.b", "HO to bts 2 doesn't work, not listed as neighbor",
			"handover any to arfcn 871 bsic 12",
			false);
	f_perform_clear();
}
testcase TC_ho_neighbor_config_2() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(3, true, guard_timeout := 50.0);
	f_sleep(1.0);
	f_ctrs_bsc_and_bts_handover_init();
	vc_conn := f_start_handler(refers(f_tc_ho_neighbor_config_2));
	vc_conn.done;

	/* f_tc_ho_neighbor_config_start() */
	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");

	/* 2.a */
	/* "failed" means a handover was triggered and started (which is all this test aims for) and the test ended the
	 * handover quickly by sending a Handover Failure message. */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:failed");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:attempted");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:failed");
	f_ctrs_bts_add(1, "incoming_intra_bsc_ho:attempted");
	f_ctrs_bts_add(1, "incoming_intra_bsc_ho:failed");

	/* 2.b */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:error");

	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

private function f_tc_ho_neighbor_config_3(charstring id) runs on MSC_ConnHdlr {
	f_tc_ho_neighbor_config_start();

	/*
	 * bts 0 ARFCN 871 BSIC 10
	 * bts 1 ARFCN 871 BSIC 11
	 * bts 2 ARFCN 871 BSIC 12
	 * bts 3 ARFCN 871 BSIC 12  serves as ambiguity for bts 2, re-using the ARFCN+BSIC
	 */

	log("f_tc_ho_neighbor_config: 3. explicit local neighbor: 'neighbor bts 2'");
	f_bts_0_cfg(BSCVTY, {"no neighbors", "neighbor bts 2"});
	f_sleep(0.5);

	f_probe_for_handover("3.a", "HO to bts 1 doesn't work, not listed as neighbor",
			"handover any to arfcn 871 bsic 11",
			false);
	f_probe_for_handover("3.b", "HO to bts 2 works, explicitly listed as neighbor; no ambiguity because bts 3 is not listed as neighbor",
			"handover any to arfcn 871 bsic 12",
			true, expect_target_tsc := c_BtsParams[2].tsc);
	f_perform_clear();
}
testcase TC_ho_neighbor_config_3() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(3, true, guard_timeout := 50.0);
	f_sleep(1.0);
	f_ctrs_bsc_and_bts_handover_init();
	vc_conn := f_start_handler(refers(f_tc_ho_neighbor_config_3));
	vc_conn.done;

	/* f_tc_ho_neighbor_config_start() */
	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");

	/* 3.a */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:error");

	/* 3.b */
	/* "failed" means a handover was triggered and started (which is all this test aims for) and the test ended the
	 * handover quickly by sending a Handover Failure message. */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:failed");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:attempted");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:failed");
	f_ctrs_bts_add(2, "incoming_intra_bsc_ho:attempted");
	f_ctrs_bts_add(2, "incoming_intra_bsc_ho:failed");

	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

private function f_tc_ho_neighbor_config_4(charstring id) runs on MSC_ConnHdlr {
	f_tc_ho_neighbor_config_start();

	/*
	 * bts 0 ARFCN 871 BSIC 10
	 * bts 1 ARFCN 871 BSIC 11
	 * bts 2 ARFCN 871 BSIC 12
	 * bts 3 ARFCN 871 BSIC 12  serves as ambiguity for bts 2, re-using the ARFCN+BSIC
	 */

	log("f_tc_ho_neighbor_config: 4. explicit remote neighbor: 'neighbor lac 99 arfcn 123 bsic 45'");
	f_bts_0_cfg(BSCVTY, {"no neighbors", "neighbor lac 99 arfcn 123 bsic 45"});
	f_sleep(0.5);

	f_probe_for_handover("4.a", "HO to bts 1 doesn't work, not listed as neighbor",
			"handover any to arfcn 871 bsic 11",
			false);
	f_probe_for_handover("4.b", "HO to bts 2 doesn't work, not listed as neighbor",
			"handover any to arfcn 871 bsic 12",
			false);
	f_probe_for_handover("4.c", "HO to 123-45 triggers inter-BSC HO",
			"handover any to arfcn 123 bsic 45",
			true, true);
	f_perform_clear();
}
testcase TC_ho_neighbor_config_4() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(3, true, guard_timeout := 50.0);
	f_sleep(1.0);
	f_ctrs_bsc_and_bts_handover_init();
	vc_conn := f_start_handler(refers(f_tc_ho_neighbor_config_4));
	vc_conn.done;

	/* f_tc_ho_neighbor_config_start() */
	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");

	/* 4.a */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:error");

	/* 4.b */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:error");

	/* 4.c */
	/* "timeout" means a handover was triggered and started (which is all this test aims for) and the test ended the
	 * handover quickly by timing out after the Handover Required message */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:timeout");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:attempted");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:timeout");

	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

private function f_tc_ho_neighbor_config_5(charstring id) runs on MSC_ConnHdlr {
	f_tc_ho_neighbor_config_start();

	/*
	 * bts 0 ARFCN 871 BSIC 10
	 * bts 1 ARFCN 871 BSIC 11
	 * bts 2 ARFCN 871 BSIC 12
	 * bts 3 ARFCN 871 BSIC 12  serves as ambiguity for bts 2, re-using the ARFCN+BSIC
	 */

	log("f_tc_ho_neighbor_config: 5. explicit remote neighbor re-using ARFCN+BSIC: 'neighbor lac 99 arfcn 871 bsic 12'");
	f_bts_0_cfg(BSCVTY, {"no neighbors", "neighbor lac 99 arfcn 871 bsic 12"});
	f_sleep(0.5);

	f_probe_for_handover("5.a", "HO to 871-12 triggers inter-BSC HO (ignoring local cells with same ARFCN+BSIC)",
			"handover any to arfcn 871 bsic 12",
			true, true);
	f_perform_clear();
}
testcase TC_ho_neighbor_config_5() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(3, true);
	f_sleep(1.0);
	f_ctrs_bsc_and_bts_handover_init();
	vc_conn := f_start_handler(refers(f_tc_ho_neighbor_config_5));
	vc_conn.done;

	/* f_tc_ho_neighbor_config_start() */
	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");

	/* 5 */
	/* "timeout" means a handover was triggered and started (which is all this test aims for) and the test ended the
	 * handover quickly by timing out after the Handover Required message */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:timeout");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:attempted");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:timeout");

	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

private function f_tc_ho_neighbor_config_6(charstring id) runs on MSC_ConnHdlr {
	f_tc_ho_neighbor_config_start();

	/*
	 * bts 0 ARFCN 871 BSIC 10
	 * bts 1 ARFCN 871 BSIC 11
	 * bts 2 ARFCN 871 BSIC 12
	 * bts 3 ARFCN 871 BSIC 12  serves as ambiguity for bts 2, re-using the ARFCN+BSIC
	 */

	log("f_tc_ho_neighbor_config: 6. config error: explicit local and remote neighbors with ambiguous ARFCN+BSIC:"
	    & " 'neighbor bts 2; neighbor lac 99 arfcn 871 bsic 12'");
	f_bts_0_cfg(BSCVTY, {"no neighbors", "neighbor bts 2", "neighbor lac 99 arfcn 871 bsic 12"});
	f_sleep(0.5);

	f_probe_for_handover("6.a", "HO to 871-12 is ambiguous = error",
			"handover any to arfcn 871 bsic 12",
			false);
	f_perform_clear();
}
testcase TC_ho_neighbor_config_6() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(3, true);
	f_sleep(1.0);
	f_ctrs_bsc_and_bts_handover_init();
	vc_conn := f_start_handler(refers(f_tc_ho_neighbor_config_6));
	vc_conn.done;

	/* f_tc_ho_neighbor_config_start() */
	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");

	/* 6.a */
	/* "timeout" means a handover was triggered and started (which is all this test aims for) and the test ended the
	 * handover quickly by timing out after the Handover Required message */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:error");

	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

private function f_tc_ho_neighbor_config_7(charstring id) runs on MSC_ConnHdlr {
	f_tc_ho_neighbor_config_start();

	/*
	 * bts 0 ARFCN 871 BSIC 10
	 * bts 1 ARFCN 871 BSIC 11
	 * bts 2 ARFCN 871 BSIC 12
	 * bts 3 ARFCN 871 BSIC 12  serves as ambiguity for bts 2, re-using the ARFCN+BSIC
	 */

	log("f_tc_ho_neighbor_config: 7. explicit local and remote neighbors:"
	    & " 'neighbor bts 2; neighbor lac 99 arfcn 123 bsic 45'");
	f_bts_0_cfg(BSCVTY, {"no neighbors", "neighbor bts 2", "neighbor lac 99 arfcn 123 bsic 45"});
	f_sleep(0.5);

	f_probe_for_handover("7.a", "HO to 871-12 does HO to bts 2",
			"handover any to arfcn 871 bsic 12",
			true, expect_target_tsc := c_BtsParams[2].tsc);
	f_probe_for_handover("7.b", "HO to 123-45 triggers inter-BSC HO",
			"handover any to arfcn 123 bsic 45",
			true, true);
	f_perform_clear();
}
testcase TC_ho_neighbor_config_7() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	f_init(3, true, guard_timeout := 50.0);
	f_sleep(1.0);
	f_ctrs_bsc_and_bts_handover_init();
	vc_conn := f_start_handler(refers(f_tc_ho_neighbor_config_7));
	vc_conn.done;

	/* f_tc_ho_neighbor_config_start() */
	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");

	/* 7.a */
	/* "failed" means a handover was triggered and started (which is all this test aims for) and the test ended the
	 * handover quickly by sending a Handover Failure message. */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:failed");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:attempted");
	f_ctrs_bsc_and_bts_add(0, "intra_bsc_ho:failed");
	f_ctrs_bts_add(2, "incoming_intra_bsc_ho:attempted");
	f_ctrs_bts_add(2, "incoming_intra_bsc_ho:failed");

	/* 7.b */
	/* "timeout" means a handover was triggered and started (which is all this test aims for) and the test ended the
	 * handover quickly by timing out after the Handover Required message */
	f_ctrs_bsc_and_bts_add(0, "handover:attempted");
	f_ctrs_bsc_and_bts_add(0, "handover:timeout");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:attempted");
	f_ctrs_bsc_and_bts_add(0, "interbsc_ho_out:timeout");

	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

/* OS#3041: Open and close N connections in a normal fashion, and expect no
 * BSSMAP Reset just because of that. */
testcase TC_bssap_rlsd_does_not_cause_bssmap_reset() runs on test_CT {
	var default d;
	var integer i;
	var DchanTuple dt;

	f_init();

	/* Wait for initial BSSMAP Reset to pass */
	f_sleep(4.0);

	d := activate(no_bssmap_reset());

	/* Setup up a number of connections and RLSD them again from the MSC
	 * side. In the buggy behavior, the fourth one triggers BSSMAP Reset.
	 * Let's do it some more times for good measure. */
	for (i := 0; i < 4; i := i+1) {
		/* Since we're doing a lot of runs, give each one a fresh
		 * T_guard from the top. */
		T_guard.start;

		/* Setup a BSSAP connection and clear it right away. This is
		 * the MSC telling the BSC about a planned release, it's not an
		 * erratic loss of a connection. */
		dt := f_est_dchan(int2oct(i,1), 23+i, '00010203040506'O);

		/* MSC disconnects (RLSD). */
		BSSAP.send(ts_BSSAP_DISC_req(dt.sccp_conn_id, 0));
	}

	/* In the buggy behavior, a timeout of 2 seconds happens between above
	 * trigger (logs "SIGTRAN connection down, reconnecting...") and the
	 * actual BSSMAP Reset. Wait a bit longer just to make sure. */
	f_sleep(4.0);

	deactivate(d);
	f_shutdown_helper();
}

/* OS#3041: Open and close N connections in a normal fashion, and expect no
 * BSSMAP Reset just because of that. Invoke the release by a BSSMAP Clear from
 * the MSC. */
testcase TC_bssmap_clear_does_not_cause_bssmap_reset() runs on test_CT {
	var default d;
	var integer i;
	var DchanTuple dt;
	var BSSAP_N_DATA_ind rx_di;
	var myBSSMAP_Cause cause_val := GSM0808_CAUSE_CALL_CONTROL;
	var BssmapCause cause := enum2int(cause_val);

	f_init();

	/* Wait for initial BSSMAP Reset to pass */
	f_sleep(4.0);

	d := activate(no_bssmap_reset());

	/* Setup up a number of connections and RLSD them again from the MSC
	 * side. In the buggy behavior, the fourth one triggers BSSMAP Reset.
	 * Let's do it some more times for good measure. */
	for (i := 0; i < 8; i := i+1) {
		/* Since we're doing a lot of runs, give each one a fresh
		 * T_guard from the top. */
		T_guard.start;

		/* Setup a BSSAP connection and clear it right away. This is
		 * the MSC telling the BSC about a planned release, it's not an
		 * erratic loss of a connection. */
		dt := f_est_dchan(int2oct(i,1), 23+i, '00010203040506'O);

		/* Instruct BSC to clear channel */
		BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(cause)));

		/* expect BSC to disable the channel */
		f_exp_chan_rel_and_clear(dt);
	}

	/* In the buggy behavior, a timeout of 2 seconds happens between above
	 * trigger (logs "SIGTRAN connection down, reconnecting...") and the
	 * actual BSSMAP Reset. Wait a bit longer just to make sure. */
	f_sleep(4.0);

	deactivate(d);
	f_shutdown_helper();
}

/* OS#3041: Open and close N connections in a normal fashion, and expect no
 * BSSMAP Reset just because of that. Close connections from the MS side with a
 * Release Ind on RSL. */
testcase TC_ms_rel_ind_does_not_cause_bssmap_reset() runs on test_CT {
	var default d;
	var integer i;
	var DchanTuple dt;
	var BSSAP_N_DATA_ind rx_di;
	var integer j;

	f_init();

	/* Wait for initial BSSMAP Reset to pass */
	f_sleep(4.0);

	d := activate(no_bssmap_reset());

	/* Setup up a number of connections and RLSD them again from the MSC
	 * side. In the buggy behavior, the fourth one triggers BSSMAP Reset.
	 * Let's do it some more times for good measure. */
	for (i := 0; i < 8; i := i+1) {
		/* Since we're doing a lot of runs, give each one a fresh
		 * T_guard from the top. */
		T_guard.start;

		/* Setup a BSSAP connection and clear it right away. This is
		 * the MSC telling the BSC about a planned release, it's not an
		 * erratic loss of a connection. */
		dt := f_est_dchan('23'O, 23, '00010203040506'O);

		/* simulate RLL REL IND */
		f_ipa_tx(ts_RSL_REL_IND(dt.rsl_chan_nr, valueof(ts_RslLinkID_DCCH(0))));

		/* expect Clear Request on MSC side */
		BSSAP.receive(tr_BSSAP_DATA_ind(dt.sccp_conn_id, tr_BSSMAP_ClearRequest)) -> value rx_di;

		/* Instruct BSC to clear channel */
		var BssmapCause cause := bit2int(rx_di.userData.pdu.bssmap.clearRequest.cause.causeValue);
		BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(cause)));

		/* expect BSC to disable the channel */
		f_exp_chan_rel_and_clear(dt);
	}

	/* In the buggy behavior, a timeout of 2 seconds happens between above
	 * trigger (logs "SIGTRAN connection down, reconnecting...") and the
	 * actual BSSMAP Reset. Wait a bit longer just to make sure. */
	f_sleep(4.0);

	deactivate(d);
	f_shutdown_helper();
}

/***********************************************************************
 * IPA style dynamic PDCH
 ***********************************************************************/

private function f_dyn_ipa_pdch_act(integer bts_nr, integer trx_nr, integer ts_nr,
				    template (omit) RSL_Cause nack := omit)
runs on test_CT {
	var RslChannelNr chan_nr := valueof(t_RslChanNr_Bm(ts_nr));
	var RSL_Message rsl_unused;
	/* ask BSC via VTY to activate a given IPA style chan as PDCH */
	f_vty_ts_action("pdch activate", bts_nr, trx_nr, ts_nr);
	/* expect the BSC to issue the related RSL command */
	rsl_unused := f_exp_ipa_rx(tr_RSL_IPA_PDCH_ACT(chan_nr));
	if (istemplatekind(nack, "omit")) {
		/* respond with a related acknowledgement */
		f_ipa_tx(ts_RSL_IPA_PDCH_ACT_ACK(chan_nr, ts_RSL_IE_FrameNumber(2342)));
	} else {
		f_ipa_tx(ts_RSL_IPA_PDCH_ACT_NACK(chan_nr, valueof(nack)));
	}
}

private function f_dyn_ipa_pdch_deact(integer bts_nr, integer trx_nr, integer ts_nr,
				      template (omit) RSL_Cause nack := omit)
runs on test_CT {
	var RslChannelNr chan_nr := valueof(t_RslChanNr_Bm(ts_nr));
	var RSL_Message rsl_unused;
	/* ask BSC via VTY to activate a given IPA style chan as PDCH */
	f_vty_ts_action("pdch deactivate", bts_nr, trx_nr, ts_nr);
	/* expect the BSC to issue the related RSL command */
	rsl_unused := f_exp_ipa_rx(tr_RSL_IPA_PDCH_DEACT(chan_nr));
	if (istemplatekind(nack, "omit")) {
		/* respond with a related acknowledgement */
		f_ipa_tx(ts_RSL_IPA_PDCH_DEACT_ACK(chan_nr));
	} else {
		f_ipa_tx(ts_RSL_IPA_PDCH_DEACT_NACK(chan_nr, valueof(nack)));
	}
}

private function f_ts_dyn_mode_get(integer bts_nr, integer trx_nr, integer ts_nr)
runs on test_CT return charstring {
	var charstring cmd, resp;
	cmd := "show timeslot "&int2str(bts_nr)&" "&int2str(trx_nr)&" "&int2str(ts_nr);
	return f_vty_transceive_match_regexp_retry(BSCVTY, cmd, "*\((*)\)*", 0, 4, 1.0);
}

private function f_ts_dyn_mode_assert(integer bts_nr, integer trx_nr, integer ts_nr,
					template charstring exp)
runs on test_CT {
	var charstring mode := f_ts_dyn_mode_get(bts_nr, trx_nr, ts_nr);
	if (not match(mode, exp)) {
		setverdict(fail, "Unexpected TS Mode: ", mode);
		mtc.stop;
	}
}

private function f_ts_set_chcomb(integer bts_nr, integer trx_nr, integer ts_nr, charstring chcomb)
runs on test_CT {
	f_vty_enter_cfg_ts(BSCVTY, bts_nr, trx_nr, ts_nr);
	f_vty_transceive(BSCVTY, "phys_chan_config " & chcomb);
	f_vty_transceive(BSCVTY, "end");
}


private function f_ts_reset_chcomb(integer bts_nr) runs on test_CT {
	var integer i;
	for (i := 0; i < 8; i := i + 1) {
		f_ts_set_chcomb(bts_nr, 0, i, phys_chan_config[i]);
	}
}

private const charstring TCHF_MODE := "TCH/F mode";
private const charstring TCHH_MODE := "TCH/H mode";
private const charstring PDCH_MODE := "PDCH mode";
private const charstring NONE_MODE := "NONE mode";
private const charstring SDCCH8_MODE := "SDCCH8 mode";

/* Test IPA PDCH activation / deactivation triggered by VTY */
testcase TC_dyn_pdch_ipa_act_deact() runs on test_CT {
	var RSL_Message rsl_unused;

	/* change Timeslot 6 before f_init() starts RSL */
	f_init_vty();
	f_ts_set_chcomb(0, 0, 6, "TCH/F_PDCH");
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1, false);
	f_sleep(1.0);

	var RslChannelNr chan_nr := valueof(t_RslChanNr_Bm(6));

	log("TCH/F_PDCH pchan starts out in TCH/F mode:");
	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, TCHF_MODE);
	/* The BSC will activate the dynamic PDCH by default, so confirm that */
	rsl_unused := f_exp_ipa_rx(tr_RSL_IPA_PDCH_ACT(chan_nr));
	f_ipa_tx(ts_RSL_IPA_PDCH_ACT_ACK(chan_nr, ts_RSL_IE_FrameNumber(2342)));
	f_sleep(1.0);
	log("TCH/F_PDCH pchan, PDCH ACT was ACKed, so now in PDCH mode:");
	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, PDCH_MODE);

	/* De-activate it via VTY */
	f_dyn_ipa_pdch_deact(0, 0, chan_nr.tn);
	f_sleep(1.0);
	log("TCH/F_PDCH pchan, PDCH DEACT via VTY, so now back in TCH/F mode:");
	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, TCHF_MODE);

	/* re-activate it via VTY */
	f_dyn_ipa_pdch_act(0, 0, chan_nr.tn);
	f_sleep(1.0);
	log("TCH/F_PDCH pchan, PDCH ACT via VTY, so now in PDCH mode:");
	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, PDCH_MODE);

	/* and finally de-activate it again */
	f_dyn_ipa_pdch_deact(0, 0, chan_nr.tn);
	f_sleep(1.0);
	log("TCH/F_PDCH pchan, PDCH DEACT via VTY, so now back in TCH/F mode:");
	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, TCHF_MODE);

	/* clean up config */
	f_ts_set_chcomb(0, 0, 6, "PDCH");

	f_shutdown_helper();
}

/* Test IPA PDCH activation NACK */
testcase TC_dyn_pdch_ipa_act_nack() runs on test_CT {
	var RSL_Message rsl_unused;

	/* change Timeslot 6 before f_init() starts RSL */
	f_init_vty();
	f_ts_set_chcomb(0, 0, 6, "TCH/F_PDCH");
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1, false);
	f_sleep(1.0);

	var RslChannelNr chan_nr := valueof(t_RslChanNr_Bm(6));

	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, TCHF_MODE);
	/* The BSC will activate the dynamic PDCH by default, so confirm that */
	rsl_unused := f_exp_ipa_rx(tr_RSL_IPA_PDCH_ACT(chan_nr));
	f_ipa_tx(ts_RSL_IPA_PDCH_ACT_ACK(chan_nr, ts_RSL_IE_FrameNumber(2342)));
	f_sleep(1.0);
	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, PDCH_MODE);

	/* De-activate it via VTY */
	f_dyn_ipa_pdch_deact(0, 0, chan_nr.tn);
	f_sleep(1.0);
	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, TCHF_MODE);

	/* re-activate it via VTY, but fail that; check BSC still assumes TCH/F mode */
	f_dyn_ipa_pdch_act(0, 0, chan_nr.tn, RSL_ERR_EQUIPMENT_FAIL);
	f_sleep(1.0);
	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, TCHF_MODE);

	/* clean up config */
	f_ts_set_chcomb(0, 0, 6, "PDCH");

	f_shutdown_helper();
}


/***********************************************************************
 * Osmocom style dynamic PDCH
 ***********************************************************************/

private function f_dyn_osmo_pdch_act(integer bts_nr, integer trx_nr, integer ts_nr,
				     template (omit) RSL_Cause nack := omit)
runs on test_CT {
	var RslChannelNr chan_nr := valueof(t_RslChanNr_PDCH(ts_nr));
	var RSL_Message rsl_unused;
	/* ask BSC via VTY to activate a given OSMO style chan as PDCH */
	/* FIXME: no VTY command to activate Osmocom PDCH !! */
	/* expect the BSC to issue the related RSL command */
	rsl_unused := f_exp_ipa_rx(tr_RSL_CHAN_ACT(chan_nr, ?));
	if (istemplatekind(nack, "omit")) {
		/* respond with a related acknowledgement */
		f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, 2342));
	} else {
		f_ipa_tx(ts_RSL_CHAN_ACT_NACK(chan_nr, valueof(nack)));
	}
}

private function f_dyn_osmo_pdch_deact(integer bts_nr, integer trx_nr, integer ts_nr,
				       template (omit) RSL_Cause nack := omit)
runs on test_CT {
	var RslChannelNr chan_nr := valueof(t_RslChanNr_PDCH(ts_nr));
	var RSL_Message rsl_unused;
	/* ask BSC via VTY to activate a given OSMO style chan as PDCH */
	/* FIXME: no VTY command to activate Osmocom PDCH !! */
	/* expect the BSC to issue the related RSL command */
	rsl_unused := f_exp_ipa_rx(tr_RSL_RF_CHAN_REL(chan_nr));
	if (istemplatekind(nack, "omit")) {
		/* respond with a related acknowledgement */
		f_ipa_tx(ts_RSL_RF_CHAN_REL_ACK(chan_nr));
	} else {
		//f_ipa_tx(ts_RSL_RF_CHAN_REL_NACK(chan_nr, valueof(nack)));
	}
}

/* Test Osmocom dyn PDCH activation / deactivation triggered by VTY */
testcase TC_dyn_pdch_osmo_act_deact() runs on test_CT {
	var RSL_Message rsl_unused;

	/* change Timeslot 6 before f_init() starts RSL */
	f_init_vty();
	f_ts_set_chcomb(0, 0, 6, "TCH/F_TCH/H_PDCH");
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1, false);
	f_sleep(1.0);

	var RslChannelNr chan_nr := valueof(t_RslChanNr_PDCH(6));

	log("TCH/F_TCH/H_PDCH pchan starts out in disabled mode:");
	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, NONE_MODE);
	/* The BSC will activate the dynamic PDCH by default, so confirm that */
	rsl_unused := f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(chan_nr));

	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, 2342));
	f_sleep(1.0);
	log("TCH/F_TCH/H_PDCH requested to PDCH ACT on startup, which was ACKed, so now in PDCH:");
	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, PDCH_MODE);

	/* clean up config */
	f_ts_set_chcomb(0, 0, 6, "PDCH");

	f_shutdown_helper();
}

/* Test Osmocom dyn PDCH activation NACK behavior */
testcase TC_dyn_pdch_osmo_act_nack() runs on test_CT {
	var RSL_Message rsl_unused;

	/* change Timeslot 6 before f_init() starts RSL */
	f_init_vty();
	f_ts_set_chcomb(0, 0, 6, "TCH/F_TCH/H_PDCH");
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1, false);
	f_sleep(1.0);

	var RslChannelNr chan_nr := valueof(t_RslChanNr_PDCH(6));

	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, NONE_MODE);
	/* The BSC will activate the dynamic PDCH by default, so confirm that */
	rsl_unused := f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(chan_nr));

	/* NACK this activation and expect the "show timeslot" mode still to be NONE */
	f_ipa_tx(ts_RSL_CHAN_ACT_NACK(chan_nr, RSL_ERR_EQUIPMENT_FAIL));
	f_sleep(1.0);
	f_ts_dyn_mode_assert(0, 0, chan_nr.tn, NONE_MODE);

	/* clean up config */
	f_ts_set_chcomb(0, 0, 6, "PDCH");

	f_shutdown_helper();
}

/* Test Osmocom dyn TS SDCCH8 activation / deactivation */
testcase TC_dyn_ts_sdcch8_act_deact() runs on test_CT {
	var RSL_Message rsl_unused, rsl_msg;
	var DchanTuple dt;
	var BSSAP_N_CONNECT_ind rx_c_ind;

	/* change Timeslot 6 before f_init() starts RSL */
	f_init_vty();
	f_ts_set_chcomb(0, 0, 6, "TCH/F_TCH/H_SDCCH8_PDCH");
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1, false);
	f_sleep(1.0);

	var RslChannelNr pdch_chan_nr := valueof(t_RslChanNr_PDCH(6));

	log("TCH/F_TCH/H_SDCCH8_PDCH pchan starts out in disabled mode:");
	f_ts_dyn_mode_assert(0, 0, pdch_chan_nr.tn, NONE_MODE);
	/* The BSC will activate the dynamic PDCH by default, so confirm that */
	rsl_unused := f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(pdch_chan_nr));

	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(pdch_chan_nr, 2342));
	f_sleep(1.0);
	log("TCH/F_TCH/H_SDCCH8_PDC requested to PDCH ACT on startup, which was ACKed, so now in PDCH:");
	f_ts_dyn_mode_assert(0, 0, pdch_chan_nr.tn, PDCH_MODE);

	/* Fill TS0 SDCCH channels (NOTE: only 3 SDCCH/4 channels are available
	 * on CCCH+SDCCH4+CBCH) */
	var DchanTuples sdcch_cleanup := {};
	var integer i;
	for (i := 0; i < NUM_SDCCH_PER_BTS; i := i + 1) {
		dt := f_est_dchan('23'O, i, '00010203040506'O);
		sdcch_cleanup := sdcch_cleanup & { dt };
	}

	/* Now the dyn ts is selected. First PDCH is released, then sdcch chan is activated */
	f_ipa_tx(ts_RSL_CHAN_RQD(int2oct(oct2int('23'O) + i, 1), 2342));
	rsl_unused := f_exp_ipa_rx(tr_RSL_RF_CHAN_REL(pdch_chan_nr));
	f_ipa_tx(ts_RSL_RF_CHAN_REL_ACK(pdch_chan_nr));

	rsl_msg := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));
	dt.rsl_chan_nr := rsl_msg.ies[0].body.chan_nr;
	dt.idx := {0, 0};

	f_ts_dyn_mode_assert(0, 0, dt.rsl_chan_nr.tn, SDCCH8_MODE);
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(dt.rsl_chan_nr, 2342));
	rsl_msg := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0));
	f_ts_dyn_mode_assert(0, 0, dt.rsl_chan_nr.tn, SDCCH8_MODE);

	f_ipa_tx(ts_RSL_EST_IND(dt.rsl_chan_nr, valueof(ts_RslLinkID_DCCH(0)), '1234'O));
	BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3('1234'O))) -> value rx_c_ind;
	dt.sccp_conn_id := rx_c_ind.connectionId;
	BSSAP.send(ts_BSSAP_CONNECT_res(dt.sccp_conn_id));

	/* Instruct BSC to clear channel */
	var BssmapCause cause := 0;
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(cause)));
	f_exp_chan_rel_and_clear(dt);

	/* The BSC will switch the TS back to PDCH once the only lchan using it is released: */
	rsl_unused := f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(pdch_chan_nr));
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(pdch_chan_nr, 2342));
	f_sleep(1.0);
	f_ts_dyn_mode_assert(0, 0, pdch_chan_nr.tn, PDCH_MODE);

	/* Clean up SDCCH lchans */
	for (i := 0; i < lengthof(sdcch_cleanup); i := i + 1) {
		f_perform_clear_test_ct(sdcch_cleanup[i]);
	}

	/* clean up config */
	f_ts_set_chcomb(0, 0, 6, "PDCH");

	f_shutdown_helper();
}

/* Validate all 8 subslots of a dynamics TS configured as SDCCH8 are used */
testcase TC_dyn_ts_sdcch8_all_subslots_used() runs on test_CT {
	var ASP_RSL_Unitdata rsl_ud;
	var integer i;
	var integer chreq_total, chreq_nochan;

	f_init_vty();
	for (i := 1; i < 8; i := i + 1) {
		if (i == 2) {
			f_ts_set_chcomb(0, 0, i, "TCH/F_TCH/H_SDCCH8_PDCH");
		} else {
			f_ts_set_chcomb(0, 0, i, "PDCH");
		}
	}
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1, guard_timeout := 60.0);

	/* The dyn TS want to activate PDCH mode, ACK that. */
	var RslChannelNr chan_nr;
	chan_nr := valueof(t_RslChanNr_PDCH(2));
	f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(chan_nr));
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, 2342));

	f_sleep(1.0);

	/* Exhaust all dedicated SDCCH lchans.
	/* GSM 44.018 Table 9.1.8.2:
	 * RA = '13'O -> Establishment cause = 0001xxxx (MS dual rate capable and asks for "SDCCH").
	 */
	var DchanTuples chan_cleanup := {};
	for (i := 0; i < NUM_SDCCH_PER_BTS; i := i+1) {
		chan_cleanup := chan_cleanup & { f_est_dchan('13'O, NUM_SDCCH_PER_BTS + i, '00010203040506'O) };
	}

	/* Only the dyn TS is still available. Its first lchan gets converted to SDCCH8 */
	chan_cleanup := chan_cleanup & { f_est_dchan_dyn('33'O, NUM_SDCCH_PER_BTS + i, '00010203040506'O) };
	/* Also occupy the seven other SDCCH of the dyn TS */
	for (i := 0; i < 7; i := i+1) {
		chan_cleanup := chan_cleanup & { f_est_dchan('33'O, NUM_SDCCH_PER_BTS + i, '00010203040506'O) };
	}

	/* Clean up SDCCH lchans */
	for (i := 0; i < lengthof(chan_cleanup); i := i + 1) {
		f_perform_clear_test_ct(chan_cleanup[i]);
	}

	/* clean up config */
	f_ts_reset_chcomb(0);

	f_shutdown_helper();
}

/* Test Osmocom dyn TS SDCCH8 activation / deactivation: If activating dyn TS as
   SDCCH8 would end up in having no free TCH, then BSC should decide to activate
   it as TCH directly instead. SYS#5309. */
testcase TC_dyn_ts_sdcch8_tch_call_act_deact() runs on test_CT {
	var RSL_Message rsl_unused, rsl_msg;
	var DchanTuple dt;
	var BSSAP_N_CONNECT_ind rx_c_ind;
	var integer i;

	/* change Timeslot 6 before f_init() starts RSL */
	f_init_vty();
	for (i := 1; i < 8; i := i + 1) {
		if (i == 6) {
			f_ts_set_chcomb(0, 0, i, "TCH/F_TCH/H_SDCCH8_PDCH");
		} else {
			f_ts_set_chcomb(0, 0, i, "PDCH");
		}
	}
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1, false);
	f_sleep(1.0);

	var RslChannelNr pdch_chan_nr := valueof(t_RslChanNr_PDCH(6));

	log("TCH/F_TCH/H_SDCCH8_PDCH pchan starts out in disabled mode:");
	f_ts_dyn_mode_assert(0, 0, pdch_chan_nr.tn, NONE_MODE);
	/* The BSC will activate the dynamic PDCH by default, so confirm that */
	rsl_unused := f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(pdch_chan_nr));

	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(pdch_chan_nr, 2342));
	f_sleep(1.0);
	log("TCH/F_TCH/H_SDCCH8_PDC requested to PDCH ACT on startup, which was ACKed, so now in PDCH:");
	f_ts_dyn_mode_assert(0, 0, pdch_chan_nr.tn, PDCH_MODE);

	/* Fill TS0 SDCCH channels (NOTE: only 3 SDCCH/4 channels are available
	 * on CCCH+SDCCH4+CBCH) */
	var DchanTuples chan_cleanup := {};
	var OCT1 ra := '43'O; /* RA containing reason=originating speech call*/
	for (i := 0; i < NUM_SDCCH_PER_BTS; i := i + 1) {
		dt := f_est_dchan(ra, i, '00010203040506'O);
		chan_cleanup := chan_cleanup & { dt };
	}

	/* Now the dyn ts is selected. First PDCH is released, then TCH chan is activated */
	f_ipa_tx(ts_RSL_CHAN_RQD(int2oct(oct2int(ra) + i, 1), 2342));
	rsl_unused := f_exp_ipa_rx(tr_RSL_RF_CHAN_REL(pdch_chan_nr));
	f_ipa_tx(ts_RSL_RF_CHAN_REL_ACK(pdch_chan_nr));

	rsl_msg := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));
	dt.rsl_chan_nr := rsl_msg.ies[0].body.chan_nr;
	dt.idx := {0, 0};

	f_ts_dyn_mode_assert(0, 0, dt.rsl_chan_nr.tn, TCHH_MODE);
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(dt.rsl_chan_nr, 2342));
	rsl_msg := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0));
	f_ts_dyn_mode_assert(0, 0, dt.rsl_chan_nr.tn, TCHH_MODE);

	f_ipa_tx(ts_RSL_EST_IND(dt.rsl_chan_nr, valueof(ts_RslLinkID_DCCH(0)), '1234'O));
	BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3('1234'O))) -> value rx_c_ind;
	dt.sccp_conn_id := rx_c_ind.connectionId;
	BSSAP.send(ts_BSSAP_CONNECT_res(dt.sccp_conn_id));

	/* Instruct BSC to clear channel */
	var BssmapCause cause := 0;
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(cause)));
	f_exp_chan_rel_and_clear(dt);

	/* The BSC will switch the TS back to PDCH once the only lchan using it is released: */
	rsl_unused := f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(pdch_chan_nr));
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(pdch_chan_nr, 2342));
	f_sleep(1.0);
	f_ts_dyn_mode_assert(0, 0, pdch_chan_nr.tn, PDCH_MODE);

	/* Clean up SDCCH lchans */
	for (i := 0; i < lengthof(chan_cleanup); i := i + 1) {
		f_perform_clear_test_ct(chan_cleanup[i]);
	}

	/* clean up config */
	f_ts_reset_chcomb(0);
	/* TODO: clean up other channels? */

	f_shutdown_helper();
}

/* Test Osmocom dyn TS SDCCH8 activation / deactivation when SDCCH fails at BTS */
testcase TC_dyn_ts_sdcch8_act_nack() runs on test_CT {
	var RSL_Message rsl_unused, rsl_msg;
	var DchanTuple dt;
	var BSSAP_N_CONNECT_ind rx_c_ind;
	var GsmRrMessage rr;

	/* change Timeslot 6 before f_init() starts RSL */
	f_init_vty();
	f_ts_set_chcomb(0, 0, 6, "TCH/F_TCH/H_SDCCH8_PDCH");
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1, false);
	f_sleep(1.0);

	var RslChannelNr pdch_chan_nr := valueof(t_RslChanNr_PDCH(6));

	log("TCH/F_TCH/H_SDCCH8_PDCH pchan starts out in disabled mode:");
	f_ts_dyn_mode_assert(0, 0, pdch_chan_nr.tn, NONE_MODE);
	/* The BSC will activate the dynamic PDCH by default, so confirm that */
	rsl_unused := f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(pdch_chan_nr));

	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(pdch_chan_nr, 2342));
	f_sleep(1.0);
	log("TCH/F_TCH/H_SDCCH8_PDC requested to PDCH ACT on startup, which was ACKed, so now in PDCH:");
	f_ts_dyn_mode_assert(0, 0, pdch_chan_nr.tn, PDCH_MODE);

	/* Fill TS0 SDCCH channels (NOTE: only 3 SDCCH/4 channels are available
	 * on CCCH+SDCCH4+CBCH) */
	var DchanTuples chan_cleanup := {};
	var integer i;
	for (i := 0; i < NUM_SDCCH_PER_BTS; i := i + 1) {
		dt := f_est_dchan('23'O, i, '00010203040506'O);
		chan_cleanup := chan_cleanup & { dt };
	}

	/* Now the dyn ts is selected. First PDCH is released, then sdcch chan is activated */
	f_ipa_tx(ts_RSL_CHAN_RQD(int2oct(oct2int('23'O) + i, 1), 2342));
	rsl_unused := f_exp_ipa_rx(tr_RSL_RF_CHAN_REL(pdch_chan_nr));
	f_ipa_tx(ts_RSL_RF_CHAN_REL_ACK(pdch_chan_nr));

	rsl_msg := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));
	dt.rsl_chan_nr := rsl_msg.ies[0].body.chan_nr;
	dt.idx := {0, 0};

	f_ts_dyn_mode_assert(0, 0, dt.rsl_chan_nr.tn, SDCCH8_MODE);
	f_ipa_tx(ts_RSL_CHAN_ACT_NACK(dt.rsl_chan_nr, RSL_ERR_EQUIPMENT_FAIL));
	rsl_msg := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0));
	rr := dec_GsmRrMessage(rsl_msg.ies[1].body.full_imm_ass_info.payload);
	if (rr.header.message_type != IMMEDIATE_ASSIGNMENT_REJECT) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Expected reject");
	}

	/* FIXME? Currently the TS stays in state BORKEN: */

	/* The BSC will switch the TS back to PDCH once the only lchan using it is released: */
	/* rsl_unused := f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(pdch_chan_nr));
	 * f_ipa_tx(ts_RSL_CHAN_ACT_ACK(pdch_chan_nr, 2342));
	 * f_sleep(1.0);
	 * f_ts_dyn_mode_assert(0, 0, pdch_chan_nr.tn, PDCH_MODE)
	 */

	/* Clean up SDCCH lchans */
	for (i := 0; i < lengthof(chan_cleanup); i := i + 1) {
		f_perform_clear_test_ct(chan_cleanup[i]);
	}

	/* clean up config */
	f_ts_set_chcomb(0, 0, 6, "PDCH");

	f_shutdown_helper();
}

testcase TC_chopped_ipa_ping() runs on test_CT {
	const Integers bsc_ipa_ports := {mp_bsc_rsl_port, mp_bsc_oml_port, mp_bsc_ctrl_port};
	for (var integer i := 0; i < lengthof(bsc_ipa_ports); i := i + 1) {
		IPA_Testing.f_run_TC_chopped_ipa_ping(mp_bsc_ip, bsc_ipa_ports[i], CONNECT_TO_SERVER);
	}
	f_shutdown_helper();
}

testcase TC_chopped_ipa_payload() runs on test_CT {
	const Integers bsc_ipa_ports := {mp_bsc_rsl_port, mp_bsc_oml_port
					/* TODO: mp_bsc_ctrl_port does not work yet */};
	for (var integer i := 0; i < lengthof(bsc_ipa_ports); i := i + 1) {
		IPA_Testing.f_run_TC_chopped_ipa_payload(mp_bsc_ip, bsc_ipa_ports[i], CONNECT_TO_SERVER);
	}
	f_shutdown_helper();
}

/* Verify the BSC sends the MS Power Parameters IE during CHAN ACT to make sure
   the BTS does autonomous MS power control loop */
testcase TC_assignment_verify_ms_power_params_ie() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	//pars.encr := valueof(t_EncrParams('01'O, f_rnd_octstring(8)));
	pars.exp_ms_power_params := true;

	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_assignment_fr_a5), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* Verify activation and deactivation of the BCCH carrier power reduction mode */
testcase TC_c0_power_red_mode() runs on test_CT {
	f_init(1);

	for (var integer red := 6; red >= 0; red := red - 2) {
		/* Configure BCCH carrier power reduction mode via the VTY */
		f_vty_transceive(BSCVTY, "bts 0 c0-power-reduction " & int2str(red));

		/* Expect Osmocom specific BS Power Control message on the RSL */
		var template (present) RSL_Message tr_rsl_pdu := tr_RSL_BS_PWR_CTRL(
			chan_nr := t_RslChanNr_BCCH(0),
			bs_power := tr_RSL_IE_BS_Power(red / 2));
		tr_rsl_pdu.msg_disc := tr_RSL_MsgDisc(RSL_MDISC_CCHAN, false);
		var RSL_Message unused := f_exp_ipa_rx(tr_rsl_pdu);

		/* Additionally verify the applied value over the CTRL interface */
		var CtrlValue cred := f_ctrl_get_bts(IPA_CTRL, 0, "c0-power-reduction");
		if (cred != int2str(red)) {
			setverdict(fail, "Unexpected BCCH carrier power reduction value ",
					 cred, " (expected ", red, ")");
		}
	}

	f_shutdown_helper();
}

/***********************************************************************
 * MSC Pooling
 ***********************************************************************/

template MobileIdentityLV ts_MI_TMSI_NRI_LV(integer nri_v, integer nri_bitlen := 10) :=
	ts_MI_TMSI_LV(tmsi := f_gen_tmsi(suffix := 0, nri_v := nri_v, nri_bitlen := nri_bitlen));

private function f_expect_lchan_rel(RSL_DCHAN_PT rsl_pt, RSLEM_PROC_PT rsl_proc_pt, template PDU_ML3_NW_MS exp_rr_rel_tmpl := tr_RRM_RR_RELEASE)
runs on MSC_ConnHdlr {
	interleave {
	[] rsl_pt.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, decmatch exp_rr_rel_tmpl)) {
			f_logp(BSCVTY, "Got RSL RR Release");
		}
	[] rsl_pt.receive(tr_RSL_DEACT_SACCH(g_chan_nr)) {
			f_logp(BSCVTY, "Got RSL Deact SACCH");
		}
	[] rsl_pt.receive(tr_RSL_RF_CHAN_REL(g_chan_nr)) {
			f_logp(BSCVTY, "Got RSL RF Chan Rel, sending Rel Ack");
			rsl_pt.send(ts_RSL_RF_CHAN_REL_ACK(g_chan_nr));
			f_rslem_unregister(0, g_chan_nr, PT := rsl_proc_pt);
			break;
		}
	}
}

private altstep as_mgcp_ack_all_dlcx() runs on MSC_ConnHdlr {
	var MgcpCommand mgcp_cmd;
	[] MGCP.receive(tr_DLCX(?)) -> value mgcp_cmd {
		MGCP.send(ts_DLCX_ACK2(mgcp_cmd.line.trans_id));
		repeat;
	}
}

private altstep as_rsl_ack_all_rel_req() runs on MSC_ConnHdlr {
	var RslLinkId main_dcch := valueof(ts_RslLinkID_DCCH(0));
	[] RSL.receive(tr_RSL_REL_REQ(g_chan_nr, ?)) {
		RSL.send(ts_RSL_REL_CONF(g_chan_nr, main_dcch));
		repeat;
	}
}

friend function f_perform_clear(RSL_DCHAN_PT rsl_pt := RSL, RSLEM_PROC_PT rsl_proc_pt := RSL_PROC,
                                template PDU_ML3_NW_MS exp_rr_rel_tmpl := tr_RRM_RR_RELEASE)
runs on MSC_ConnHdlr {
	var default ack_dlcx := activate(as_mgcp_ack_all_dlcx());
	var default ack_rel_req := activate(as_rsl_ack_all_rel_req());
	f_logp(BSCVTY, "MSC instructs BSC to clear channel");
	BSSAP.send(ts_BSSMAP_ClearCommand(0));
	interleave {
	[] rsl_pt.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, decmatch exp_rr_rel_tmpl)) {
			f_logp(BSCVTY, "Got RSL RR Release");
		}
	[] rsl_pt.receive(tr_RSL_DEACT_SACCH(g_chan_nr)) {
			f_logp(BSCVTY, "Got RSL Deact SACCH");
		}
	[] BSSAP.receive(tr_BSSMAP_ClearComplete) {
			f_logp(BSCVTY, "Got BSSMAP Clear Complete");
			/* Also drop the SCCP connection */
			BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);
		}
	[] rsl_pt.receive(tr_RSL_RF_CHAN_REL(g_chan_nr)) {
			f_logp(BSCVTY, "Got RSL RF Chan Rel, sending Rel Ack");
			rsl_pt.send(ts_RSL_RF_CHAN_REL_ACK(g_chan_nr));
			f_rslem_unregister(0, g_chan_nr, PT := rsl_proc_pt);
		}
	}
	deactivate(ack_dlcx);
	deactivate(ack_rel_req);
}

friend function f_perform_clear_no_rr_rel(RSL_DCHAN_PT rsl_pt := RSL, RSLEM_PROC_PT rsl_proc_pt := RSL_PROC)
runs on MSC_ConnHdlr {
	var default ack_dlcx := activate(as_mgcp_ack_all_dlcx());
	var default ack_rel_req := activate(as_rsl_ack_all_rel_req());
	f_logp(BSCVTY, "MSC instructs BSC to clear channel");
	BSSAP.send(ts_BSSMAP_ClearCommand(0));
	interleave {
	[] rsl_pt.receive(tr_RSL_DEACT_SACCH(g_chan_nr)) {
			f_logp(BSCVTY, "Got RSL Deact SACCH");
		}
	[] BSSAP.receive(tr_BSSMAP_ClearComplete) {
			f_logp(BSCVTY, "Got BSSMAP Clear Complete");
			/* Also drop the SCCP connection */
			BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);
		}
	[] rsl_pt.receive(tr_RSL_RF_CHAN_REL(g_chan_nr)) {
			f_logp(BSCVTY, "Got RSL RF Chan Rel, sending Rel Ack");
			rsl_pt.send(ts_RSL_RF_CHAN_REL_ACK(g_chan_nr));
			f_rslem_unregister(0, g_chan_nr, PT := rsl_proc_pt);
		}
	}
	deactivate(ack_dlcx);
	deactivate(ack_rel_req);
}

friend function f_perform_clear_no_lchan()
runs on MSC_ConnHdlr {
	f_logp(BSCVTY, "MSC instructs BSC to clear channel");
	BSSAP.send(ts_BSSMAP_ClearCommand(0));
	BSSAP.receive(tr_BSSMAP_ClearComplete);
	f_logp(BSCVTY, "Got BSSMAP Clear Complete");
	/* Also drop the SCCP connection */
	BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);
}

friend function f_perform_clear_test_ct(DchanTuple dt)
	runs on test_CT
{
	/* Instruct BSC to clear channel */
	var BssmapCause cause := 0;
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(cause)));
	f_exp_chan_rel_and_clear(dt);
}

private function f_perform_compl_l3(RSL_DCHAN_PT rsl_pt, RSLEM_PROC_PT rsl_proc_pt,
                                    template PDU_ML3_MS_NW l3_info, boolean do_clear := true, boolean expect_bssmap_l3 := true)
runs on MSC_ConnHdlr {
	timer T := 10.0;
	var octetstring l3_enc := enc_PDU_ML3_MS_NW(valueof(l3_info));

	f_logp(BSCVTY, "establish channel, send Complete Layer 3 Info");
	f_create_bssmap_exp(l3_enc);

	/* RSL_Emulation.f_chan_est() on rsl_pt:
	 * This is basically code dup with s/RSL/rsl_pt from:
	 * RSL_Emulation.f_chan_est(g_pars.ra, l3_enc, g_pars.link_id, g_pars.fn);
	 */
	var RSL_Message rx_rsl;
	var GsmRrMessage rr;

	/* request a channel to be established */
	rsl_pt.send(ts_RSLDC_ChanRqd(g_pars.ra, g_pars.fn));
	/* expect immediate assignment.
	 * Code dup with s/RSL/rsl_pt from:
	 * rx_rsl := f_rx_or_fail(tr_RSL_IMM_ASSIGN);
	 */
	timer Tt := 10.0;

	/* request a channel to be established */
	Tt.start;
	alt {
		[] rsl_pt.receive(tr_RSL_IMM_ASSIGN) -> value rx_rsl {
			Tt.stop;
		}
		[] rsl_pt.receive {
			setverdict(fail, "Unexpected RSL message on DCHAN");
			mtc.stop;
		}
		[] Tt.timeout {
			setverdict(fail, "Timeout waiting for RSL on DCHAN");
			mtc.stop;
		}
	}
	rr := dec_GsmRrMessage(rx_rsl.ies[1].body.full_imm_ass_info.payload);
	g_chan_nr := rr.payload.imm_ass.chan_desc.chan_nr;
	rsl_pt.send(ts_RSL_EST_IND(g_chan_nr, valueof(g_pars.link_id), l3_enc));


	if (expect_bssmap_l3) {
		f_logp(BSCVTY, "expect BSSAP Complete Layer 3 Info at MSC");
		var template PDU_BSSAP exp_l3_compl;
		exp_l3_compl := tr_BSSMAP_ComplL3()
		if (g_pars.aoip == false) {
			exp_l3_compl.pdu.bssmap.completeLayer3Information.codecList := omit;
		} else {
			exp_l3_compl.pdu.bssmap.completeLayer3Information.codecList := ?;
		}

		var PDU_BSSAP bssap;
		T.start;
		alt {
		[] BSSAP.receive(exp_l3_compl) -> value bssap {
			f_logp(BSCVTY, "received expected Complete Layer 3 Info at MSC");
			log("rx exp_l3_compl = ", bssap);
			}
		[] BSSAP.receive(tr_BSSMAP_ComplL3) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Received non-matching COMPLETE LAYER 3 INFORMATION");
			}
		[] T.timeout {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for COMPLETE LAYER 3 INFORMATION");
			}
		}

		/* start ciphering, if requested */
		if (ispresent(g_pars.encr)) {
			f_logp(BSCVTY, "start ciphering");
			f_cipher_mode(g_pars.encr, rsl_pt := rsl_pt, rsl_proc_pt := rsl_proc_pt);
		}
	}

	if (do_clear) {
		f_perform_clear(rsl_pt, rsl_proc_pt);
	}
	setverdict(pass);
	f_sleep(1.0);
}

private function f_tc_mscpool_compl_l3(charstring id) runs on MSC_ConnHdlr {
	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);
	if (g_pars.mscpool.rsl_idx == 0) {
		f_perform_compl_l3(RSL, RSL_PROC, g_pars.mscpool.l3_info);
	} else if (g_pars.mscpool.rsl_idx == 1) {
		f_perform_compl_l3(RSL1, RSL1_PROC, g_pars.mscpool.l3_info);
	} else if (g_pars.mscpool.rsl_idx == 2) {
		f_perform_compl_l3(RSL2, RSL2_PROC, g_pars.mscpool.l3_info);
	}
}

/* Various Complete Layer 3 by IMSI all end up with the first MSC, because the other MSCs are not connected. */
private function f_tc_mscpool_L3Compl_on_1_msc(charstring id) runs on MSC_ConnHdlr {
	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);
	f_perform_compl_l3(RSL, RSL_PROC, ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_IMSI_LV('001010000000001'H)), '00F110'O) );
	f_perform_compl_l3(RSL, RSL_PROC, ts_CM_SERV_REQ(CM_TYPE_MO_SMS, valueof(ts_MI_IMSI_LV('001010000000002'H))) );
	f_perform_compl_l3(RSL, RSL_PROC, ts_PAG_RESP(valueof(ts_MI_IMSI_LV('001010000000003'H))) );
	f_perform_compl_l3(RSL, RSL_PROC, ts_ML3_MO_MM_IMSI_DET_Ind(valueof(ts_MI_IMSI_LV('001010000000004'H))) );
}
testcase TC_mscpool_L3Compl_on_1_msc() runs on test_CT {

	f_init(1, true);
	f_sleep(1.0);
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_ctrs_msc_init();

	vc_conn := f_start_handler(refers(f_tc_mscpool_L3Compl_on_1_msc), pars);
	vc_conn.done;

	f_ctrs_msc_expect(0, "mscpool:subscr:new", 4);
	f_shutdown_helper();
}

/* Three Layer 3 Complete by IMSI are round-robin'ed across two connected MSCs */
/* FIXME: each run is using a separate RSLem: RSL, RSL1, RSL2. It should work
 * just as well using only RSL. */
testcase TC_mscpool_L3Complete_by_imsi_round_robin() runs on test_CT {

	f_init(nr_bts := 3, handler_mode := true, nr_msc := 2);
	f_sleep(1.0);

	/* Control which MSC gets chosen next by the round-robin, otherwise
	 * would be randomly affected by which other tests ran before this. */
	f_vty_transceive(BSCVTY, "mscpool roundrobin next 0");

	f_ctrs_msc_init();

	var MSC_ConnHdlr vc_conn1;
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars1.mscpool.rsl_idx := 0;
	pars1.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_IMSI_LV('001010000000001'H)), '00F110'O));
	vc_conn1 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars1);
	vc_conn1.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:new");

	var MSC_ConnHdlr vc_conn2;
	var TestHdlrParams pars2 := f_gen_test_hdlr_pars(bssap_idx := 1);
	pars2.mscpool.rsl_idx := 1;
	pars2.mscpool.l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_MO_CALL, valueof(ts_MI_IMSI_LV('001010000000002'H))));
	vc_conn2 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars2);
	vc_conn2.done;
	f_ctrs_msc_expect(1, "mscpool:subscr:new");

	/* Test round-robin wrap to the first MSC */
	var MSC_ConnHdlr vc_conn3;
	var TestHdlrParams pars3 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars3.mscpool.rsl_idx := 2;
	pars3.mscpool.l3_info := valueof(ts_PAG_RESP(valueof(ts_MI_IMSI_LV('001010000000003'H))));
	vc_conn3 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars3);
	vc_conn3.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:new");
	f_shutdown_helper();
}

/* Three LU by TMSI are round-robin'ed across two connected MSCs, because they contain the NULL-NRI 0
 * (configured in osmo-bsc.cfg). */
/* FIXME: each run is using a separate RSLem: RSL, RSL1, RSL2. It should work
 * just as well using only RSL. */
testcase TC_mscpool_LU_by_tmsi_null_nri_0_round_robin() runs on test_CT {

	f_init(nr_bts := 3, handler_mode := true, nr_msc := 2);
	f_sleep(1.0);

	/* Control which MSC gets chosen next by the round-robin, otherwise
	 * would be randomly affected by which other tests ran before this. */
	f_vty_transceive(BSCVTY, "mscpool roundrobin next 0");

	f_ctrs_msc_init();

	var MSC_ConnHdlr vc_conn1;
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars1.mscpool.rsl_idx := 0;
	pars1.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_TMSI_NRI_LV(0)), '00F110'O));
	vc_conn1 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars1);
	vc_conn1.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:reattach");

	var MSC_ConnHdlr vc_conn2;
	var TestHdlrParams pars2 := f_gen_test_hdlr_pars(bssap_idx := 1);
	pars2.mscpool.rsl_idx := 1;
	pars2.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_TMSI_NRI_LV(0)), '00F110'O));
	vc_conn2 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars2);
	vc_conn2.done;
	f_ctrs_msc_expect(1, "mscpool:subscr:reattach");

	/* Test round-robin wrap to the first MSC */
	var MSC_ConnHdlr vc_conn3;
	var TestHdlrParams pars3 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars3.mscpool.rsl_idx := 2;
	pars3.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_TMSI_NRI_LV(0)), '00F110'O));
	vc_conn3 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars3);
	vc_conn3.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:reattach");
	f_shutdown_helper();
}

/* Three LU by TMSI are round-robin'ed across two connected MSCs, because they contain the NULL-NRI 1
 * (configured in osmo-bsc.cfg). In this case, one of the MSC also has the NULL-NRI as part of its owned NRIs, but the
 * NULL-NRI setting is stronger than that. */
/* FIXME: each run is using a separate RSLem: RSL, RSL1, RSL2. It should work
 * just as well using only RSL. */
testcase TC_mscpool_LU_by_tmsi_null_nri_1_round_robin() runs on test_CT {

	f_init(nr_bts := 3, handler_mode := true, nr_msc := 2);
	f_sleep(1.0);

	/* Control which MSC gets chosen next by the round-robin, otherwise
	 * would be randomly affected by which other tests ran before this. */
	f_vty_transceive(BSCVTY, "mscpool roundrobin next 0");

	f_ctrs_msc_init();

	var MSC_ConnHdlr vc_conn1;
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars1.mscpool.rsl_idx := 0;
	pars1.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_TMSI_NRI_LV(1)), '00F110'O));
	vc_conn1 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars1);
	vc_conn1.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:reattach");

	var MSC_ConnHdlr vc_conn2;
	var TestHdlrParams pars2 := f_gen_test_hdlr_pars(bssap_idx := 1);
	pars2.mscpool.rsl_idx := 1;
	pars2.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_TMSI_NRI_LV(1)), '00F110'O));
	vc_conn2 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars2);
	vc_conn2.done;
	f_ctrs_msc_expect(1, "mscpool:subscr:reattach");

	/* Test round-robin wrap to the first MSC */
	var MSC_ConnHdlr vc_conn3;
	var TestHdlrParams pars3 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars3.mscpool.rsl_idx := 2;
	pars3.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_TMSI_NRI_LV(1)), '00F110'O));
	vc_conn3 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars3);
	vc_conn3.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:reattach");
	f_shutdown_helper();
}

/* Three Layer 3 Complete by TMSI are round-robin'ed across two connected MSCs, because they contain an NRI not
 * assigned to any MSC (configured in osmo-bsc.cfg). */
/* FIXME: each run is using a separate RSLem: RSL, RSL1, RSL2. It should work
 * just as well using only RSL. */
testcase TC_mscpool_L3Complete_by_tmsi_unassigned_nri_round_robin() runs on test_CT {

	f_init(nr_bts := 3, handler_mode := true, nr_msc := 2);
	f_sleep(1.0);

	/* Control which MSC gets chosen next by the round-robin, otherwise
	 * would be randomly affected by which other tests ran before this. */
	f_vty_transceive(BSCVTY, "mscpool roundrobin next 0");

	f_ctrs_msc_init();

	var MSC_ConnHdlr vc_conn1;
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars1.mscpool.rsl_idx := 0;
	/* An NRI that is not assigned to any MSC */
	pars1.mscpool.l3_info := valueof(ts_ML3_MO_MM_IMSI_DET_Ind(valueof(ts_MI_TMSI_NRI_LV(1023))));
	vc_conn1 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars1);
	vc_conn1.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:new");

	var MSC_ConnHdlr vc_conn2;
	var TestHdlrParams pars2 := f_gen_test_hdlr_pars(bssap_idx := 1);
	pars2.mscpool.rsl_idx := 1;
	/* An NRI that is not assigned to any MSC */
	pars2.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_TMSI_NRI_LV(768)), '00F110'O));
	vc_conn2 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars2);
	vc_conn2.done;
	f_ctrs_msc_expect(1, "mscpool:subscr:new");

	/* Test round-robin wrap to the first MSC */
	var MSC_ConnHdlr vc_conn3;
	var TestHdlrParams pars3 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars3.mscpool.rsl_idx := 2;
	/* An NRI that is not assigned to any MSC */
	pars3.mscpool.l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_SS_ACT, valueof(ts_MI_TMSI_NRI_LV(819))));
	vc_conn3 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars3);
	vc_conn3.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:new");
	f_shutdown_helper();
}

/* Three Layer 3 Complete by TMSI are round-robin'ed across two connected MSCs, because they contain an NRI
 * assigned to an MSC that is currently not connected (configured in osmo-bsc.cfg). */
/* FIXME: each run is using a separate RSLem: RSL, RSL1, RSL2. It should work
 * just as well using only RSL. */
testcase TC_mscpool_L3Complete_by_tmsi_valid_nri_msc_not_connected_round_robin() runs on test_CT {

	f_init(nr_bts := 3, handler_mode := true, nr_msc := 2);
	f_sleep(1.0);

	/* Control which MSC gets chosen next by the round-robin, otherwise
	 * would be randomly affected by which other tests ran before this. */
	f_vty_transceive(BSCVTY, "mscpool roundrobin next 0");

	f_ctrs_msc_init();

	var MSC_ConnHdlr vc_conn1;
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars1.mscpool.rsl_idx := 0;
	/* An NRI that is assigned to an unconnected MSC */
	pars1.mscpool.l3_info := valueof(ts_PAG_RESP(valueof(ts_MI_TMSI_NRI_LV(512))));
	vc_conn1 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars1);
	vc_conn1.done;
	f_ctrs_msc_add(2, "mscpool:subscr:attach_lost");
	f_ctrs_msc_add(0, "mscpool:subscr:new");
	f_ctrs_msc_verify();

	var MSC_ConnHdlr vc_conn2;
	var TestHdlrParams pars2 := f_gen_test_hdlr_pars(bssap_idx := 1);
	pars2.mscpool.rsl_idx := 1;
	/* An NRI that is assigned to an unconnected MSC */
	pars2.mscpool.l3_info := valueof(ts_ML3_MO_MM_IMSI_DET_Ind(valueof(ts_MI_TMSI_NRI_LV(767))));
	vc_conn2 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars2);
	vc_conn2.done;
	f_ctrs_msc_add(2, "mscpool:subscr:attach_lost");
	f_ctrs_msc_add(1, "mscpool:subscr:new");
	f_ctrs_msc_verify();

	/* Test round-robin wrap to the first MSC */
	var MSC_ConnHdlr vc_conn3;
	var TestHdlrParams pars3 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars3.mscpool.rsl_idx := 2;
	/* An NRI that is assigned to an unconnected MSC */
	pars3.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_TMSI_NRI_LV(750)), '00F110'O));
	vc_conn3 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars3);
	vc_conn3.done;
	f_ctrs_msc_add(2, "mscpool:subscr:attach_lost");
	f_ctrs_msc_add(0, "mscpool:subscr:new");
	f_ctrs_msc_verify();
	f_shutdown_helper();
}

/* Three Layer 3 Complete by TMSI with valid NRI for the second MSC are all directed to the second MSC (configured in
 * osmo-bsc.cfg). */
/* FIXME: each run is using a separate RSLem: RSL, RSL1, RSL2. It should work
 * just as well using only RSL. */
testcase TC_mscpool_L3Complete_by_tmsi_valid_nri_1() runs on test_CT {

	f_init(nr_bts := 3, handler_mode := true, nr_msc := 2);
	f_sleep(1.0);

	/* All TMSIs in this test point at the second MSC, set the round robin to point at the first MSC to make sure
	 * this is not using round-robin. */
	f_vty_transceive(BSCVTY, "mscpool roundrobin next 0");

	f_ctrs_msc_init();

	var MSC_ConnHdlr vc_conn1;
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars(bssap_idx := 1);
	pars1.mscpool.rsl_idx := 0;
	/* An NRI of the second MSC's range (256-511) */
	pars1.mscpool.l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_MO_SMS, valueof(ts_MI_TMSI_NRI_LV(256))));
	vc_conn1 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars1);
	vc_conn1.done;
	f_ctrs_msc_expect(1, "mscpool:subscr:known");

	var MSC_ConnHdlr vc_conn2;
	var TestHdlrParams pars2 := f_gen_test_hdlr_pars(bssap_idx := 1);
	pars2.mscpool.rsl_idx := 1;
	/* An NRI of the second MSC's range (256-511) */
	pars2.mscpool.l3_info := valueof(ts_PAG_RESP(valueof(ts_MI_TMSI_NRI_LV(260))));
	vc_conn2 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars2);
	vc_conn2.done;
	f_ctrs_msc_expect(1, "mscpool:subscr:known");

	var MSC_ConnHdlr vc_conn3;
	var TestHdlrParams pars3 := f_gen_test_hdlr_pars(bssap_idx := 1);
	pars3.mscpool.rsl_idx := 2;
	/* An NRI of the second MSC's range (256-511) */
	pars3.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_TMSI_NRI_LV(511)), '00F110'O));
	vc_conn3 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars3);
	vc_conn3.done;
	f_ctrs_msc_expect(1, "mscpool:subscr:known");
	f_shutdown_helper();
}

/* Layer 3 Complete by TMSI with valid NRI for the third MSC are directed to the third MSC (configured in osmo-bsc.cfg),
 * while a round-robin remains unaffected by that. */
/* FIXME: each run is using a separate RSLem: RSL, RSL1, RSL2. It should work
 * just as well using only RSL. */
testcase TC_mscpool_L3Complete_by_tmsi_valid_nri_2() runs on test_CT {

	f_init(nr_bts := 3, handler_mode := true, nr_msc := 3);
	f_sleep(1.0);

	/* All TMSIs in this test point at the third MSC, set the round robin to point at the second MSC to make sure
	 * this is not using round-robin. */
	f_vty_transceive(BSCVTY, "mscpool roundrobin next 1");

	f_ctrs_msc_init();

	var MSC_ConnHdlr vc_conn1;
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars(bssap_idx := 2);
	pars1.mscpool.rsl_idx := 0;
	/* An NRI of the third MSC's range (512-767) */
	pars1.mscpool.l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_MO_SMS, valueof(ts_MI_TMSI_NRI_LV(512))));
	vc_conn1 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars1);
	vc_conn1.done;
	f_ctrs_msc_expect(2, "mscpool:subscr:known");

	var MSC_ConnHdlr vc_conn2;
	var TestHdlrParams pars2 := f_gen_test_hdlr_pars(bssap_idx := 2);
	pars2.mscpool.rsl_idx := 1;
	/* An NRI of the third MSC's range (512-767) */
	pars2.mscpool.l3_info := valueof(ts_PAG_RESP(valueof(ts_MI_TMSI_NRI_LV(678))));
	vc_conn2 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars2);
	vc_conn2.done;
	f_ctrs_msc_expect(2, "mscpool:subscr:known");

	/* The above forwardings to third MSC have not affected the round robin, which still points at the second MSC */
	var MSC_ConnHdlr vc_conn3;
	var TestHdlrParams pars3 := f_gen_test_hdlr_pars(bssap_idx := 1);
	pars3.mscpool.rsl_idx := 2;
	pars3.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_IMSI_LV('001010000000013'H)), '00F110'O));
	vc_conn3 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars3);
	vc_conn3.done;
	f_ctrs_msc_expect(1, "mscpool:subscr:new");
	f_shutdown_helper();
}

/* LU with a TMSI but indicating a different PLMN in its previous LAI: ignore the NRI. */
/* FIXME: each run is using a separate RSLem: RSL, RSL1, RSL2. It should work
 * just as well using only RSL. */
testcase TC_mscpool_LU_by_tmsi_from_other_PLMN() runs on test_CT {

	f_init(nr_bts := 3, handler_mode := true, nr_msc := 3);
	f_sleep(1.0);

	/* The TMSIs in this test points at the second MSC, but since it is from a different PLMN, round-robin is used
	 * instead, and hits msc 0. */
	f_vty_transceive(BSCVTY, "mscpool roundrobin next 0");

	f_ctrs_msc_init();

	/* An NRI of the second MSC's range (256-511), but a PLMN that doesn't match with osmo-bsc.cfg */
	var MSC_ConnHdlr vc_conn1;
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars1.mscpool.rsl_idx := 0;
	pars1.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_TMSI_NRI_LV(260)), '99F999'O));
	vc_conn1 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars1);
	vc_conn1.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:new");

	/* An NRI of the third MSC's range (512-767) and a matching PLMN gets directed by NRI. */
	var MSC_ConnHdlr vc_conn2;
	var TestHdlrParams pars2 := f_gen_test_hdlr_pars(bssap_idx := 2);
	pars2.mscpool.rsl_idx := 1;
	pars2.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_TMSI_NRI_LV(555)), '00F110'O));
	vc_conn2 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars2);
	vc_conn2.done;
	f_ctrs_msc_expect(2, "mscpool:subscr:known");
	f_shutdown_helper();
}

/* Make sure that whichever MSC paged a subscriber will also get the Paging Response. Page by IMSI, which would be
 * round-robined to another MSC, to make sure the Paging->Response relation is stronger than the NRI->MSC mapping. */
private function f_tc_mscpool_paging_imsi(charstring id) runs on MSC_ConnHdlr {
	var template BSSMAP_FIELD_CellIdentificationList cid_list := { cIl_CI := { ts_BSSMAP_CI_CI(0) } };
	//cid_list := { cIl_allInBSS := ''O };
	var RSL_ChanNeeded rsl_chneed := RSL_CHANNEED_SDCCH;
	var template BSSMAP_IE_ChannelNeeded bssmap_chneed := ts_BSSMAP_IE_ChanNeeded(int2bit(enum2int(valueof(rsl_chneed)),2));
	var BSSAP_N_UNITDATA_req paging;
	var hexstring imsi := '001010000000123'H;

	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);

	paging := valueof(ts_BSSAP_UNITDATA_req(g_pars.sccp_addr_bsc, g_pars.sccp_addr_msc,
						valueof(ts_BSSMAP_Paging(imsi, cid_list, omit, bssmap_chneed))));
	BSSAP.send(paging);

	/* Register any RSL conn so that the Paging Command gets received here. With the current RSL_Emulation's main()
	 * handling of '[bts_role] IPA_PT.receive(tr_ASP_RSL_UD(tr_RSL_PAGING_CMD()))' it doesn't matter at all which
	 * channel number is picked here. */
	var RslChannelNr new_chan_nr := valueof(t_RslChanNr0(0, RSL_CHAN_NR_INVALID));
	f_rslem_register(0, new_chan_nr);
	RSL.receive(tr_RSL_PAGING_CMD(tr_MI_IMSI(imsi)));
	f_rslem_unregister(0, new_chan_nr);

	/* Despite the round robin pointing at the second MSC ('roundrobin next 1'), the earlier Paging for the same IMSI
	 * causes this Paging Response to go to the first MSC (bssap_idx := 0). */
	f_perform_compl_l3(RSL, RSL_PROC, ts_PAG_RESP(valueof(ts_MI_IMSI_LV(imsi))) );
	f_sleep(1.0);
}
testcase TC_mscpool_paging_and_response_imsi() runs on test_CT {
	f_init(nr_bts := 1, handler_mode := true, nr_msc := 3);
	f_sleep(1.0);

	/* Testing a Paging on the first MSC to get a Paging Response back to the first MSC. Set round robin to the
	 * second MSC to make sure we're getting the Paging logic, not a coincidental round robin match. */
	f_vty_transceive(BSCVTY, "mscpool roundrobin next 1");

	f_ctrs_msc_init();

	var MSC_ConnHdlr vc_conn1;
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars1.mscpool.rsl_idx := 0;
	pars1.sccp_addr_bsc := g_bssap[pars1.mscpool.bssap_idx].sccp_addr_peer;
	pars1.sccp_addr_msc := g_bssap[pars1.mscpool.bssap_idx].sccp_addr_own;
	vc_conn1 := f_start_handler(refers(f_tc_mscpool_paging_imsi), pars1);
	vc_conn1.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:paged");
	f_shutdown_helper();
}

/* Make sure that whichever MSC paged a subscriber will also get the Paging Response.  Page by TMSI with an NRI value
 * that matches a different MSC, to make sure the Paging->Response relation is stronger than the NRI->MSC mapping. */
private function f_tc_mscpool_paging_tmsi(charstring id) runs on MSC_ConnHdlr {
	var template BSSMAP_FIELD_CellIdentificationList cid_list := { cIl_CI := { ts_BSSMAP_CI_CI(0) } };
	//cid_list := { cIl_allInBSS := ''O };
	var RSL_ChanNeeded rsl_chneed := RSL_CHANNEED_SDCCH;
	var template BSSMAP_IE_ChannelNeeded bssmap_chneed := ts_BSSMAP_IE_ChanNeeded(int2bit(enum2int(valueof(rsl_chneed)),2));
	var integer nri_v := 300; /* <-- second MSC's NRI */
	var octetstring tmsi := f_gen_tmsi(suffix := 0, nri_v := nri_v);
	var BSSAP_N_UNITDATA_req paging;

	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);

	paging := valueof(ts_BSSAP_UNITDATA_req(g_pars.sccp_addr_bsc, g_pars.sccp_addr_msc,
						valueof(ts_BSSMAP_Paging('001010000000011'H, cid_list, tmsi, bssmap_chneed))));
	BSSAP.send(paging);

	/* Register any RSL conn so that the Paging Command gets received here. With the current RSL_Emulation's main()
	 * handling of '[bts_role] IPA_PT.receive(tr_ASP_RSL_UD(tr_RSL_PAGING_CMD()))' it doesn't matter at all which
	 * channel number is picked here. */
	var RslChannelNr new_chan_nr := valueof(t_RslChanNr0(0, RSL_CHAN_NR_INVALID));
	f_rslem_register(0, new_chan_nr);
	RSL.receive(tr_RSL_PAGING_CMD(t_MI_TMSI(tmsi)));
	f_rslem_unregister(0, new_chan_nr);

	/* Despite the NRI matching the second MSC (NRI from 'msc 1' in osmo-bsc.cfg) and round robin pointing at the
	 * third MSC ('roundrobin next 2'), the earlier Paging for the same TMSI causes this Paging Response to go to
	 * the first MSC (bssap_idx := 0). */
	f_perform_compl_l3(RSL, RSL_PROC, ts_PAG_RESP(valueof(ts_MI_TMSI_NRI_LV(nri_v))) );
	f_sleep(1.0);
}
testcase TC_mscpool_paging_and_response_tmsi() runs on test_CT {
	f_init(nr_bts := 1, handler_mode := true, nr_msc := 3);
	f_sleep(1.0);

	/* Testing a Paging on the first MSC to get a Paging Response back to the first MSC. Set round robin to the
	 * third MSC to make sure we're getting the Paging logic, not a coincidental round robin match. */
	f_vty_transceive(BSCVTY, "mscpool roundrobin next 2");

	f_ctrs_msc_init();

	var MSC_ConnHdlr vc_conn1;
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars1.mscpool.rsl_idx := 0;
	pars1.sccp_addr_bsc := g_bssap[pars1.mscpool.bssap_idx].sccp_addr_peer;
	pars1.sccp_addr_msc := g_bssap[pars1.mscpool.bssap_idx].sccp_addr_own;
	vc_conn1 := f_start_handler(refers(f_tc_mscpool_paging_tmsi), pars1);
	vc_conn1.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:paged");
	f_shutdown_helper();
}

/* For round-robin, skip an MSC that has 'no allow-attach' set. */
/* FIXME: each run is using a separate RSLem: RSL, RSL1, RSL2. It should work
 * just as well using only RSL. */
testcase TC_mscpool_no_allow_attach_round_robin() runs on test_CT {

	f_init(nr_bts := 3, handler_mode := true, nr_msc := 3);
	f_sleep(1.0);
	/* Mark the second MSC as offloading, round-robin should skip this MSC now. */
	f_vty_msc_allow_attach(BSCVTY, {true, false, true});

	/* Control which MSC gets chosen next by the round-robin, otherwise
	 * would be randomly affected by which other tests ran before this. */
	f_vty_transceive(BSCVTY, "mscpool roundrobin next 0");

	f_ctrs_msc_init();

	var MSC_ConnHdlr vc_conn1;
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars1.mscpool.rsl_idx := 0;
	pars1.mscpool.l3_info := valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_IMSI_LV('001010000000001'H)), '00F110'O));
	vc_conn1 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars1);
	vc_conn1.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:new");

	var MSC_ConnHdlr vc_conn2;
	var TestHdlrParams pars2 := f_gen_test_hdlr_pars(bssap_idx := 2);
	pars2.mscpool.rsl_idx := 1;
	pars2.mscpool.l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_MO_CALL, valueof(ts_MI_IMSI_LV('001010000000002'H))));
	vc_conn2 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars2);
	vc_conn2.done;
	f_ctrs_msc_expect(2, "mscpool:subscr:new");

	var MSC_ConnHdlr vc_conn3;
	var TestHdlrParams pars3 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars3.mscpool.rsl_idx := 2;
	pars3.mscpool.l3_info := valueof(ts_PAG_RESP(valueof(ts_MI_IMSI_LV('001010000000003'H))));
	vc_conn3 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars3);
	vc_conn3.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:new");
	f_shutdown_helper();
}

/* An MSC that has 'no allow-attach' set should still serve subscribers that are already attached according to their
 * TMSI NRI. */
testcase TC_mscpool_no_allow_attach_valid_nri() runs on test_CT {

	f_init(nr_bts := 3, handler_mode := true, nr_msc := 3);
	f_sleep(1.0);

	/* Mark the second MSC as offloading, round-robin should skip this MSC now. */
	f_vty_msc_allow_attach(BSCVTY, {true, false, true});

	/* Control which MSC gets chosen next by the round-robin, otherwise
	 * would be randomly affected by which other tests ran before this. */
	f_vty_transceive(BSCVTY, "mscpool roundrobin next 0");

	f_ctrs_msc_init();

	/* Round robin points at msc 0, but the valid NRI directs to msc 1, even though msc 1 has 'no allow-attach'. */
	var MSC_ConnHdlr vc_conn1;
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars(bssap_idx := 1);
	pars1.mscpool.rsl_idx := 0;
	/* An NRI of the second MSC's range (256-511) */
	pars1.mscpool.l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_MO_CALL, valueof(ts_MI_TMSI_NRI_LV(260))));
	vc_conn1 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars1);
	vc_conn1.done;
	f_ctrs_msc_expect(1, "mscpool:subscr:known");

	var MSC_ConnHdlr vc_conn2;
	var TestHdlrParams pars2 := f_gen_test_hdlr_pars(bssap_idx := 0);
	pars2.mscpool.rsl_idx := 1;
	pars2.mscpool.l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_MO_CALL, valueof(ts_MI_IMSI_LV('001010000000002'H))));
	vc_conn2 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars2);
	vc_conn2.done;
	f_ctrs_msc_expect(0, "mscpool:subscr:new");

	var MSC_ConnHdlr vc_conn3;
	var TestHdlrParams pars3 := f_gen_test_hdlr_pars(bssap_idx := 2);
	pars3.mscpool.rsl_idx := 2;
	pars3.mscpool.l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_MO_CALL, valueof(ts_MI_IMSI_LV('001010000000003'H))));
	vc_conn3 := f_start_handler(refers(f_tc_mscpool_compl_l3), pars3);
	vc_conn3.done;
	f_ctrs_msc_expect(2, "mscpool:subscr:new");
	f_shutdown_helper();
}

/* Allow/Deny emergency calls globally via VTY */
private function f_vty_allow_emerg_msc(boolean allow) runs on test_CT {
	f_vty_enter_cfg_msc(BSCVTY, 0);
	if (allow) {
		f_vty_transceive(BSCVTY, "allow-emergency allow");
	} else {
		f_vty_transceive(BSCVTY, "allow-emergency deny");
	}
	f_vty_transceive(BSCVTY, "exit");
	f_vty_transceive(BSCVTY, "exit");
}

/* Allow/Deny emergency calls per BTS via VTY */
private function f_vty_allow_emerg_bts(boolean allow, integer bts_nr) runs on test_CT {
	f_vty_enter_cfg_bts(BSCVTY, bts_nr);
	if (allow) {
		f_vty_transceive(BSCVTY, "rach emergency call allowed 1");
	} else {
		f_vty_transceive(BSCVTY, "rach emergency call allowed 0");
	}
	f_vty_transceive(BSCVTY, "exit");
	f_vty_transceive(BSCVTY, "exit");
	f_vty_transceive(BSCVTY, "exit");
}

/* Allow/Forbid Fast Return after SRVCC on a given BTS via VTY */
private function f_vty_allow_srvcc_fast_return(boolean allow, integer bts_nr) runs on test_CT {
	f_vty_enter_cfg_bts(BSCVTY, bts_nr);
	if (allow) {
		f_vty_transceive(BSCVTY, "srvcc fast-return allow");
	} else {
		f_vty_transceive(BSCVTY, "srvcc fast-return forbid");
	}
	f_vty_transceive(BSCVTY, "exit");
	f_vty_transceive(BSCVTY, "exit");
	f_vty_transceive(BSCVTY, "exit");
}

/* Allow/Forbid TCH for signalling if SDCCH exhausted on a given BTS via VTY */
private function f_vty_allow_tch_for_signalling(boolean allow, integer bts_nr) runs on test_CT {
	f_vty_enter_cfg_bts(BSCVTY, bts_nr);
	if (allow) {
		f_vty_transceive(BSCVTY, "channel allocator allow-tch-for-signalling 1");
	} else {
		f_vty_transceive(BSCVTY, "channel allocator allow-tch-for-signalling 0");
	}
	f_vty_transceive(BSCVTY, "exit");
	f_vty_transceive(BSCVTY, "exit");
	f_vty_transceive(BSCVTY, "exit");
}

/* Begin assignmet procedure and send an EMERGENCY SETUP (RR) */
private function f_assignment_emerg_setup() runs on MSC_ConnHdlr {
	var PDU_ML3_MS_NW emerg_setup;
	var octetstring emerg_setup_enc;
	var RSL_Message emerg_setup_data_ind;

	f_establish_fully(omit, omit);

	emerg_setup := valueof(ts_ML3_MO_CC_EMERG_SETUP(1, valueof(ts_Bcap_voice)));
	emerg_setup_enc := enc_PDU_ML3_MS_NW(emerg_setup);
	emerg_setup_data_ind := valueof(ts_RSL_DATA_IND(g_chan_nr, valueof(ts_RslLinkID_DCCH(0)), emerg_setup_enc));

	RSL.send(emerg_setup_data_ind);
}

/* Test if the EMERGENCY SETUP gets passed on to the MSC via A when EMERGENCY
 * CALLS are permitted by the BSC config. */
private function f_TC_assignment_emerg_setup_allow(charstring id) runs on MSC_ConnHdlr {
	var PDU_BSSAP emerg_setup_data_ind_bssap;
	var PDU_ML3_MS_NW emerg_setup;
	timer T := 3.0;

	f_assignment_emerg_setup()

	T.start;
	alt {
	[] BSSAP.receive(tr_BSSAP_DTAP) -> value emerg_setup_data_ind_bssap {
		emerg_setup := dec_PDU_ML3_MS_NW(emerg_setup_data_ind_bssap.pdu.dtap);
		if (not isbound(emerg_setup.msgs.cc.emergencySetup)) {
			setverdict(fail, "no emergency setup");
		}
		}
	[] BSSAP.receive {
		setverdict(fail, "unexpected BSSAP message!");
		}
	[] T.timeout {
		setverdict(fail, "timout waiting for EMERGENCY SETUP!");
		}
	}

	setverdict(pass);
	f_perform_clear();
}

/* Test if the EMERGENCY SETUP gets blocked by the BSC if EMERGENCY CALLS are
 * forbidden by the BSC config. */
private function f_TC_assignment_emerg_setup_deny(charstring id) runs on MSC_ConnHdlr {
	var PDU_BSSAP emerg_setup_data_ind_bssap;
	timer T := 3.0;

	f_assignment_emerg_setup()

	T.start;
	alt {
	[] RSL.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, decmatch tr_RRM_RR_RELEASE)) {
		setverdict(pass);
		}
	[] RSL.receive {
		setverdict(fail, "unexpected RSL message!");
		}
	[] T.timeout {
		setverdict(fail, "timout waiting for RR CHANNEL RELEASE!");
		}
	}
	BSSAP.receive(tr_BSSMAP_ClearRequest);
	f_perform_clear_no_rr_rel();
}

/* EMERGENCY CALL situation #1, allowed globally and by BTS */
testcase TC_assignment_emerg_setup_allow() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	f_vty_allow_emerg_msc(true);
	f_vty_allow_emerg_bts(true, 0);
	vc_conn := f_start_handler(refers(f_TC_assignment_emerg_setup_allow), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* EMERGENCY CALL situation #2, forbidden globally but allowed by BTS */
testcase TC_assignment_emerg_setup_deny_msc() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	f_vty_allow_emerg_msc(false);
	f_vty_allow_emerg_bts(true, 0);
	vc_conn := f_start_handler(refers(f_TC_assignment_emerg_setup_deny), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* EMERGENCY CALL situation #3, allowed globally but forbidden by BTS */
testcase TC_assignment_emerg_setup_deny_bts() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	/* Note: This simulates a spec violation by the MS, correct MS
	 * implementations would not try to establish an emergency call because
	 * the system information tells in advance that emergency calls are
	 * not forbidden */

	f_init(1, true);
	f_sleep(1.0);

	f_vty_allow_emerg_msc(true);
	f_vty_allow_emerg_bts(false, 0);
	vc_conn := f_start_handler(refers(f_TC_assignment_emerg_setup_deny), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* Test what happens when an emergency call arrives while all TCH channels are
 * busy, the BSC is expected to terminate one call in favor of the incoming
 * emergency call */
testcase TC_emerg_premption() runs on test_CT {
	var ASP_RSL_Unitdata rsl_ud;
	var integer i;
	var integer chreq_total, chreq_nochan;
	var RSL_Message rx_rsl;

	f_init(1);
	f_sleep(1.0);

	f_vty_allow_emerg_msc(true);
	f_vty_allow_emerg_bts(true, 0);

	/* Fill up all channels on the BTS */
	chreq_total := f_ctrl_get_ratectr_abs(IPA_CTRL, "bts", 0, "chreq:total");
	chreq_nochan := f_ctrl_get_ratectr_abs(IPA_CTRL, "bts", 0, "chreq:no_channel");
	for (i := 0; i < NUM_TCHF_PER_BTS + NUM_TCHH_PER_BTS + NUM_SDCCH_PER_BTS; i := i+1) {
		f_chreq_act_ack('33'O, i);
	}
	IPA_RSL[0][0].clear;
	f_ctrl_get_exp_ratectr_abs(IPA_CTRL, "bts", 0, "chreq:total",
				   chreq_total + NUM_TCHF_PER_BTS + NUM_TCHH_PER_BTS + NUM_SDCCH_PER_BTS);

	/* Send EST IND for the first TCH, so we get to test the RR release cause */
	var RslChannelNr first_tch := valueof(t_RslChanNr_Bm(1));
	var octetstring l3 := '00010203040506'O;
	f_ipa_tx(ts_RSL_EST_IND(first_tch, valueof(ts_RslLinkID_DCCH(0)), l3));

	/* Accept BSSAP conn, so we get to test the Clear Request cause */
	var BSSAP_N_CONNECT_ind rx_c_ind;
	BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) -> value rx_c_ind;
	var integer sccp_conn_id := rx_c_ind.connectionId;
	BSSAP.send(ts_BSSAP_CONNECT_res(rx_c_ind.connectionId));

	/* Send Channel request for emegergency call */
	f_ipa_tx(ts_RSL_CHAN_RQD('A5'O, 23));

	/* Expect the BSC to release one (the first) TCH/F on the BTS */
	f_expect_chan_rel(first_tch, expect_rr_chan_rel := true, expect_rll_rel_req := false,
			  expect_rr_cause := GSM48_RR_CAUSE_PREMPTIVE_REL);

	/* Also expect a BSSMAP Clear Request with PREEMPTION */
	var BSSAP_N_DATA_ind rx_clear_req;
	const myBSSMAP_Cause preemption := GSM0808_CAUSE_PREEMPTION;
	BSSAP.receive(tr_BSSAP_DATA_ind(sccp_conn_id, tr_BSSMAP_ClearRequest)) -> value rx_clear_req;
	log("XXX ", rx_clear_req);
	if (rx_clear_req.userData.pdu.bssmap.clearRequest.cause.causeValue != int2bit(enum2int(preemption), 7)) {
		setverdict(fail, "BSSMAP Clear Request: expected cause PREEMPTION");
	}

	/* Expect the BSC to send activate/assign the channel for the emergency call */
	rx_rsl := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));
	if (first_tch != rx_rsl.ies[0].body.chan_nr) {
		setverdict(fail, "different TCH lchan activated than expected");
	}
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(first_tch, 33));
	rx_rsl := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0));

	/* complete the BSSMAP Clear to satisfy the conn leak check */
	BSSAP.send(ts_BSSAP_DATA_req(sccp_conn_id, ts_BSSMAP_ClearCommand(enum2int(preemption))));
	BSSAP.receive(tr_BSSAP_DATA_ind(sccp_conn_id, tr_BSSMAP_ClearComplete)) {
		BSSAP.send(ts_BSSAP_DISC_req(sccp_conn_id, 0));
	}

	f_shutdown_helper();
}

/* Hopping parameters per a timeslot */
private type record length(0..64) of GsmArfcn ArfcnList;
private type record FHParamsTs {
	boolean		enabled,
	uint6_t		hsn,
	uint6_t		maio,
	ArfcnList	ma
};

/* Hopping parameters per a transceiver */
private type record FHParamsTrx {
	GsmBandArfcn	arfcn,
	FHParamsTs	ts[8]
};

/* Randomly generate the hopping parameters for the given timeslot numbers */
private function f_TC_fh_params_gen(template integer tr_tn := (1, 3, 5))
runs on test_CT return FHParamsTrx {
	var FHParamsTrx fhp;

	/* Generate a random ARFCN in the range of 0 - 3. This ARFCN will
	 * fall in the GSM900 band. */
	fhp.arfcn.arfcn := f_rnd_int(3);
	fhp.arfcn.pcs := false;

	for (var integer tn := 0; tn < 8; tn := tn + 1) {
		if (not match(tn, tr_tn)) {
			fhp.ts[tn].enabled := false;
			fhp.ts[tn].ma := { };
			continue;
		}

		/* Random HSN / MAIO values: 0..63 */
		fhp.ts[tn].hsn := f_rnd_int(64);
		fhp.ts[tn].maio := f_rnd_int(64);
		fhp.ts[tn].ma := { };

		/* Random Mobile Allocation (hopping channels) */
		var integer ma_len := 2 + f_rnd_int(9); /* 2..10 channels */
		var integer step := 3 + f_rnd_int(4); /* 3..6 stepping */
		for (var integer i := 1; i <= ma_len; i := i + 1) {
			fhp.ts[tn].ma := fhp.ts[tn].ma & { i * step };
		}

		fhp.ts[tn].enabled := true;
	}

	log("f_TC_fh_params_gen(): ", fhp);
	return fhp;
}

/* Make sure that the given Channel Description IE matches the hopping configuration */
private function f_TC_fh_params_match_chan_desc(in FHParamsTrx fhp, in ChannelDescription cd)
{
	var template (present) ChannelDescription tr_cd;
	var template (present) MaioHsn tr_maio_hsn;
	var uint3_t tn := cd.chan_nr.tn;

	if (fhp.ts[tn].enabled) {
		tr_maio_hsn := tr_HsnMaio(fhp.ts[tn].hsn, fhp.ts[tn].maio);
		tr_cd := tr_ChanDescH1(cd.chan_nr, tr_maio_hsn);
	} else {
		tr_cd := tr_ChanDescH0(cd.chan_nr, fhp.arfcn.arfcn);
	}

	if (not match(cd, tr_cd)) {
		setverdict(fail, "Channel Description IE does not match: ",
			   cd, " vs expected ", tr_cd);
	}
}

/* Make sure that the given Mobile Allocation IE matches the hopping configuration */
private function f_TC_fh_params_match_ma(in FHParamsTrx fhp, uint3_t tn,
					 in MobileAllocationLV ma)
{
	var template MobileAllocationLV tr_ma := f_TC_fh_params_gen_tr_ma(fhp, tn, ma);

	if (not match(ma, tr_ma)) {
		setverdict(fail, "Mobile Allocation IE does not match (tn := ",
			   tn, "): ", ma, " vs expected: ", tr_ma);
	} else {
		setverdict(pass);
	}
}

private function f_TC_fh_params_gen_tr_ma(in FHParamsTrx fhp, uint3_t tn,
					  in MobileAllocationLV ma)
return template MobileAllocationLV {
	/* Mobile Allocation IE is expected to be empty if hopping is not enabled */
	if (not fhp.ts[tn].enabled) {
		return { len := 0, ma := ''B };
	}

	var bitstring full_mask := f_pad_bit(''B, 1024, '0'B);
	var bitstring slot_mask := f_pad_bit(''B, 1024, '0'B);
	var bitstring ma_mask := ''B;

	/* Compose the full bit-mask (all channels, up to 1024 entries) */
	for (var integer i := 0; i < lengthof(fhp.ts); i := i + 1) {
		for (var integer j := 0; j < lengthof(fhp.ts[i].ma); j := j + 1) {
			if (full_mask[fhp.ts[i].ma[j]] == '1'B)
				{ continue; }
			full_mask[fhp.ts[i].ma[j]] := '1'B;
		}
	}

	/* Take ARFCN of the TRX itself into account */
	full_mask[fhp.arfcn.arfcn] := '1'B;

	/* Compose a bit-mask for the given timeslot number */
	for (var integer i := 0; i < lengthof(fhp.ts[tn].ma); i := i + 1) {
		slot_mask[fhp.ts[tn].ma[i]] := '1'B;
	}

	/* Finally, compose the Mobile Allocation bit-mask */
	for (var integer i := 1; i < lengthof(full_mask); i := i + 1) {
		if (full_mask[i] != '1'B)
			{ continue; }

		/* FIXME: ma_mask := ma_mask & slot_mask[i]; // triggers a bug in TITAN */
		if (slot_mask[i] == '1'B) {
			ma_mask := ma_mask & '1'B;
		} else {
			ma_mask := ma_mask & '0'B;
		}
	}

	/* ARFCN 0 (if present) goes to the last position of the bit-mask */
	if (full_mask[0] == '1'B) {
		/* FIXME: ma_mask := ma_mask & slot_mask[0]; // triggers a bug in TITAN */
		if (slot_mask[0] == '1'B) {
			ma_mask := ma_mask & '1'B;
		} else {
			ma_mask := ma_mask & '0'B;
		}
	}

	/* Ensure that ma_mask is octet-aligned */
	var integer ma_mask_len := (lengthof(ma_mask) + 8 - 1) / 8;
	ma_mask := f_pad_bit(ma_mask, ma_mask_len * 8, '0'B);

	return { len := ma_mask_len, ma := ma_mask };
}

/* Configure the appropriate band for a given arfcn, exc */
private function f_TC_set_band_by_arfcn(integer bts_nr, GsmBandArfcn arfcn) runs on test_CT
{
	var charstring band;
	var GsmBandArfcn arfcn_ := valueof(ts_GsmBandArfcn(arfcn.arfcn, arfcn.pcs, false));

	select (arfcn_) {
	case (tr_GsmBandArfcn((259..293), false, ?)) { band := "GSM450"; }
	case (tr_GsmBandArfcn((306..340), false, ?)) { band := "GSM480"; }
	case (tr_GsmBandArfcn((438..511), false, ?)) { band := "GSM750"; }
	case (tr_GsmBandArfcn((128..251), false, ?)) { band := "GSM850"; }
	case (tr_GsmBandArfcn((0..124), false, ?)) { band := "GSM900"; }
	case (tr_GsmBandArfcn((955..1023), false, ?)) { band := "GSM900"; }
	case (tr_GsmBandArfcn((512..885), false, ?)) { band := "DCS1800"; }
	case (tr_GsmBandArfcn((512..810), true, ?)) { band := "PCS1900"; }
	case else { return; }
	}

	f_vty_enter_cfg_bts(BSCVTY, bts_nr);
	f_vty_transceive(BSCVTY, "band " & band);
	f_vty_transceive(BSCVTY, "end");
}

/* Configure the hopping parameters in accordance with the given record */
private function f_TC_fh_params_set(in FHParamsTrx fhp,
				    uint8_t bts_nr := 0,
				    uint8_t trx_nr := 0)
runs on test_CT {

	f_TC_set_band_by_arfcn(bts_nr, fhp.arfcn);

	/* Enter the configuration node for the given BTS/TRX numbers */
	f_vty_enter_cfg_trx(BSCVTY, bts_nr, trx_nr);

	f_vty_transceive(BSCVTY, "arfcn " & int2str(fhp.arfcn.arfcn));

	for (var integer tn := 0; tn < lengthof(fhp.ts); tn := tn + 1) {
		f_vty_transceive(BSCVTY, "timeslot " & int2str(tn));

		if (not fhp.ts[tn].enabled) {
			f_vty_transceive(BSCVTY, "hopping enabled 0");
			f_vty_transceive(BSCVTY, "exit"); /* go back */
			continue;
		}

		/* Configure HSN / MAIO values */
		f_vty_transceive(BSCVTY, "hopping sequence-number " & int2str(fhp.ts[tn].hsn));
		f_vty_transceive(BSCVTY, "hopping maio " & int2str(fhp.ts[tn].maio));

		/* Configure the Mobile Allocation (hopping channels) */
		for (var integer i := 0; i < lengthof(fhp.ts[tn].ma); i := i + 1) {
			f_vty_transceive(BSCVTY, "hopping arfcn add " & int2str(fhp.ts[tn].ma[i]));
		}

		f_vty_transceive(BSCVTY, "hopping enabled 1");
		f_vty_transceive(BSCVTY, "exit"); /* go back */
	}

	f_vty_transceive(BSCVTY, "end");
}

/* Disable frequency hopping on all timeslots */
private function f_TC_fh_params_unset(in FHParamsTrx fhp,
				      uint8_t bts_nr := 0,
				      uint8_t trx_nr := 0,
				      GsmBandArfcn arfcn := {pcs := false, arfcn := 871})
runs on test_CT {

	f_TC_set_band_by_arfcn(bts_nr, arfcn);

	/* Enter the configuration node for the given BTS/TRX numbers */
	f_vty_enter_cfg_trx(BSCVTY, bts_nr, trx_nr);

	f_vty_transceive(BSCVTY, "arfcn " & int2str(arfcn.arfcn));

	for (var integer tn := 0; tn < lengthof(fhp.ts); tn := tn + 1) {
		f_vty_transceive(BSCVTY, "timeslot " & int2str(tn));

		/* Delete all ARFCNs from the Mobile Allocation (if any) */
		for (var integer i := 0; i < lengthof(fhp.ts[tn].ma); i := i + 1) {
			f_vty_transceive(BSCVTY, "hopping arfcn del " & int2str(fhp.ts[tn].ma[i]));
		}

		f_vty_transceive(BSCVTY, "hopping enabled 0");
		f_vty_transceive(BSCVTY, "exit"); /* go back */
	}

	f_vty_transceive(BSCVTY, "end");
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");
}

/* Verify presence and correctness of the hopping parameters (HSN, MAIO)
 * in the Channel Identification IE of the RSL CHANnel ACTIVation message. */
testcase TC_fh_params_chan_activ() runs on test_CT {
	var FHParamsTrx fhp := f_TC_fh_params_gen();
	var RSL_Message rsl_msg;
	var RSL_IE_Body ie;

	f_init_vty();

	f_TC_fh_params_set(fhp); /* Enable frequency hopping */
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1);

	/* CS domain: 3 (SDCCH/4+CBCH) + 4 (TCH/F) + 2 (TCH/H) channels available */
	for (var integer i := 0; i < 9; i := i + 1) {
		f_ipa_tx(ts_RSL_CHAN_RQD(f_rnd_ra_cs(), 23));
		rsl_msg := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));

		/* Make sure that Channel Identification IE is present */
		if (not f_rsl_find_ie(rsl_msg, RSL_IE_CHAN_IDENT, ie)) {
			setverdict(fail, "RSL Channel Identification IE is absent");
			continue;
		}

		/* Make sure that hopping parameters (HSN/MAIO) match */
		f_TC_fh_params_match_chan_desc(fhp, ie.chan_ident.ch_desc.v);

		/* "Mobile Allocation shall be included but empty" - let's check this */
		if (ie.chan_ident.ma.v.len != 0) {
			setverdict(fail, "Mobile Allocation IE is not empty: ",
				   ie.chan_ident.ma, ", despite it shall be");
			continue;
		}
	}

	/* Disable frequency hopping */
	f_TC_fh_params_unset(fhp);

	f_shutdown_helper();
}

/* Verify the hopping parameters (HSN, MAIO, MA) in (RR) Immediate Assignment */
testcase TC_fh_params_imm_ass() runs on test_CT {
	var FHParamsTrx fhp := f_TC_fh_params_gen();
	var RSL_Message rsl_msg;
	var RSL_IE_Body ie;

	f_init_vty();

	f_TC_fh_params_set(fhp); /* Enable frequency hopping */
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1);

	/* CS domain: 3 (SDCCH/4+CBCH) + 4 (TCH/F) + 2 (TCH/H) channels available */
	for (var integer i := 0; i < 9; i := i + 1) {
		f_ipa_tx(ts_RSL_CHAN_RQD(f_rnd_ra_cs(), 23));
		rsl_msg := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));

		f_ipa_tx(ts_RSL_CHAN_ACT_ACK(rsl_msg.ies[0].body.chan_nr, 33));
		rsl_msg := f_exp_ipa_rx(tr_RSL_MsgTypeC(RSL_MT_IMMEDIATE_ASSIGN_CMD));

		/* Make sure that Full Immediate Assign Info IE is present */
		if (not f_rsl_find_ie(rsl_msg, RSL_IE_FULL_IMM_ASS_INFO, ie)) {
			setverdict(fail, "RSL Full Immediate Assign Info IE is absent");
			continue;
		}

		/* Decode the actual Immediate Assignment message */
		var GsmRrMessage rr_msg := dec_GsmRrMessage(ie.full_imm_ass_info.payload);
		if (not match(rr_msg.header, t_RrHeader(IMMEDIATE_ASSIGNMENT, ?))) {
			setverdict(fail, "Failed to match Immediate Assignment: ", rr_msg);
			continue;
		}

		/* Make sure that hopping parameters (HSN/MAIO) match */
		f_TC_fh_params_match_chan_desc(fhp, rr_msg.payload.imm_ass.chan_desc);

		/* Make sure that the Mobile Allocation IE matches */
		f_TC_fh_params_match_ma(fhp, rr_msg.payload.imm_ass.chan_desc.chan_nr.tn,
					rr_msg.payload.imm_ass.mobile_allocation);
	}

	/* Disable frequency hopping */
	f_TC_fh_params_unset(fhp);

	f_shutdown_helper();
}

/* Verify the hopping parameters (HSN, MAIO, MA) in (RR) Assignment Command */
testcase TC_fh_params_assignment_cmd() runs on test_CT {
	var FHParamsTrx fhp := f_TC_fh_params_gen();
	var RSL_Message rsl_msg;
	var RSL_IE_Body ie;

	f_init_vty();

	f_TC_fh_params_set(fhp); /* Enable frequency hopping */
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1);

	/* HACK: work around "Couldn't find Expect for CRCX" */
	vc_MGCP.stop;

	var template PDU_BSSAP ass_cmd := f_gen_ass_req();
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := ts_BSSMAP_IE_CodecList({ts_CodecFR});

	/* CS domain (TCH): 4 (TCH/F) + 2 (TCH/H) channels available
	 * NOTE: only 3 SDCCH/4 channels are available on CCCH+SDCCH4+CBCH */
	for (var integer i := 0; i < 3; i := i + 1) {
		/* Establish a dedicated channel, so we can trigger (late) TCH assignment */
		var DchanTuple dt := f_est_dchan(f_rnd_ra_cs(), 23, f_rnd_octstring(16));

		/* Send a BSSMAP Assignment Command, expect CHANnel ACTIVation */
		BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ass_cmd));
		rsl_msg := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));

		/* ACKnowledge CHANnel ACTIVation, expect RSL DATA REQuest */
		f_ipa_tx(ts_RSL_CHAN_ACT_ACK(rsl_msg.ies[0].body.chan_nr, 33));
		rsl_msg := f_exp_ipa_rx(tr_RSL_MsgTypeR(RSL_MT_DATA_REQ));

		/* Make sure that L3 Information IE is present */
		if (not f_rsl_find_ie(rsl_msg, RSL_IE_L3_INFO, ie)) {
			setverdict(fail, "RSL L3 Information IE is absent");
			continue;
		}

		/* Decode the L3 message and make sure it is (RR) Assignment Command */
		var GsmRrL3Message l3_msg := dec_GsmRrL3Message(ie.l3_info.payload);
		if (not match(l3_msg.header, t_RrL3Header(ASSIGNMENT_COMMAND))) {
			setverdict(fail, "Failed to match Assignment Command: ", l3_msg);
			continue;
		}

		/* Make sure that hopping parameters (HSN/MAIO) match */
		var ChannelDescription chan_desc := l3_msg.payload.ass_cmd.chan_desc;
		f_TC_fh_params_match_chan_desc(fhp, chan_desc);

		/* Make sure that Cell Channel Description IE is present if FH is enabled */
		if (chan_desc.h and not ispresent(l3_msg.payload.ass_cmd.cell_chan_desc)) {
			setverdict(fail, "FH enabled, but Cell Channel Description IE is absent");
			continue;
		}

		/* Make sure that the Mobile Allocation IE matches (if present) */
		var boolean ma_present := ispresent(l3_msg.payload.ass_cmd.mobile_allocation);
		if (chan_desc.h and ma_present) {
			f_TC_fh_params_match_ma(fhp, chan_desc.chan_nr.tn,
						l3_msg.payload.ass_cmd.mobile_allocation.v);
		} else if (chan_desc.h and not ma_present) {
			setverdict(fail, "FH enabled, but Mobile Allocation IE is absent");
			continue;
		} else if (not chan_desc.h and ma_present) {
			setverdict(fail, "FH disabled, but Mobile Allocation IE is present");
			continue;
		}

		f_perform_clear_test_ct(dt);
	}

	/* Give the IUT some time to release all channels */
	f_sleep(3.0);

	/* Disable frequency hopping */
	f_TC_fh_params_unset(fhp);

	f_shutdown_helper();
}

/* Verify the hopping parameters (HSN, MAIO, MA) in (RR) Handover Command */
private function f_TC_fh_params_handover_cmd(in FHParamsTrx fhp)
runs on test_CT {
	var RSL_Message rsl_msg;
	var RSL_IE_Body ie;
	var DchanTuple dt;

	/* Establish a dedicated channel, so we can trigger handover */
	dt := f_est_dchan(f_rnd_ra_cs(), 23, f_rnd_octstring(16));
	f_sleep(0.5);

	/* Trigger handover from BTS0 to BTS1 */
	f_bts_0_cfg(BSCVTY, { "neighbor bts 1" });
	f_vty_handover(BSCVTY, 0, 0, dt.rsl_chan_nr, 1);

	/* Expect RSL CHANnel ACTIVation on BTS1/TRX0/TS1 */
	rsl_msg := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV), idx := {1, 0});

	/* ACKnowledge channel activation and expect (RR) Handover Command */
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(rsl_msg.ies[0].body.chan_nr, 33), idx := {1, 0});
	rsl_msg := f_exp_ipa_rx(tr_RSL_MsgTypeR(RSL_MT_DATA_REQ));

	/* Make sure that L3 Information IE is present */
	if (not f_rsl_find_ie(rsl_msg, RSL_IE_L3_INFO, ie)) {
		setverdict(fail, "RSL L3 Information IE is absent");
		return;
	}

	/* Decode the L3 message and make sure it is (RR) Handover Command */
	var GsmRrL3Message l3_msg := dec_GsmRrL3Message(ie.l3_info.payload);
	if (not match(l3_msg.header, t_RrL3Header(HANDOVER_COMMAND))) {
		setverdict(fail, "Failed to match Handover Command: ", l3_msg);
		return;
	}

	/* Make sure that we've got SDCCH/8 on TS1 (expected to be hopping) */
	var ChannelDescription chan_desc := l3_msg.payload.ho_cmd.chan_desc;
	if (not match(chan_desc.chan_nr, t_RslChanNr_SDCCH8(1, ?))) {
		setverdict(fail, "Unexpected channel number: ", chan_desc.chan_nr);
		return;
	}

	/* Make sure that hopping parameters (HSN/MAIO) match */
	f_TC_fh_params_match_chan_desc(fhp, chan_desc);

	/* Make sure that Cell Channel Description IE is present */
	if (not ispresent(l3_msg.payload.ho_cmd.cell_chan_desc)) {
		setverdict(fail, "FH enabled, but Cell Channel Description IE is absent");
		return;
	}

	/* Make sure that the Mobile Allocation (after time) IE is present and matches */
	var boolean ma_present := ispresent(l3_msg.payload.ho_cmd.mobile_allocation);
	if (ma_present) {
		f_TC_fh_params_match_ma(fhp, chan_desc.chan_nr.tn,
					l3_msg.payload.ho_cmd.mobile_allocation.v);
	} else {
		setverdict(fail, "FH enabled, but Mobile Allocation IE is absent");
		return;
	}

	f_perform_clear_test_ct(dt);
}
testcase TC_fh_params_handover_cmd() runs on test_CT {
	var FHParamsTrx fhp := f_TC_fh_params_gen();

	f_init_vty();

	/* (Re)configure TS0 as BCCH and TS1 as SDCCH8 on BTS1/TRX0 */
	f_vty_enter_cfg_trx(BSCVTY, bts := 1, trx := 0);

	f_vty_transceive(BSCVTY, "timeslot 0");
	f_vty_transceive(BSCVTY, "phys_chan_config ccch");
	f_vty_transceive(BSCVTY, "exit"); /* go back */

	f_vty_transceive(BSCVTY, "timeslot 1");
	f_vty_transceive(BSCVTY, "phys_chan_config sdcch8");
	f_vty_transceive(BSCVTY, "end"); /* we're done */

	f_TC_fh_params_set(fhp, 1); /* Enable frequency hopping on BTS1 */
	f_vty_transceive(BSCVTY, "drop bts connection 1 oml");

	f_init(2);

	f_TC_fh_params_handover_cmd(fhp);

	/* Disable frequency hopping on BTS1 */
	f_TC_fh_params_unset(fhp, 1);

	/* (Re)configure TS0 as CCCH+SDCCH4+CBCH and TS1 as TCH/F */
	f_vty_enter_cfg_trx(BSCVTY, bts := 1, trx := 0);

	f_vty_transceive(BSCVTY, "timeslot 0");
	f_vty_transceive(BSCVTY, "phys_chan_config ccch+sdcch4+cbch");
	f_vty_transceive(BSCVTY, "exit"); /* go back */

	f_vty_transceive(BSCVTY, "timeslot 1");
	f_vty_transceive(BSCVTY, "phys_chan_config tch/f");
	f_vty_transceive(BSCVTY, "end"); /* we're done */

	f_shutdown_helper();
}

/* Verify the hopping parameters in System Information Type 4 */
testcase TC_fh_params_si4_cbch() runs on test_CT {
	var FHParamsTrx fhp := f_TC_fh_params_gen(tr_tn := 1);
	var ASP_RSL_Unitdata rx_rsl_ud;
	timer T := 5.0;

	f_init_vty();

	/* (Re)configure TS0 as BCCH and TS1 as SDCCH8+CBCH */
	f_vty_enter_cfg_trx(BSCVTY, trx := 0);

	f_vty_transceive(BSCVTY, "timeslot 0");
	f_vty_transceive(BSCVTY, "phys_chan_config ccch");
	f_vty_transceive(BSCVTY, "exit"); /* go back */

	f_vty_transceive(BSCVTY, "timeslot 1");
	f_vty_transceive(BSCVTY, "phys_chan_config sdcch8+cbch");
	f_vty_transceive(BSCVTY, "end"); /* we're done */

	f_TC_fh_params_set(fhp); /* Enable frequency hopping */
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1);

	T.start;
	alt {
	[] IPA_RSL[0][0].receive(tr_ASP_RSL_UD(tr_RSL_BCCH_INFO(RSL_SYSTEM_INFO_4))) -> value rx_rsl_ud {
		var RSL_IE_Body ie := rx_rsl_ud.rsl.ies[2].body; /* FULL BCCH Information IE */
		var SystemInformation si := dec_SystemInformation(ie.other.payload);

		/* Make sure that what we decoded is System Information Type 4 */
		if (si.header.message_type != SYSTEM_INFORMATION_TYPE_4) {
			setverdict(fail, "RSL FULL BCCH Information IE contains: ", si);
			repeat;
		}

		/* Make sure that CBCH Channel Description IE is present */
		if (not ispresent(si.payload.si4.cbch_chan_desc)) {
			setverdict(fail, "CBCH Channel Description IE is absent");
			break;
		}

		/* Finally, check the hopping parameters (HSN, MAIO) */
		var ChannelDescription chan_desc := si.payload.si4.cbch_chan_desc.v;
		f_TC_fh_params_match_chan_desc(fhp, chan_desc);

		/* 3GPP TS 44.018, section 9.1.36.2 "CBCH Mobile Allocation":
		 * The CBCH Mobile Allocation IE *shall* be present if FH is enabled. */
		if (chan_desc.h and not ispresent(si.payload.si4.cbch_mobile_alloc)) {
			setverdict(fail, "FH enabled, but Mobile Allocation IE is absent");
			break;
		} else if (chan_desc.h and ispresent(si.payload.si4.cbch_mobile_alloc)) {
			f_TC_fh_params_match_ma(fhp, chan_desc.chan_nr.tn,
						si.payload.si4.cbch_mobile_alloc.v);
		}
		}
	[] IPA_RSL[0][0].receive { repeat; }
	[] T.timeout {
		setverdict(fail, "Timeout waiting for RSL BCCH INFOrmation (SI4)");
		}
	}

	/* Disable frequency hopping */
	f_TC_fh_params_unset(fhp);

	/* (Re)configure TS0 as CCCH+SDCCH4+CBCH and TS1 as TCH/F */
	f_vty_enter_cfg_trx(BSCVTY, trx := 0);

	f_vty_transceive(BSCVTY, "timeslot 0");
	f_vty_transceive(BSCVTY, "phys_chan_config ccch+sdcch4+cbch");
	f_vty_transceive(BSCVTY, "exit"); /* go back */

	f_vty_transceive(BSCVTY, "timeslot 1");
	f_vty_transceive(BSCVTY, "phys_chan_config tch/f");
	f_vty_transceive(BSCVTY, "end"); /* we're done */

	f_shutdown_helper();
}

template (value) PDU_BSSAP_LE ts_BSSMAP_LE_BSSLAP(template (value) BSSLAP_PDU bsslap)
	:= ts_BSSMAP_LE_ConnInfo(BSSMAP_LE_PROT_BSSLAP, data := enc_BSSLAP_PDU(valueof(bsslap)));

private function f_match_bsslap(PDU_BSSAP_LE got_bsslap_msg,
				template (present) BSSLAP_PDU expect_bsslap)
{
	var BSSLAP_PDU bsslap := dec_BSSLAP_PDU(got_bsslap_msg.pdu.bssmap.co_info.bsslap_apdu.data);
	if (not match(bsslap, expect_bsslap)) {
		log("EXPECTING BSSLAP: ", expect_bsslap);
		log("GOT BSSLAP: ", bsslap);
		setverdict(fail, "BSSLAP is not as expected");
		mtc.stop;
	}
	setverdict(pass);
}

/* GAD: this is an Ellipsoid point with uncertainty circle, encoded as in 3GPP TS 23.032 §7.3.2. */
const octetstring gad_ell_point_unc_circle := '10b0646d0d5f6627'O;

private function f_expect_bsslap(template (present) BSSLAP_PDU expect_rx_bsslap) runs on MSC_ConnHdlr {
	var PDU_BSSAP_LE rx_bsslap;
	BSSAP_LE.receive(tr_BSSMAP_LE_ConnInfo(BSSMAP_LE_PROT_BSSLAP, ?)) -> value(rx_bsslap);
	f_match_bsslap(rx_bsslap, expect_rx_bsslap);
}

/* With an active lchan, start BSSMAP Perform Location Request on A interface, starting BSSMAP-LE Perform Location
 * Request on Lb interface. Either with or without the SMLC doing a BSSLAP TA Request. */
private function f_lcs_loc_req_for_active_ms(boolean do_ta_request := false) runs on MSC_ConnHdlr {
	f_sleep(1.0);

	f_establish_fully(omit, omit);
	f_bssap_le_register_imsi(g_pars.imsi, omit);

	BSSAP.send(valueof(ts_BSSMAP_Perform_Location_Request(ts_BSSMAP_Imsi(g_pars.imsi),
					ts_CellId_CGI('262'H, '42'H, 23, 42))));

	var PDU_BSSAP_LE plr;
	BSSAP_LE.receive(tr_BSSMAP_LE_PerfLocReq(BSSMAP_LE_LOC_INFO_CURRENT_GEOGRAPHIC_LOC, ?, ?)) -> value(plr);

	if (not do_ta_request) {
		/* verify TA Layer 3 in APDU. First the APDU type (BSSLAP), then the BSSLAP data contents. */
		var template BSSMAP_LE_IE_APDU expect_apdu := tr_BSSMAP_LE_APDU(BSSMAP_LE_PROT_BSSLAP, ?);
		if (not match(plr.pdu.bssmap.perf_loc_req.bsslap_apdu, expect_apdu)) {
			log("EXPECTING BSSMAP-LE APDU IE ", expect_apdu);
			log("GOT BSSMAP-LE APDU IE ", plr.pdu.bssmap.perf_loc_req.bsslap_apdu);
			setverdict(fail, "BSSMAP-LE APDU IE is not as expected");
			mtc.stop;
		}
		var template BSSLAP_PDU expect_ta_layer3 := tr_BSSLAP_TA_Layer3(tr_BSSLAP_IE_TA(0));
		var BSSLAP_PDU bsslap := dec_BSSLAP_PDU(plr.pdu.bssmap.perf_loc_req.bsslap_apdu.data);
		if (not match(bsslap, expect_ta_layer3)) {
			log("EXPECTING BSSLAP TA Layer 3: ", expect_ta_layer3);
			log("GOT BSSLAP: ", bsslap);
			setverdict(fail, "BSSLAP is not as expected");
			mtc.stop;
		}
		/* OsmoBSC directly sent the TA as BSSLAP APDU in the BSSMAP-LE Perform Location Request to the SMLC. The SMLC
		 * has no need to request the TA from the BSC and directly responds. */
	} else {
		/* SMLC wants to ask the TA from the BSC explicitly in a BSSLAP TA Request message */
		BSSAP_LE.send(ts_BSSMAP_LE_BSSLAP(ts_BSSLAP_TA_Req));
		f_expect_bsslap(tr_BSSLAP_TA_Resp(?, ?));
	}

	/* SMLC got the TA from the BSC, now responds with geo information data. */
	BSSAP_LE.send(ts_BSSMAP_LE_PerfLocResp(gad_ell_point_unc_circle, omit));
	BSSAP_LE.receive(BSSAP_LE_Conn_Prim:CONN_PRIM_DISC_IND);
	BSSAP.receive(tr_BSSMAP_Perform_Location_Response(tr_BSSMAP_IE_LocationEstimate(gad_ell_point_unc_circle)));

	/* The LCS was using an active A-interface conn. It should still remain active after this. */
	f_mo_l3_transceive();

	f_perform_clear();

	f_sleep(2.0);
	setverdict(pass);
}

/* With an active lchan, start BSSMAP Perform Location Request on A interface, starting BSSMAP-LE Perform Location
 * Request on Lb interface.  Without the SMLC doing a BSSLAP TA Request. */
private function f_tc_lcs_loc_req_for_active_ms(charstring id) runs on MSC_ConnHdlr {
	f_lcs_loc_req_for_active_ms(false);
}
testcase TC_lcs_loc_req_for_active_ms() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_lcs_loc_req_for_active_ms), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* With an active lchan, start BSSMAP Perform Location Request on A interface, starting BSSMAP-LE Perform Location
 * Request on Lb interface.  With the SMLC doing a BSSLAP TA Request. */
private function f_tc_lcs_loc_req_for_active_ms_ta_req(charstring id) runs on MSC_ConnHdlr {
	f_lcs_loc_req_for_active_ms(true);
}
testcase TC_lcs_loc_req_for_active_ms_ta_req() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_lcs_loc_req_for_active_ms_ta_req), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* Clear the A-interface conn only, without doing anything on Abis. Useful for LCS, for cases where there is only an A
 * conn without an active lchan. */
private function f_clear_A_conn() runs on MSC_ConnHdlr
{
	var BssmapCause cause := 0;
	BSSAP.send(ts_BSSMAP_ClearCommand(cause));
	BSSAP.receive(tr_BSSMAP_ClearComplete);
	BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);

	timer no_more_bssap := 5.0;
	no_more_bssap.start;
	alt {
	[] no_more_bssap.timeout { break; }
	[] BSSAP.receive(tr_BSSAP_BSSMAP) {
		setverdict(fail, "Expected no more BSSAP after Clear Complete");
		mtc.stop;
	}
	}
	setverdict(pass);
}

/* Verify that the A-interface connection is still working, and then clear it, without doing anything on Abis.  Useful
 * for LCS, for cases where there is only an A conn without an active lchan. */
private function f_verify_active_A_conn_and_clear() runs on MSC_ConnHdlr
{
	f_logp(BSCVTY, "f_verify_active_A_conn_and_clear: test A link, then clear");

	/* When an lchan is active, we can send some L3 data from the BTS side and verify that it shows up on the other
	 * side towards the MSC. When there is no lchan, this is not possible. To probe whether the A-interface
	 * connection is still up, we need something that echos back on the A-interface. Another LCS request! */
	BSSAP.send(valueof(ts_BSSMAP_Perform_Location_Request(ts_BSSMAP_Imsi(g_pars.imsi),
					ts_CellId_CGI('262'H, '42'H, 23, 42))));
	BSSAP_LE.receive(tr_BSSMAP_LE_PerfLocReq(BSSMAP_LE_LOC_INFO_CURRENT_GEOGRAPHIC_LOC, ?, ?));

	/* Right, the Perform Location Request showed up on Lb, now we can clear the A conn. */
	f_clear_A_conn();
	BSSAP_LE.receive(tr_BSSMAP_LE_PerfLocAbort(BSSMAP_LE_LCS_CAUSE_REQUEST_ABORTED));
	BSSAP_LE.receive(BSSAP_LE_Conn_Prim:CONN_PRIM_DISC_IND);
}

/* With *no* active lchan, start BSSMAP Perform Location Request on A interface, starting BSSMAP-LE Perform Location
 * Request on Lb interface. BSC will Page for the subscriber as soon as we (virtual SMLC) request the TA via BSSLAP.
 */
private function f_tc_lcs_loc_req_for_idle_ms(charstring id) runs on MSC_ConnHdlr {
	f_sleep(1.0);

	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);
	f_bssap_le_register_imsi(g_pars.imsi, omit);

	/* Register to receive the Paging Command */
	var RslChannelNr new_chan_nr := valueof(t_RslChanNr0(1, RSL_CHAN_NR_Bm_ACCH));
	g_chan_nr := new_chan_nr;
	f_rslem_register(0, g_chan_nr);

	BSSAP.send(ts_BSSAP_Conn_Req(g_pars.sccp_addr_bsc, g_pars.sccp_addr_msc,
				     valueof(ts_BSSMAP_Perform_Location_Request(ts_BSSMAP_Imsi(g_pars.imsi),
										ts_CellId_CGI('001'H, '01'H, 1, 0)))));
	BSSAP.receive(RAN_Conn_Prim:MSC_CONN_PRIM_CONF_IND);

	var PDU_BSSAP_LE plr;
	BSSAP_LE.receive(tr_BSSMAP_LE_PerfLocReq(BSSMAP_LE_LOC_INFO_CURRENT_GEOGRAPHIC_LOC, ?, ?)) -> value(plr);

	/* SMLC wants to ask the TA from the BSC explicitly in a BSSLAP TA Request message */
	BSSAP_LE.send(ts_BSSMAP_LE_BSSLAP(ts_BSSLAP_TA_Req));

	/* OsmoBSC needs to Page */
	RSL.receive(tr_RSL_PAGING_CMD(tr_MI_IMSI(g_pars.imsi)));
	f_logp(BSCVTY, "got Paging Command");

	/* MS requests channel. Since the Paging was for LCS, the Paging Response does not trigger a Complete Layer 3 to
	 * the MSC, and releases the lchan directly. */
	f_perform_compl_l3(RSL, RSL_PROC, ts_PAG_RESP(valueof(ts_MI_IMSI_LV(g_pars.imsi))), do_clear := false, expect_bssmap_l3 := false);
	f_expect_lchan_rel(RSL, RSL_PROC);

	/* From the Paging Response, the TA is now known to the BSC, and it responds to the SMLC. */

	f_expect_bsslap(tr_BSSLAP_TA_Resp(?, ?));

	/* SMLC got the TA from the BSC, now responds with geo information data. */
	BSSAP_LE.send(ts_BSSMAP_LE_PerfLocResp(gad_ell_point_unc_circle, omit));
	BSSAP_LE.receive(BSSAP_LE_Conn_Prim:CONN_PRIM_DISC_IND);

	BSSAP.receive(tr_BSSMAP_Perform_Location_Response(tr_BSSMAP_IE_LocationEstimate(gad_ell_point_unc_circle)));

	/* The lchan is gone, the A-interface conn was created for the LCS only.
	 * Still it is clearly the MSC's job to decide whether to tear down the conn or not. */
	f_verify_active_A_conn_and_clear();

	f_sleep(2.0);
	setverdict(pass);
}
testcase TC_lcs_loc_req_for_idle_ms() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);

	pars.sccp_addr_msc := g_bssap[0].sccp_addr_own;
	pars.sccp_addr_bsc := g_bssap[0].sccp_addr_peer;

	vc_conn := f_start_handler(refers(f_tc_lcs_loc_req_for_idle_ms), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* With no active lchan, start BSSMAP Perform Location Request on A interface, but omit IMSI; expect failure response.
 */
private function f_tc_lcs_loc_req_no_subscriber(charstring id) runs on MSC_ConnHdlr {
	f_sleep(1.0);

	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);
	f_bssap_le_register_imsi(g_pars.imsi, omit);

	/* provoke an abort by omitting both IMSI and IMEI */
	BSSAP.send(ts_BSSAP_Conn_Req(g_pars.sccp_addr_bsc, g_pars.sccp_addr_msc,
				valueof(ts_BSSMAP_Perform_Location_Request(omit,
					ts_CellId_CGI('262'H, '42'H, 23, 42)))));
	BSSAP.receive(RAN_Conn_Prim:MSC_CONN_PRIM_CONF_IND);

	/* BSC tells MSC about failure */
	BSSAP.receive(tr_BSSMAP_Perform_Location_Response(
			locationEstimate := omit, positioningData := omit,
			lCS_Cause := tr_BSSMAP_LcsCause(BSSMAP_LCS_CAUSE_DATA_MISSING_IN_REQ)));

	/* There is no lchan. Still the MSC's job to decide whether to tear down the conn or not. */
	f_verify_active_A_conn_and_clear();

	f_sleep(2.0);
	setverdict(pass);
}
testcase TC_lcs_loc_req_no_subscriber() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);

	pars.sccp_addr_msc := g_bssap[0].sccp_addr_own;
	pars.sccp_addr_bsc := g_bssap[0].sccp_addr_peer;

	vc_conn := f_start_handler(refers(f_tc_lcs_loc_req_no_subscriber), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* With an active lchan, start a Perform Location Request on the A-interface, but virtual SMLC does not answer with
 * BSSMAP-LE Perform Location Response (before or after sending a BSSLAP TA Request) */
private function f_lcs_loc_req_for_active_ms_le_timeout(boolean do_ta) runs on MSC_ConnHdlr {
	f_sleep(1.0);

	f_establish_fully(omit, omit);
	f_bssap_le_register_imsi(g_pars.imsi, omit);

	BSSAP.send(valueof(ts_BSSMAP_Perform_Location_Request(ts_BSSMAP_Imsi(g_pars.imsi),
					ts_CellId_CGI('262'H, '42'H, 23, 42))));

	var PDU_BSSAP_LE plr;
	BSSAP_LE.receive(tr_BSSMAP_LE_PerfLocReq(BSSMAP_LE_LOC_INFO_CURRENT_GEOGRAPHIC_LOC, ?, ?)) -> value(plr);

	if (do_ta) {
		/* SMLC wants to ask the TA from the BSC explicitly in a BSSLAP TA Request message */
		BSSAP_LE.send(ts_BSSMAP_LE_BSSLAP(ts_BSSLAP_TA_Req));
		f_expect_bsslap(tr_BSSLAP_TA_Resp(?, ?));
	}

	/* SMLC fails to respond, BSC runs into timeout */
	BSSAP_LE.receive(tr_BSSMAP_LE_PerfLocAbort(BSSMAP_LE_LCS_CAUSE_SYSTEM_FAILURE));
	BSSAP_LE.receive(BSSAP_LE_Conn_Prim:CONN_PRIM_DISC_IND);

	BSSAP.receive(tr_BSSMAP_Perform_Location_Response(
			locationEstimate := omit, positioningData := omit,
			lCS_Cause := tr_BSSMAP_LcsCause(BSSMAP_LCS_CAUSE_SYSTEM_FAILURE)));

	/* There is no lchan. Still the MSC's job to decide whether to tear down the conn or not. */
	f_verify_active_A_conn_and_clear();

	f_sleep(2.0);
	setverdict(pass);
}

/* With an active lchan, start a Perform Location Request on the A-interface, but virtual SMLC does not answer with
 * BSSMAP-LE Perform Location Response, without sending a BSSLAP TA Request. */
private function f_tc_lcs_loc_req_for_active_ms_le_timeout(charstring id) runs on MSC_ConnHdlr {
	f_lcs_loc_req_for_active_ms_le_timeout(false);
}

testcase TC_lcs_loc_req_for_active_ms_le_timeout() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_lcs_loc_req_for_active_ms_le_timeout), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* With an active lchan, start a Perform Location Request on the A-interface, but virtual SMLC does not answer with
 * BSSMAP-LE Perform Location Response, after sending a BSSLAP TA Request. */
private function f_tc_lcs_loc_req_for_active_ms_le_timeout2(charstring id) runs on MSC_ConnHdlr {
	f_lcs_loc_req_for_active_ms_le_timeout(true);
}

testcase TC_lcs_loc_req_for_active_ms_le_timeout2() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_lcs_loc_req_for_active_ms_le_timeout2), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* With *no* active lchan, start a Perform Location Request, expecting that the MS will be Paged. */
private function f_tc_lcs_loc_req_for_idle_ms_no_pag_resp(charstring id) runs on MSC_ConnHdlr {
	f_sleep(1.0);

	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);
	f_bssap_le_register_imsi(g_pars.imsi, omit);

	/* Register to receive the Paging Command */
	var RslChannelNr new_chan_nr := valueof(t_RslChanNr0(1, RSL_CHAN_NR_Bm_ACCH));
	g_chan_nr := new_chan_nr;
	f_rslem_register(0, g_chan_nr);

	BSSAP.send(ts_BSSAP_Conn_Req(g_pars.sccp_addr_bsc, g_pars.sccp_addr_msc,
				     valueof(ts_BSSMAP_Perform_Location_Request(ts_BSSMAP_Imsi(g_pars.imsi),
										ts_CellId_CGI('001'H, '01'H, 1, 0)))));
	BSSAP.receive(RAN_Conn_Prim:MSC_CONN_PRIM_CONF_IND);

	var PDU_BSSAP_LE plr;
	BSSAP_LE.receive(tr_BSSMAP_LE_PerfLocReq(BSSMAP_LE_LOC_INFO_CURRENT_GEOGRAPHIC_LOC, ?, ?)) -> value(plr);

	/* SMLC wants to ask the TA from the BSC explicitly in a BSSLAP TA Request message */
	BSSAP_LE.send(ts_BSSMAP_LE_BSSLAP(ts_BSSLAP_TA_Req));

	/* OsmoBSC needs to Page */
	var PDU_BSSAP_LE rx_bsslap;
	alt {
	[] RSL.receive(tr_RSL_PAGING_CMD(tr_MI_IMSI(g_pars.imsi))) {
		f_logp(BSCVTY, "got Paging Command");
		repeat;
	}
	[] BSSAP_LE.receive(tr_BSSMAP_LE_ConnInfo(BSSMAP_LE_PROT_BSSLAP, ?)) -> value(rx_bsslap) {
		/* MS does not respond to Paging, TA Req runs into timeout. */
		f_match_bsslap(rx_bsslap, tr_BSSLAP_Abort(?));
	}
	}

	/* SMLC responds with failure */
	BSSAP_LE.send(ts_BSSMAP_LE_PerfLocResp(omit, BSSMAP_LE_LCS_CAUSE_REQUEST_ABORTED));
	BSSAP_LE.receive(BSSAP_LE_Conn_Prim:CONN_PRIM_DISC_IND);

	/* BSC tells MSC about failure */
	BSSAP.receive(tr_BSSMAP_Perform_Location_Response(
			locationEstimate := omit, positioningData := omit,
			lCS_Cause := tr_BSSMAP_LcsCause(BSSMAP_LCS_CAUSE_REQUEST_ABORTED)));

	/* There is no lchan. Still the MSC's job to decide whether to tear down the conn or not. */
	f_verify_active_A_conn_and_clear();

	f_sleep(2.0);
	setverdict(pass);
}
testcase TC_lcs_loc_req_for_idle_ms_no_pag_resp() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);

	pars.sccp_addr_msc := g_bssap[0].sccp_addr_own;
	pars.sccp_addr_bsc := g_bssap[0].sccp_addr_peer;

	vc_conn := f_start_handler(refers(f_tc_lcs_loc_req_for_idle_ms_no_pag_resp), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* During an ongoing Location Request, the MS sends a CM Service Request. Expect the same A-conn to be re-used / taken
 * over. */
private function f_tc_cm_service_during_lcs_loc_req(charstring id) runs on MSC_ConnHdlr {
	f_sleep(1.0);

	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);
	f_bssap_le_register_imsi(g_pars.imsi, omit);

	/* Register to receive the Paging Command */
	var RslChannelNr new_chan_nr := valueof(t_RslChanNr0(1, RSL_CHAN_NR_Bm_ACCH));
	g_chan_nr := new_chan_nr;
	f_rslem_register(0, g_chan_nr);

	BSSAP.send(ts_BSSAP_Conn_Req(g_pars.sccp_addr_bsc, g_pars.sccp_addr_msc,
				     valueof(ts_BSSMAP_Perform_Location_Request(ts_BSSMAP_Imsi(g_pars.imsi),
										ts_CellId_CGI('001'H, '01'H, 1, 0)))));
	BSSAP.receive(RAN_Conn_Prim:MSC_CONN_PRIM_CONF_IND);

	var PDU_BSSAP_LE plr;
	BSSAP_LE.receive(tr_BSSMAP_LE_PerfLocReq(BSSMAP_LE_LOC_INFO_CURRENT_GEOGRAPHIC_LOC, ?, ?)) -> value(plr);

	/* As the A-interface conn was established for LCS, the MS coincidentally decides to issue a CM Service Request
	 * and establish Layer 3. It should use the existing A-interface conn. */
	f_perform_compl_l3(RSL, RSL_PROC, valueof(ts_CM_SERV_REQ(CM_TYPE_MO_CALL, valueof(ts_MI_IMSI_LV(g_pars.imsi)))),
			do_clear := false, expect_bssmap_l3 := true);

	/* SMLC wants to ask the TA from the BSC explicitly in a BSSLAP TA Request message */
	BSSAP_LE.send(ts_BSSMAP_LE_BSSLAP(ts_BSSLAP_TA_Req));

	/* OsmoBSC already has an lchan, no need to Page, just returns the TA */
	f_expect_bsslap(tr_BSSLAP_TA_Resp(?, ?));

	/* SMLC got the TA from the BSC, now responds with geo information data. */
	BSSAP_LE.send(ts_BSSMAP_LE_PerfLocResp(gad_ell_point_unc_circle, omit));
	BSSAP_LE.receive(BSSAP_LE_Conn_Prim:CONN_PRIM_DISC_IND);
	BSSAP.receive(tr_BSSMAP_Perform_Location_Response(tr_BSSMAP_IE_LocationEstimate(gad_ell_point_unc_circle)));

	/* The lchan should still exist, it was from a CM Service Request. */
	f_mo_l3_transceive();

	f_perform_clear();

	f_sleep(2.0);
	setverdict(pass);
}
testcase TC_cm_service_during_lcs_loc_req() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);

	pars.sccp_addr_msc := g_bssap[0].sccp_addr_own;
	pars.sccp_addr_bsc := g_bssap[0].sccp_addr_peer;

	vc_conn := f_start_handler(refers(f_tc_cm_service_during_lcs_loc_req), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* During an ongoing Perform Location Request, do a Handover, an expect a BSSLAP Reset message from the BSC to indicate
 * the new lchan after handover. */
private function f_tc_ho_during_lcs_loc_req(charstring id) runs on MSC_ConnHdlr {
	f_sleep(1.0);

	f_establish_fully(omit, omit);
	f_bssap_le_register_imsi(g_pars.imsi, omit);

	BSSAP.send(valueof(ts_BSSMAP_Perform_Location_Request(ts_BSSMAP_Imsi(g_pars.imsi),
					ts_CellId_CGI('262'H, '42'H, 23, 42))));

	var PDU_BSSAP_LE plr;
	BSSAP_LE.receive(tr_BSSMAP_LE_PerfLocReq(BSSMAP_LE_LOC_INFO_CURRENT_GEOGRAPHIC_LOC, ?, ?)) -> value(plr);

	/* SMLC ponders the Location Request, in the meantime the BSC decides to handover */
	f_bts_0_cfg(BSCVTY, {"neighbor bts 1"});

	var HandoverState hs := {
		rr_ho_cmpl_seen := false,
		handover_done := false,
		old_chan_nr := -,
		expect_target_tsc := c_BtsParams[1].tsc
	};
	/* issue hand-over command on VTY */
	f_vty_handover(BSCVTY, 0, 0, g_chan_nr, 1);
	/* temporarily suspend DChan processing on BTS1 to avoid race with RSLEM_register */
	f_rslem_suspend(RSL1_PROC);

	/* From the MGW perspective, a handover is is characterized by
	 * performing one MDCX operation with the MGW. So we expect to see
	 * one more MDCX during handover. */
	g_media.mgcp_conn[0].mdcx_seen_exp := g_media.mgcp_conn[0].crcx_seen_exp + 1;

	alt {
	[] as_handover(hs);
	}

	var PDU_BSSAP_LE rx_bsslap;

	interleave {
	/* Expect the BSC to inform the MSC about the handover */
	[] BSSAP.receive(tr_BSSMAP_HandoverPerformed);

	/* Expect the BSC to inform the SMLC about the handover */
	[] BSSAP_LE.receive(tr_BSSMAP_LE_ConnInfo(BSSMAP_LE_PROT_BSSLAP, ?)) -> value(rx_bsslap) {
		f_match_bsslap(rx_bsslap, tr_BSSLAP_Reset(BSSLAP_CAUSE_INTRA_BSS_HO));
	}
	}

	/* SMLC now responds with geo information data. */
	BSSAP_LE.send(ts_BSSMAP_LE_PerfLocResp(gad_ell_point_unc_circle, omit));
	BSSAP_LE.receive(BSSAP_LE_Conn_Prim:CONN_PRIM_DISC_IND);
	BSSAP.receive(tr_BSSMAP_Perform_Location_Response(tr_BSSMAP_IE_LocationEstimate(gad_ell_point_unc_circle)));

	/* lchan still active */
	f_mo_l3_transceive(RSL1);

	/* MSC decides it is done now. */
	f_perform_clear(RSL1, RSL1_PROC);

	f_sleep(2.0);
	setverdict(pass);
}
testcase TC_ho_during_lcs_loc_req() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(2, true);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_tc_ho_during_lcs_loc_req), pars);
	vc_conn.done;
	f_shutdown_helper();
}

private function f_tc_emerg_call_and_lcs_loc_req(charstring id) runs on MSC_ConnHdlr
{
	/* Make sure the CHAN RQD indicates an emergency call (0b101xxxxx). The difference is that osmo-bsc directly
	 * assigns a TCH lchan and establishing voice for the emergency call will use Mode Modify, not reassignment to
	 * another lchan. */
	g_pars.ra := 'b7'O;
	f_assignment_emerg_setup();

	var PDU_BSSAP emerg_setup_data_ind_bssap;
	timer T := 3.0;
	T.start;
	alt {
	[] BSSAP.receive(tr_BSSAP_DTAP) -> value emerg_setup_data_ind_bssap {
		var PDU_ML3_MS_NW verify_emerg_setup;
		verify_emerg_setup := dec_PDU_ML3_MS_NW(emerg_setup_data_ind_bssap.pdu.dtap);
		if (not isbound(verify_emerg_setup.msgs.cc.emergencySetup)) {
			setverdict(fail, "no emergency setup");
		}
		}
	[] BSSAP.receive {
		setverdict(fail, "unexpected BSSAP message!");
		}
	[] T.timeout {
		setverdict(fail, "timeout waiting for EMERGENCY SETUP!");
		}
	}

	/* Here would usually be a CC Call Proceeding from the MSC, but what does the BSC care about DTAP. */

	/* Do a Location Request in-between the CC call setup */
	f_bssap_le_register_imsi(g_pars.imsi, omit);
	BSSAP.send(valueof(ts_BSSMAP_Perform_Location_Request(ts_BSSMAP_Imsi(g_pars.imsi),
					ts_CellId_CGI('262'H, '42'H, 23, 42))));
	BSSAP_LE.receive(tr_BSSMAP_LE_PerfLocReq(BSSMAP_LE_LOC_INFO_CURRENT_GEOGRAPHIC_LOC, ?, ?));
	/* SMLC got the TA from the BSC, now responds with geo information data. */
	BSSAP_LE.send(ts_BSSMAP_LE_PerfLocResp(gad_ell_point_unc_circle, omit));
	BSSAP_LE.receive(BSSAP_LE_Conn_Prim:CONN_PRIM_DISC_IND);
	BSSAP.receive(tr_BSSMAP_Perform_Location_Response(tr_BSSMAP_IE_LocationEstimate(gad_ell_point_unc_circle)));

	/* Go on with voice call assignment */
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();

	/* Below speechOrDataIndicator and codecList are copied from an emergency call captured during tests.
	 * They seem a bit weird (AMR-WB, and the order differ between speechId_DataIndicator and the codecList), but
	 * seems a good idea to see how osmo-bsc reacts to this. */
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := {
		elementIdentifier := '0B'O,	/* overwritten */
		lengthIndicator := 0,		/* overwritten */
		speechOrDataIndicator := '0001'B,	/* speech */
		spare1_4 := '0000'B,
		channelRateAndType := ChRate_TCHForH_Fpref,
		speechId_DataIndicator := 'c2918105'O
	};
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({
		ts_CodecHR, ts_CodecAMR_WB, ts_CodecEFR, ts_CodecFR}));

	f_rslem_dchan_queue_enable();

	var ExpectCriteria mgcpcrit := {
		connid := omit,
		endpoint := omit,
		transid := omit
	};
	f_create_mgcp_expect(mgcpcrit);

	BSSAP.send(ass_cmd);

	var AssignmentState st := valueof(ts_AssignmentStateInit);
	st.voice_call := true;
	st.is_assignment := false;
	alt {
	[] as_modify(st);
	[] as_Media();
	[st.modify_done] BSSAP.receive(exp_compl) {
		setverdict(pass);
		}
	}

	/* Voice call carries on ... */
	f_sleep(2.0);

	setverdict(pass);
	f_perform_clear();
}

testcase TC_emerg_call_and_lcs_loc_req() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);
	f_vty_allow_emerg_msc(true);
	f_vty_allow_emerg_bts(true, 0);
	vc_conn := f_start_handler(refers(f_tc_emerg_call_and_lcs_loc_req), pars);
	vc_conn.done;
	f_shutdown_helper();
}

private altstep no_bssmap_clear_req() runs on MSC_ConnHdlr {
	[] BSSAP.receive(tr_BSSMAP_ClearRequest) {
		setverdict(fail, "unexpected BSSMAP Clear Request");
		mtc.stop;
	}
}

private type enumerated RslRel {
	RSLREL_REL_IND,
	RSLREL_CONN_FAIL
};

private function f_emerg_call_and_lcs_loc_req_early_lchan_release(RslRel rsl_rel) runs on MSC_ConnHdlr
{
	g_pars.ra := f_rnd_ra_emerg();
	f_assignment_emerg_setup();

	var PDU_BSSAP emerg_setup_data_ind_bssap;
	timer T := 3.0;
	T.start;
	alt {
	[] BSSAP.receive(tr_BSSAP_DTAP) -> value emerg_setup_data_ind_bssap {
		var PDU_ML3_MS_NW verify_emerg_setup;
		verify_emerg_setup := dec_PDU_ML3_MS_NW(emerg_setup_data_ind_bssap.pdu.dtap);
		if (not ischosen(verify_emerg_setup.msgs.cc.emergencySetup)) {
			setverdict(fail, "no emergency setup");
		}
		}
	[] BSSAP.receive {
		setverdict(fail, "unexpected BSSAP message!");
		}
	[] T.timeout {
		setverdict(fail, "timeout waiting for EMERGENCY SETUP!");
		}
	}

	/* Start a Location Request to locate the emergency */
	f_bssap_le_register_imsi(g_pars.imsi, omit);
	BSSAP.send(valueof(ts_BSSMAP_Perform_Location_Request(ts_BSSMAP_Imsi(g_pars.imsi),
					ts_CellId_CGI('262'H, '42'H, 23, 42))));
	BSSAP_LE.receive(tr_BSSMAP_LE_PerfLocReq(BSSMAP_LE_LOC_INFO_CURRENT_GEOGRAPHIC_LOC, ?, ?));

	/* As long as this LCS is going on, the BSC should not send any Clear Request. Later on, it is up to the MSC to
	 * do a Clear Command when the Location Response arrives. */
	activate(no_bssmap_clear_req());

	/* the lchan gets interrupted while the Location Request has no response */
	select (rsl_rel) {
	case (RSLREL_REL_IND) {
			RSL.send(ts_RSL_REL_IND(g_chan_nr, valueof(ts_RslLinkID_DCCH(0))));
			f_expect_lchan_rel(RSL, RSL_PROC);
		}
	case (RSLREL_CONN_FAIL) {
			RSL.send(ts_RSL_CONN_FAIL_IND(g_chan_nr, RSL_ERR_RADIO_LINK_FAIL));
		}
	case else {
			setverdict(fail, "Unknown RslRel type");
			mtc.stop;
		}
	}

	/* Still expect the Location Response to find its way to the MSC. */
	BSSAP_LE.send(ts_BSSMAP_LE_PerfLocResp(gad_ell_point_unc_circle, omit));
	BSSAP_LE.receive(BSSAP_LE_Conn_Prim:CONN_PRIM_DISC_IND);
	BSSAP.receive(tr_BSSMAP_Perform_Location_Response(tr_BSSMAP_IE_LocationEstimate(gad_ell_point_unc_circle)));

	setverdict(pass);

	select (rsl_rel) {
	case (RSLREL_REL_IND) {
			f_perform_clear_no_lchan();
		}
	case (RSLREL_CONN_FAIL) {
			f_perform_clear();
		}
	}
}

private function f_tc_emerg_call_and_lcs_loc_req_early_lchan_rel_ind(charstring id) runs on MSC_ConnHdlr
{
	f_emerg_call_and_lcs_loc_req_early_lchan_release(RSLREL_REL_IND);
}

testcase TC_emerg_call_and_lcs_loc_req_early_lchan_rel_ind() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);
	f_vty_allow_emerg_msc(true);
	f_vty_allow_emerg_bts(true, 0);
	vc_conn := f_start_handler(refers(f_tc_emerg_call_and_lcs_loc_req_early_lchan_rel_ind), pars);
	vc_conn.done;
	f_shutdown_helper();
}

private function f_tc_emerg_call_and_lcs_loc_req_early_lchan_conn_fail(charstring id) runs on MSC_ConnHdlr
{
	f_emerg_call_and_lcs_loc_req_early_lchan_release(RSLREL_CONN_FAIL);
}

testcase TC_emerg_call_and_lcs_loc_req_early_lchan_conn_fail() runs on test_CT {
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_init(1, true);
	f_sleep(1.0);
	f_vty_allow_emerg_msc(true);
	f_vty_allow_emerg_bts(true, 0);
	vc_conn := f_start_handler(refers(f_tc_emerg_call_and_lcs_loc_req_early_lchan_conn_fail), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* Attempt Complete Layer 3 without any MSC available (OS#4832) */
private function f_tc_no_msc(charstring id) runs on MSC_ConnHdlr {
	f_MscConnHdlr_init(g_pars.media_nr, "127.0.0.2", "127.0.0.3", FR_AMR);

	/* Also disable attach for the single connected MSC */
	f_vty_msc_allow_attach(BSCVTY, { false });

	var octetstring l3_enc := enc_PDU_ML3_MS_NW(valueof(ts_LU_REQ(LU_Type_IMSI_Attach, valueof(ts_MI_IMSI_LV('001010000100001'H)), '00F110'O) ));
	f_chan_est(g_pars.ra, l3_enc, g_pars.link_id, g_pars.fn);

	/* No MSC is found, expecting a proper release on RSL */
	interleave {
	[] RSL.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, decmatch tr_RRM_RR_RELEASE)) {
			f_logp(BSCVTY, "Got RSL RR Release");
		}
	[] RSL.receive(tr_RSL_DEACT_SACCH(g_chan_nr)) {
			f_logp(BSCVTY, "Got RSL Deact SACCH");
		}
	[] RSL.receive(tr_RSL_RF_CHAN_REL(g_chan_nr)) {
			f_logp(BSCVTY, "Got RSL RF Chan Rel, sending Rel Ack");
			RSL.send(ts_RSL_RF_CHAN_REL_ACK(g_chan_nr));
			f_rslem_unregister(0, g_chan_nr);
		}
	}
	setverdict(pass);
}
testcase TC_no_msc() runs on test_CT {

	f_init(1, true);
	f_sleep(1.0);
	var MSC_ConnHdlr vc_conn;
	var TestHdlrParams pars := f_gen_test_hdlr_pars();

	f_ctrs_bsc_init(counternames_bsc_mscpool);

	vc_conn := f_start_handler(refers(f_tc_no_msc), pars);
	vc_conn.done;

	f_ctrs_bsc_add("mscpool:subscr:no_msc");
	f_ctrs_bsc_verify();
	f_shutdown_helper();
}

/* Dyn PDCH todo:
   * activate OSMO as TCH/F
   * activate OSMO as TCH/H
   * does the BSC-located PCU socket get the updated INFO?
   * what if no PCU is connected at the time?
   * is the info correct on delayed PCU (re)connect?
 */

private function f_TC_refuse_mode_modif_to_vamos(charstring id) runs on MSC_ConnHdlr {
	var PDU_BSSAP ass_cmd := f_gen_ass_req(g_pars.use_osmux);
	var template PDU_BSSAP exp_compl := f_gen_exp_compl(g_pars.use_osmux);

	/* puzzle together the ASSIGNMENT REQ for given codec[s] */
	if (mp_bssap_cfg[0].transport == BSSAP_TRANSPORT_AoIP) {
		ass_cmd.pdu.bssmap.assignmentRequest.codecList := g_pars.ass_codec_list;
		exp_compl.pdu.bssmap.assignmentComplete.speechCodec.codecElements[0] :=
								g_pars.ass_codec_list.codecElements[0];
		if (isvalue(g_pars.expect_mr_s0_s7)) {
			exp_compl.pdu.bssmap.assignmentComplete.speechCodec.codecElements[0].s0_7 :=
								g_pars.expect_mr_s0_s7;
		}
	}
	ass_cmd.pdu.bssmap.assignmentRequest.channelType :=
				f_BSSMAP_chtype_from_codec(g_pars.ass_codec_list.codecElements[0]);
	log("expecting ASS COMPL like this: ", exp_compl);

	f_establish_fully(ass_cmd, exp_compl);

	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 1 sub-slot 0 modify vamos tsc 2 3");

	var RSL_Message rsl;

	timer T := 5.0;
	T.start;
	alt {
	[] RSL.receive(tr_RSL_DATA_REQ(g_chan_nr)) -> value rsl {
		var PDU_ML3_NW_MS l3 := dec_PDU_ML3_NW_MS(rsl.ies[2].body.l3_info.payload);
		log("Rx L3 from net: ", l3);
		if (ischosen(l3.msgs.rrm.channelModeModify)) {
			setverdict(fail, "Mode Modify to VAMOS succeeded even though BTS does not support VAMOS");
			mtc.stop;
		}
		}
	[] RSL.receive(tr_RSL_MODE_MODIFY_REQ(g_chan_nr, ?)) -> value rsl {
		setverdict(fail, "Mode Modify to VAMOS succeeded even though BTS does not support VAMOS");
		mtc.stop;
		}
	[] T.timeout {
		/* The BTS does not exhibit BTS_FEAT_VAMOS, so no VAMOS related Mode Modify should happen. */
		setverdict(pass);
		}
	}
	T.stop;

	f_perform_clear();
}

/* The BSC does *not* indicate BTS_FEAT_VAMOS; make sure that a channel Mode Modify to VAMOS mode is refused by
 * osmo-bsc. */
testcase TC_refuse_mode_modif_to_vamos() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));
	vc_conn := f_start_handler(refers(f_TC_refuse_mode_modif_to_vamos), pars);
	vc_conn.done;
	f_shutdown_helper();
}

/* The BSC does *not* indicate BTS_FEAT_VAMOS; make sure that a channel activation to VAMOS mode is refused by osmo-bsc.
 */
testcase TC_refuse_chan_act_to_vamos() runs on test_CT {
	f_init_vty();

	f_init(1, false);
	f_sleep(1.0);

	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot 1 sub-slot 0 activate-vamos fr");

	var ASP_RSL_Unitdata rx_rsl_ud;
	timer T := 5.0;

	T.start;
	alt {
	[] IPA_RSL[0][0].receive(tr_ASP_RSL_UD(?, IPAC_PROTO_RSL_TRX0)) -> value rx_rsl_ud {
		if (rx_rsl_ud.rsl.msg_type == RSL_MT_CHAN_ACTIV) {
			T.stop;
			setverdict(fail, "CHANnel ACTivate in VAMOS mode succeeded even though BTS does not support VAMOS");
			mtc.stop;
		}
		repeat;
		}
	[] T.timeout {
		/* The BTS does not exhibit BTS_FEAT_VAMOS, so no VAMOS related CHANnel ACTivate should happen. */
		setverdict(pass);
		}
	}
}

private function f_TC_reassignment_codec(charstring id) runs on MSC_ConnHdlr {
	/* First fully set up a speech lchan */
	f_assignment_codec(id, do_perform_clear := false);

	/* Trigger re-assignment to another lchan */
	var AssignmentState assignment_st := valueof(ts_AssignmentStateInit);

	/* Re-Assignment should tell the MGW endpoint the new lchan's RTP address and port, so expecting to see exactly
	 * one MDCX on MGCP. */
	g_media.mgcp_conn[0].mdcx_seen_exp := g_media.mgcp_conn[0].mdcx_seen_exp + 1;

	/* The new lchan will see all-new IPAC_CRCX and IPAC_MDCX messages telling the BTS the same RTP address and port
	 * as the old lchan used. */
	g_media.bts.ipa_crcx_seen := false;
	g_media.bts.ipa_mdcx_seen := false;

	/* Send different BTS side RTP port number for the new lchan */
	g_media.bts.bts.port_nr := 4223;

	f_rslem_register(0, valueof(ts_RslChanNr_Bm(2))); /* <-- FIXME: can we somehow infer the timeslot that will be used? */

	/* Trigger re-assignment. */
	f_vty_transceive(BSCVTY, "bts 0 trx 0 timeslot " & int2str(g_chan_nr.tn) & " sub-slot 0 assignment");

	timer T := 5.0;
	T.start;
	alt {
	[] as_assignment(assignment_st);
	[] as_Media();
	[] T.timeout {
			break;
		}
	}

	if (not assignment_st.assignment_done) {
		setverdict(fail, "Assignment did not complete");
		mtc.stop;
	}

	f_check_mgcp_expectations()
	setverdict(pass);

	f_sleep(2.0);
	log("show lchan summary: ", f_vty_transceive_ret(BSCVTY, "show lchan summary"));

	/* Instruct BSC to clear channel */
	var BssmapCause cause := 0;
	BSSAP.send(ts_BSSMAP_ClearCommand(cause));
	interleave {
	[] RSL.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, decmatch tr_RRM_RR_RELEASE)) {}
	[] RSL.receive(tr_RSL_DEACT_SACCH(g_chan_nr)) {}
	[] RSL.receive(tr_RSL_RF_CHAN_REL(g_chan_nr)) {
			RSL.send(ts_RSL_RF_CHAN_REL_ACK(g_chan_nr));
			f_rslem_unregister(0, g_chan_nr);
		}
	[] BSSAP.receive(tr_BSSMAP_ClearComplete) {
			BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);
		}
	}
	f_expect_dlcx_conns();

	f_sleep(0.5);
}

testcase TC_reassignment_fr() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	f_ctrs_bsc_and_bts_handover_init();

	pars.ass_codec_list := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));
	vc_conn := f_start_handler(refers(f_TC_reassignment_codec), pars);
	vc_conn.done;

	/* from f_establish_fully() */
	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");
	/* from re-assignment */
	f_ctrs_bsc_and_bts_add(0, "assignment:attempted");
	f_ctrs_bsc_and_bts_add(0, "assignment:completed");
	f_ctrs_bsc_and_bts_verify();
	f_shutdown_helper();
}

const charstring REEST_LOST_CONNECTION := "REEST_LOST_CONNECTION";
const charstring REEST_CLEAR := "REEST_CLEAR";
const charstring REEST_CLEAR_DONE := "REEST_CLEAR_DONE";

/* CM Re-Establishment, 3GPP TS 24.008 4.5.1.6.
 * The MS <-> BTS loses radio connection, MS shows up on second BTS and asks for CM Re-Establishment.
 * BSC should establish a separate A conn for the same MS, the original A conn is then cleared by
 * the MSC as the CM Re-Establishment is handled.
 *
 * MS      bts0       bts1     bsc    msc  test-component
 *  |<----->|<----------------->|<-0-->|   _1  Establish channel on bts 0
 *  |                                  |   _1  wait a bit, to settle down
 *  |<-x x--|                          |   _1  "lose connection"
 *  |                                  |   REEST_LOST_CONNECTION
 *  |----------------->|------->|--1-->|   _2  new A-conn: Chan Rqd, Imm Ass, Compl L3 with CM Re-Establishment Req
 *  |                                  |   REEST_CLEAR
 *  |                           |<-0---|   _1  Clear Command on first A-conn
 *  |                           |--0-->|   _1  Clear Complete
 *  |       |<----------------->|      |   _1  Release first channel
 *  |                                  |   REEST_CLEAR_DONE
 *  |<-----------------|<-------|<-1---|   _2  Chan Activ, Assignment Command
 *  |<-----------------|<-------|<-1---|   _2  Clear Command, Release
 *
 */
private function f_tc_cm_reestablishment_1(charstring id) runs on MSC_ConnHdlr {
	var template PDU_BSSAP exp_compl := f_gen_exp_compl();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();

	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));

	f_establish_fully(ass_cmd, exp_compl);

	/* The original channel loses connection, MS attemts CM Re-Establishment on another cell, see
	 * f_tc_cm_reestablishment_2(). This established channel stays active until MSC sends a Clear Command. The time
	 * when exactly that happens is determined by f_tc_cm_reestablishment_2(). */
	f_sleep(2.0);
	COORD.send(REEST_LOST_CONNECTION);

	alt {
	[] COORD.receive(REEST_CLEAR);
	[] RSL.receive(tr_RSL_DEACT_SACCH(g_chan_nr)) {
			setverdict(fail, "Unexpected channel release");
			mtc.stop;
		}
	[] RSL.receive(tr_RSL_RF_CHAN_REL(g_chan_nr)) {
			setverdict(fail, "Unexpected channel release");
			mtc.stop;
		}
	}
	f_perform_clear()
	f_create_mgcp_delete_ep(g_media.mgcp_ep);
	COORD.send(REEST_CLEAR_DONE);
}

private function f_tc_cm_reestablishment_2(charstring id) runs on MSC_ConnHdlr {
	f_MscConnHdlr_init(g_pars.media_nr, host_bts, host_mgw_mgcp, FR_AMR);

	/* The MS lost the connection on the first channel, now establishes another one */
	COORD.receive(REEST_LOST_CONNECTION);

	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
	var PDU_ML3_MS_NW l3_info := valueof(ts_CM_REESTABL_REQ(mi));
	var octetstring l3_enc := enc_PDU_ML3_MS_NW(l3_info);

	f_create_bssmap_exp(l3_enc);
	RSL_Emulation.f_chan_est(g_pars.ra, l3_enc, g_pars.link_id, g_pars.fn, rsl_pt := RSL1, rsl_proc_pt := RSL1_PROC);
	BSSAP.receive(tr_BSSMAP_ComplL3(l3_enc));

	/* MSC got the CM Re-Establishment request and first off clears the previous conn. */
	COORD.send(REEST_CLEAR);
	COORD.receive(REEST_CLEAR_DONE);

	f_sleep(2.0);

	/* Answer the CM Re-Establishment with an Assignment Command. */
	var template PDU_BSSAP expect_assignment_compl := f_gen_exp_compl();
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));

	var AssignmentState st := valueof(ts_AssignmentStateInit);
	st.voice_call := true;
	st.is_assignment := true;

	var ExpectCriteria mgcpcrit := {
		connid := omit,
		endpoint := omit,
		transid := omit
	};
	f_create_mgcp_expect(mgcpcrit);

	f_rslem_dchan_queue_enable(RSL1_PROC);

	BSSAP.send(ass_cmd);

	var PDU_BSSAP bssap;

	alt {
	[] as_assignment(st, rsl_pt := RSL1, rsl_proc_pt := RSL1_PROC);
	[] as_Media_ipacc(RSL1, RSL2);
	[] as_Media_mgw();
	[st.assignment_done] BSSAP.receive(expect_assignment_compl) {
			break;
		}
	}

	f_sleep(3.0);

	f_logp(BSCVTY, "f_tc_cm_reestablishment_2 clearing");
	f_perform_clear(RSL1, RSL1_PROC);
}

testcase TC_cm_reestablishment() runs on test_CT {
	var TestHdlrParams pars1 := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn1;

	var TestHdlrParams pars2 := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn2;
	pars2.imsi := pars1.imsi;
	pars2.media_nr := 2;
	pars2.expect_tsc := c_BtsParams[1].tsc;

	f_init(2, true, guard_timeout := 40.0);
	f_sleep(1.0);

	vc_conn1 := f_start_handler_create(pars1);
	vc_conn2 := f_start_handler_create(pars2);
	connect(vc_conn1:COORD, vc_conn2:COORD);
	f_start_handler_run(vc_conn1, refers(f_tc_cm_reestablishment_1), pars1);
	f_start_handler_run(vc_conn2, refers(f_tc_cm_reestablishment_2), pars2);
	vc_conn1.done;
	vc_conn2.done;

	f_shutdown_helper();
}

function f_exp_ipa_rx_nonfatal(template (present) RSL_Message t_rx,
			       boolean ignore_other_rx := true,
			       BtsTrxIdx idx := {0, 0},
			       float Tval := 2.0)
runs on test_CT return template (omit) RSL_Message {
	var ASP_RSL_Unitdata rx_rsl_ud;
	timer T := Tval;

	T.start;
	alt {
	[] IPA_RSL[idx.bts][idx.trx].receive(tr_ASP_RSL_UD(t_rx, ?)) -> value rx_rsl_ud {
		T.stop;
		}
	[ignore_other_rx] IPA_RSL[idx.bts][idx.trx].receive { repeat; }
	[not ignore_other_rx] IPA_RSL[idx.bts][idx.trx].receive {
			log("f_exp_ipa_rx_nonfatal(): Got different message than ", t_rx);
			T.stop;
			return omit;
		}
	[] T.timeout {
			return omit;
		}
	}
	return rx_rsl_ud.rsl;
}

private function f_vty_set_imm_ass(TELNETasp_PT pt, BtsNr bts_nr := 0, charstring imm_ass_setting := "post-chan-ack") {
	f_vty_enter_cfg_bts(pt, bts_nr);
	f_vty_transceive(pt, "immediate-assignment " & imm_ass_setting);
	f_vty_transceive(pt, "exit");
	f_vty_transceive(pt, "exit");
	f_vty_transceive(pt, "exit");
}

private function f_verify_imm_ass(RSL_Message imm_ass, template uint8_t ra := ?, template GsmFrameNumber fn := ?,
				  template (present) RslChannelNr chan_nr := ?,
				  template (present) uint12_t arfcn := ?,
				  template (present) uint3_t tsc := ?)
{
	var RSL_IE_Body full_imm_ass_info;
	if (not f_rsl_find_ie(imm_ass, RSL_IE_FULL_IMM_ASS_INFO, full_imm_ass_info)) {
		setverdict(fail, "RSL Full Immediate Assign Info IE is absent");
		mtc.stop;
	}

	var GsmRrMessage rr_imm_ass := dec_GsmRrMessage(full_imm_ass_info.full_imm_ass_info.payload);
	var template GsmRrMessage expect_imm_ass := tr_IMM_ASS(ra := ra,
							       fn := fn,
							       ch_desc := tr_ChanDescH0(chan_nr, arfcn, tsc),
							       page_mode := ?);
	if (not match(rr_imm_ass, expect_imm_ass)) {
		log("Error: expected ", expect_imm_ass, " got ", rr_imm_ass);
		setverdict(fail, "Failed to match Immediate Assignment");
		mtc.stop;
	}
}

testcase TC_imm_ass_post_chan_ack() runs on test_CT {
	var RSL_Message chan_act;
	var RSL_Message imm_ass;

	f_init(1, false);
	f_sleep(1.0);

	/* (should be the default anyway, just to make things clear) */
	f_vty_set_imm_ass(BSCVTY, 0, "post-chan-ack");

	/* RA containing reason=LU */
	var GsmFrameNumber fn := 2342;
	var uint8_t ra := 2;
	f_ipa_tx(ts_RSL_CHAN_RQD(int2oct(ra, 1), fn));

	chan_act := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));

	/* First send the Chan Act ACK */
	var RslChannelNr chan_nr := chan_act.ies[0].body.chan_nr;
	var DchanTuple dt := {-, chan_nr, {0, 0}};
	var RSL_IE_Body chan_ident_ie;
	if (not f_rsl_find_ie(chan_act, RSL_IE_CHAN_IDENT, chan_ident_ie)) {
		setverdict(fail, "RSL Channel Identification IE is absent");
		mtc.stop;
	}

	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, fn + 10));

	/* Then expect the Immediate Assignment, after we ACKed the chan act */
	imm_ass := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0));

	f_verify_imm_ass(imm_ass, ra, fn, chan_nr, chan_ident_ie.chan_ident.ch_desc.v.arfcn,
			 chan_ident_ie.chan_ident.ch_desc.v.tsc);

	/* Check that the lchan is working */
	var octetstring l3 := '00010203040506'O;
	f_ipa_tx(ts_RSL_EST_IND(chan_nr, valueof(ts_RslLinkID_DCCH(0)), l3));

	var BSSAP_N_CONNECT_ind rx_c_ind;
	BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) -> value rx_c_ind;
	dt.sccp_conn_id := rx_c_ind.connectionId;
	BSSAP.send(ts_BSSAP_CONNECT_res(rx_c_ind.connectionId));

	f_sleep(1.0);
	f_perform_clear_test_ct(dt);
	f_shutdown_helper();
}

testcase TC_imm_ass_pre_chan_ack() runs on test_CT {
	var RSL_Message chan_act;
	var RSL_Message imm_ass;

	f_init(1, false);
	f_sleep(1.0);

	f_vty_set_imm_ass(BSCVTY, 0, "pre-chan-ack");

	/* RA containing reason=LU */
	var GsmFrameNumber fn := 2342;
	var uint8_t ra := 2;
	f_ipa_tx(ts_RSL_CHAN_RQD(int2oct(ra, 1), fn));

	chan_act := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));
	var RslChannelNr chan_nr := chan_act.ies[0].body.chan_nr;
	var DchanTuple dt := {-, chan_nr, {0, 0}};
	var RSL_IE_Body chan_ident_ie;
	if (not f_rsl_find_ie(chan_act, RSL_IE_CHAN_IDENT, chan_ident_ie)) {
		setverdict(fail, "RSL Channel Identification IE is absent");
		mtc.stop;
	}

	/* (set bts 0 cfg back to default) */
	f_vty_set_imm_ass(BSCVTY);

	/* *FIRST* expect the Immediate Assignment, before we ACK the chan act */
	imm_ass := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0));
	f_verify_imm_ass(imm_ass, ra, fn, chan_nr, chan_ident_ie.chan_ident.ch_desc.v.arfcn,
			 chan_ident_ie.chan_ident.ch_desc.v.tsc);

	/* Only now send the Chan Act ACK */
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, fn+10));

	/* Check that the lchan is working */
	var octetstring l3 := '00010203040506'O;
	f_ipa_tx(ts_RSL_EST_IND(chan_nr, valueof(ts_RslLinkID_DCCH(0)), l3));

	var BSSAP_N_CONNECT_ind rx_c_ind;
	BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) -> value rx_c_ind;
	dt.sccp_conn_id := rx_c_ind.connectionId;
	BSSAP.send(ts_BSSAP_CONNECT_res(rx_c_ind.connectionId));

	f_sleep(1.0);
	f_perform_clear_test_ct(dt);
	f_shutdown_helper();
}

testcase TC_imm_ass_pre_ts_ack() runs on test_CT {
	var RSL_Message chan_act;
	var RSL_Message imm_ass;

	f_init(1, false);
	f_sleep(1.0);

	f_vty_set_imm_ass(BSCVTY, 0, "pre-ts-ack");

	/* RA containing reason=LU */
	var GsmFrameNumber fn := 2342;
	var uint8_t ra := 2;
	f_ipa_tx(ts_RSL_CHAN_RQD(int2oct(ra, 1), fn));

	chan_act := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));
	var RslChannelNr chan_nr := chan_act.ies[0].body.chan_nr;
	var DchanTuple dt := {-, chan_nr, {0, 0}};
	var RSL_IE_Body chan_ident_ie;
	if (not f_rsl_find_ie(chan_act, RSL_IE_CHAN_IDENT, chan_ident_ie)) {
		setverdict(fail, "RSL Channel Identification IE is absent");
		mtc.stop;
	}

	/* (set bts 0 cfg back to default) */
	f_vty_set_imm_ass(BSCVTY);

	/* *FIRST* expect the Immediate Assignment, before we ACK the chan act */
	imm_ass := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0));
	f_verify_imm_ass(imm_ass, ra, fn, chan_nr, chan_ident_ie.chan_ident.ch_desc.v.arfcn,
			 chan_ident_ie.chan_ident.ch_desc.v.tsc);

	/* Only now send the Chan Act ACK */
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, fn+10));

	/* Check that the lchan is working */
	var octetstring l3 := '00010203040506'O;
	f_ipa_tx(ts_RSL_EST_IND(chan_nr, valueof(ts_RslLinkID_DCCH(0)), l3));

	var BSSAP_N_CONNECT_ind rx_c_ind;
	BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) -> value rx_c_ind;
	dt.sccp_conn_id := rx_c_ind.connectionId;
	BSSAP.send(ts_BSSAP_CONNECT_res(rx_c_ind.connectionId));

	f_sleep(1.0);
	f_perform_clear_test_ct(dt);
	f_shutdown_helper();
}

testcase TC_imm_ass_pre_chan_ack_dyn_ts() runs on test_CT {
	/* change Timeslot 6 before f_init() starts RSL */
	f_init_vty();
	f_ts_set_chcomb(0, 0, 6, "TCH/F_TCH/H_PDCH");
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1, false);
	f_sleep(1.0);

	var RslChannelNr chan_nr := valueof(t_RslChanNr_PDCH(6));
	/* The BSC will activate the dynamic PDCH by default, so confirm that */
	f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(chan_nr));
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, 2323));

	/* clean up timeslot 6 config, will only take effect when the OML drops the next time */
	f_ts_set_chcomb(0, 0, 6, "PDCH");

	/* block all static timeslots so that the dyn TS will be used */
	f_disable_all_tch_f();
	f_disable_all_tch_h();
	f_disable_all_sdcch();

	var RSL_Message chan_act;
	var RSL_Message imm_ass;

	f_vty_set_imm_ass(BSCVTY, 0, "pre-chan-ack");

	/* RA containing reason=LU */
	var GsmFrameNumber fn := 2342;
	var uint8_t ra := 2;
	f_ipa_tx(ts_RSL_CHAN_RQD(int2oct(ra, 1), fn));

	/* Expect the dyn TS to deactivate PDCH first */
	f_exp_ipa_rx(tr_RSL_RF_CHAN_REL(chan_nr));
	f_ipa_tx(ts_RSL_RF_CHAN_REL_ACK(chan_nr));

	/* Now activation as SDCCH8 */
	chan_nr := valueof(t_RslChanNr_SDCCH8(tn := 6, sub_slot := 0));
	var DchanTuple dt := {-, chan_nr, {0, 0}};

	chan_act := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));
	var RSL_IE_Body chan_ident_ie;
	if (not f_rsl_find_ie(chan_act, RSL_IE_CHAN_IDENT, chan_ident_ie)) {
		setverdict(fail, "RSL Channel Identification IE is absent");
		mtc.stop;
	}

	/* *FIRST* expect the Immediate Assignment, before we ACK the chan act */
	imm_ass := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0));
	f_verify_imm_ass(imm_ass, ra, fn, chan_nr, chan_ident_ie.chan_ident.ch_desc.v.arfcn,
			 chan_ident_ie.chan_ident.ch_desc.v.tsc);

	/* Only now send the Chan Act ACK */
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, fn+10));

	/* Check that the lchan is working */
	var octetstring l3 := '00010203040506'O;
	f_ipa_tx(ts_RSL_EST_IND(chan_nr, valueof(ts_RslLinkID_DCCH(0)), l3));

	var BSSAP_N_CONNECT_ind rx_c_ind;
	BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) -> value rx_c_ind;
	dt.sccp_conn_id := rx_c_ind.connectionId;
	BSSAP.send(ts_BSSAP_CONNECT_res(rx_c_ind.connectionId));

	/* (set bts 0 cfg back to default) */
	f_vty_set_imm_ass(BSCVTY);

	f_sleep(1.0);
	f_perform_clear_test_ct(dt);
	f_shutdown_helper();
}

testcase TC_imm_ass_pre_ts_ack_dyn_ts() runs on test_CT {
	/* change Timeslot 6 before f_init() starts RSL */
	f_init_vty();
	f_ts_set_chcomb(0, 0, 6, "TCH/F_TCH/H_PDCH");
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");

	f_init(1, false);
	f_sleep(1.0);

	var RslChannelNr chan_nr := valueof(t_RslChanNr_PDCH(6));
	/* The BSC will activate the dynamic PDCH by default, so confirm that */
	f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(chan_nr));
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, 2323));

	/* clean up timeslot 6 config, will only take effect when the OML drops the next time */
	f_ts_set_chcomb(0, 0, 6, "PDCH");

	/* block all static timeslots so that the dyn TS will be used */
	f_disable_all_tch_f();
	f_disable_all_tch_h();
	f_disable_all_sdcch();

	var RSL_Message chan_act;
	var RSL_Message imm_ass;

	f_vty_set_imm_ass(BSCVTY, 0, "pre-ts-ack");

	/* RA containing reason=LU */
	var GsmFrameNumber fn := 2342;
	var uint8_t ra := 2;
	f_ipa_tx(ts_RSL_CHAN_RQD(int2oct(ra, 1), fn));

	/* Expect the dyn TS to deactivate PDCH first */
	f_exp_ipa_rx(tr_RSL_RF_CHAN_REL(chan_nr));

	/* And already the Immediate Assignment even before the PDCH Deact ACK */
	imm_ass := f_exp_ipa_rx(tr_RSL_IMM_ASSIGN(0));

	/* continue the Osmo style PDCH Deact (usual chan rel) */
	f_ipa_tx(ts_RSL_RF_CHAN_REL_ACK(chan_nr));

	/* Now activation as SDCCH8 */
	chan_nr := valueof(t_RslChanNr_SDCCH8(tn := 6, sub_slot := 0));
	var DchanTuple dt := {-, chan_nr, {0, 0}};

	chan_act := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));
	var RSL_IE_Body chan_ident_ie;
	if (not f_rsl_find_ie(chan_act, RSL_IE_CHAN_IDENT, chan_ident_ie)) {
		setverdict(fail, "RSL Channel Identification IE is absent");
		mtc.stop;
	}
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, fn+10));

	f_verify_imm_ass(imm_ass, ra, fn, chan_nr, chan_ident_ie.chan_ident.ch_desc.v.arfcn,
			 chan_ident_ie.chan_ident.ch_desc.v.tsc);

	/* Check that the lchan is working */
	var octetstring l3 := '00010203040506'O;
	f_ipa_tx(ts_RSL_EST_IND(chan_nr, valueof(ts_RslLinkID_DCCH(0)), l3));

	var BSSAP_N_CONNECT_ind rx_c_ind;
	BSSAP.receive(tr_BSSAP_CONNECT_ind(?, ?, tr_BSSMAP_ComplL3(l3))) -> value rx_c_ind;
	dt.sccp_conn_id := rx_c_ind.connectionId;
	BSSAP.send(ts_BSSAP_CONNECT_res(rx_c_ind.connectionId));

	/* (set bts 0 cfg back to default) */
	f_vty_set_imm_ass(BSCVTY);

	f_sleep(1.0);
	f_perform_clear_test_ct(dt);
	f_shutdown_helper();
}

/* GET and SET the bts.N.trx.M.rf_locked CTRL variable */
testcase TC_ctrl_trx_rf_locked() runs on test_CT {
	var MSC_ConnHdlr vc_conn;

	f_init(nr_bts := 2, handler_mode := true, nr_msc := 1);
	f_sleep(1.0);

	/* BTS 0, 1, 2 are OML unlocked, only BTS 0, 1 are actually connected to RSL. */
	f_ctrl_get_exp(IPA_CTRL, "rf_states",
		       "0,0,operational,unlocked,on,rsl-up;" &
		       "1,0,operational,unlocked,on,rsl-up;" &
		       "2,0,operational,unlocked,on,rsl-down;" &
		       "2,1,operational,unlocked,on,rsl-down;" &
		       "2,2,operational,unlocked,on,rsl-down;" &
		       "2,3,operational,unlocked,on,rsl-down;" &
		       "3,0,inoperational,locked,on,rsl-down;");

	f_logp(BSCVTY, "TC_ctrl_trx_rf_locked: lock BTS 1 TRX 0");
	f_ctrl_set(IPA_CTRL, "bts.1.trx.0.rf_locked", "1");
	/* give it a moment to settle the FSM status */
	f_sleep(1.0);

	/* Now BTS 1 TRX 0 should reflect "locked". Note the RF policy stays "on", because this is still handled
	 * globally in osmo-bsc. Probably after sending "rf_locked 1" for a TRX, that TRX should reflect an RF policy
	 * of "off"? But that's for a future patch if at all. */
	f_ctrl_get_exp(IPA_CTRL, "rf_states",
		       "0,0,operational,unlocked,on,rsl-up;" &
		       "1,0,operational,locked,on,rsl-up;" &
		       "2,0,operational,unlocked,on,rsl-down;" &
		       "2,1,operational,unlocked,on,rsl-down;" &
		       "2,2,operational,unlocked,on,rsl-down;" &
		       "2,3,operational,unlocked,on,rsl-down;" &
		       "3,0,inoperational,locked,on,rsl-down;");

	f_logp(BSCVTY, "TC_ctrl_trx_rf_locked: lock the already locked TRX, nothing should change");
	f_ctrl_set(IPA_CTRL, "bts.1.trx.0.rf_locked", "1");
	f_sleep(1.0);
	f_ctrl_get_exp(IPA_CTRL, "rf_states",
		       "0,0,operational,unlocked,on,rsl-up;" &
		       "1,0,operational,locked,on,rsl-up;" &
		       "2,0,operational,unlocked,on,rsl-down;" &
		       "2,1,operational,unlocked,on,rsl-down;" &
		       "2,2,operational,unlocked,on,rsl-down;" &
		       "2,3,operational,unlocked,on,rsl-down;" &
		       "3,0,inoperational,locked,on,rsl-down;");

	f_logp(BSCVTY, "TC_ctrl_trx_rf_locked: unlock BTS 1 TRX 0");
	f_ctrl_set(IPA_CTRL, "bts.1.trx.0.rf_locked", "0");
	f_sleep(1.0);
	f_ctrl_get_exp(IPA_CTRL, "rf_states",
		       "0,0,operational,unlocked,on,rsl-up;" &
		       "1,0,operational,unlocked,on,rsl-up;" &
		       "2,0,operational,unlocked,on,rsl-down;" &
		       "2,1,operational,unlocked,on,rsl-down;" &
		       "2,2,operational,unlocked,on,rsl-down;" &
		       "2,3,operational,unlocked,on,rsl-down;" &
		       "3,0,inoperational,locked,on,rsl-down;");

	f_logp(BSCVTY, "TC_ctrl_trx_rf_locked: unlock an already unlocked TRX, nothing should change");
	f_ctrl_set(IPA_CTRL, "bts.0.trx.0.rf_locked", "0");
	f_sleep(1.0);
	f_ctrl_get_exp(IPA_CTRL, "rf_states",
		       "0,0,operational,unlocked,on,rsl-up;" &
		       "1,0,operational,unlocked,on,rsl-up;" &
		       "2,0,operational,unlocked,on,rsl-down;" &
		       "2,1,operational,unlocked,on,rsl-down;" &
		       "2,2,operational,unlocked,on,rsl-down;" &
		       "2,3,operational,unlocked,on,rsl-down;" &
		       "3,0,inoperational,locked,on,rsl-down;");

	f_logp(BSCVTY, "TC_ctrl_trx_rf_locked: unlock an inoperational TRX");
	f_ctrl_set(IPA_CTRL, "bts.3.trx.0.rf_locked", "0");
	f_sleep(1.0);
	f_ctrl_get_exp(IPA_CTRL, "rf_states",
		       "0,0,operational,unlocked,on,rsl-up;" &
		       "1,0,operational,unlocked,on,rsl-up;" &
		       "2,0,operational,unlocked,on,rsl-down;" &
		       "2,1,operational,unlocked,on,rsl-down;" &
		       "2,2,operational,unlocked,on,rsl-down;" &
		       "2,3,operational,unlocked,on,rsl-down;" &
		       "3,0,inoperational,locked,on,rsl-down;");

	f_shutdown_helper();
}

const CounterNameVals counternames_cm_serv_rej := {
	{ "cm_serv_rej", 0 },
	{ "cm_serv_rej:imsi_unknown_in_hlr", 0 },
	{ "cm_serv_rej:illegal_ms", 0 },
	{ "cm_serv_rej:imsi_unknown_in_vlr", 0 },
	{ "cm_serv_rej:imei_not_accepted", 0 },
	{ "cm_serv_rej:illegal_me", 0 },
	{ "cm_serv_rej:plmn_not_allowed", 0 },
	{ "cm_serv_rej:loc_not_allowed", 0 },
	{ "cm_serv_rej:roaming_not_allowed", 0 },
	{ "cm_serv_rej:network_failure", 0 },
	{ "cm_serv_rej:synch_failure", 0 },
	{ "cm_serv_rej:congestion", 0 },
	{ "cm_serv_rej:srv_opt_not_supported", 0 },
	{ "cm_serv_rej:rqd_srv_opt_not_supported", 0 },
	{ "cm_serv_rej:srv_opt_tmp_out_of_order", 0 },
	{ "cm_serv_rej:call_can_not_be_identified", 0 },
	{ "cm_serv_rej:incorrect_message", 0 },
	{ "cm_serv_rej:invalid_mandantory_inf", 0 },
	{ "cm_serv_rej:msg_type_not_implemented", 0 },
	{ "cm_serv_rej:msg_type_not_compatible", 0 },
	{ "cm_serv_rej:inf_eleme_not_implemented", 0 },
	{ "cm_serv_rej:condtional_ie_error", 0 },
	{ "cm_serv_rej:msg_not_compatible", 0 },
	{ "cm_serv_rej:protocol_error", 0 },
	{ "cm_serv_rej:retry_in_new_cell", 0 }
};

private function f_TC_cm_serv_rej(charstring id) runs on MSC_ConnHdlr
{
	f_create_chan_and_exp();
	/* we should now have a COMPL_L3 at the MSC */
	BSSAP.send(ts_PDU_DTAP_MT(ts_CM_SERV_REJ('02'O), '00'O));
	RSL.receive(tr_RSL_DATA_REQ(g_chan_nr, ?, decmatch tr_CM_SERV_REJ));
	f_perform_clear();
	f_sleep(1.0);
}
testcase TC_cm_serv_rej() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	f_ctrs_bts_init(1, counternames_cm_serv_rej);

	vc_conn := f_start_handler(refers(f_TC_cm_serv_rej), pars);
	vc_conn.done;

	f_ctrs_bts_add(0, "cm_serv_rej", 1);
	f_ctrs_bts_add(0, "cm_serv_rej:imsi_unknown_in_hlr", 1);
	f_ctrs_bts_verify();

	f_sleep(1.0);
	f_shutdown_helper();
}

/* Reproduce a segfault happening when the SDCCH (primary) lchan is lost in-between a TCH Channel Activ and its Channel
 * Activ Ack (SYS#5627). */
private function f_TC_lost_sdcch_during_assignment(charstring id) runs on MSC_ConnHdlr {
	var PDU_BSSAP ass_cmd := f_gen_ass_req();

	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));

	var BSSMAP_FIELD_CodecType codecType;
	codecType := valueof(ass_cmd.pdu.bssmap.assignmentRequest.codecList.codecElements[0].codecType);

	f_MscConnHdlr_init(g_pars.media_nr, host_bts, host_mgw_mgcp, codecType);

	/* First establish a signalling lchan */
	f_create_chan_and_exp();
	f_rslem_dchan_queue_enable();

	/* we should now have a COMPL_L3 at the MSC */

	f_create_mgcp_expect(ExpectCriteria:{omit,omit,omit});
	activate(as_Media_mgw(fail_on_dlcx := false));

	var RslChannelNr chan_nr := { u := { ch0 := RSL_CHAN_NR_Bm_ACCH }, tn := 1 };
	f_rslem_register(0, chan_nr);

	f_rslem_set_auto_chan_act_ack(RSL_PROC, false);
	BSSAP.send(ass_cmd);


	/* Wait for the Channel Activ for the TCH channel */
	var ASP_RSL_Unitdata rx_rsl_ud;
	RSL.receive(tr_ASP_RSL_UD(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV), sid := ?)) -> value rx_rsl_ud;

	/* make the original SDCCH disappear */
	RSL.send(ts_RSL_REL_IND(g_chan_nr, valueof(ts_RslLinkID_DCCH(0))));

	/* and ACK the TCH channel activation. This caused a segfault up to OsmoBSC 1.7.0 (SYS#5627) */
	RSL.send(ts_ASP_RSL_UD(ts_RSL_CHAN_ACT_ACK(chan_nr, 23), rx_rsl_ud.streamId));

	interleave {
	[] BSSAP.receive(tr_BSSMAP_AssignmentFail);
	[] BSSAP.receive(tr_BSSMAP_ClearRequest);
	}

	BSSAP.send(ts_BSSMAP_ClearCommand(0));
	BSSAP.receive(tr_BSSMAP_ClearComplete);
	BSSAP.send(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);

	var MgcpCommand mgcp;
	var MGCP_RecvFrom mrf;
	var template MgcpMessage msg_dlcx := { command := tr_DLCX };
	alt {
	[g_pars.aoip] MGCP.receive(tr_DLCX) -> value mgcp {
		MGCP.send(ts_DLCX_ACK2(mgcp.line.trans_id));
		}
	[not g_pars.aoip] MGCP_MULTI.receive(tr_MGCP_RecvFrom_any(msg_dlcx)) -> value mrf {
		MGCP_MULTI.send(t_MGCP_SendToMrf(mrf, MgcpMessage:{
			response := ts_DLCX_ACK2(mrf.msg.command.line.trans_id)
		}));
		}
	}

	f_sleep(0.5);
}
testcase TC_lost_sdcch_during_assignment() runs on test_CT {
	var TestHdlrParams pars := f_gen_test_hdlr_pars();
	var MSC_ConnHdlr vc_conn;

	f_init(1, true);
	f_sleep(1.0);

	vc_conn := f_start_handler(refers(f_TC_lost_sdcch_during_assignment), pars);
	vc_conn.done;

	f_shutdown_helper();
}

const CounterNameVals counternames_bsc_bts_all_available_allocated := {
	{ "all_allocated:sdcch", 0 },
	{ "all_allocated:static_sdcch", 0 },
	{ "all_allocated:tch", 0 },
	{ "all_allocated:static_tch", 0 }
}

private function f_all_allocated_expect_counter_change(charstring_list expect_changed) runs on test_CT
{
	/* Make sure counters settle first */
	f_sleep(1.0);

	/* Take a baseline of counters */
	f_ctrs_bsc_and_bts_init(1, counternames_bsc_bts_all_available_allocated);

	/* Elapse some time so that we see changes in counters, hopefully where expected */
	f_sleep(2.0);

	/* Get new counters */
	var charstring_list all_changed := {};
	all_changed := all_changed & f_counter_name_vals_get_changed_n(IPA_CTRL, "bsc", g_ctr_bsc);
	all_changed := all_changed & f_counter_name_vals_get_changed_n(IPA_CTRL, "bts", g_ctr_bts);

	/* Compare with expectations */
	var charstring_list all_expect_changed := {};
	for (var integer i := 0; i < lengthof(expect_changed); i := i + 1) {
		all_expect_changed := all_expect_changed & { "bsc.0." & expect_changed[i], "bts.0." & expect_changed[i] };
	}
	f_counter_name_vals_expect_changed_list(all_changed, all_expect_changed);
}

testcase TC_ratectr_all_available_allocated() runs on test_CT {
	var ASP_RSL_Unitdata rsl_ud;
	var integer i;
	var integer chreq_total, chreq_nochan;

	f_init(1, guard_timeout := 60.0);
	f_sleep(1.0);

	/* Exhaust all dedicated SDCCH lchans.
	/* GSM 44.018 Table 9.1.8.2:
	 * RA = '13'O -> Establishment cause = 0001xxxx (MS dual rate capable and asks for "SDCCH").
	 */
	var DchanTuples chan_cleanup := {};
	for (i := 0; i < NUM_SDCCH_PER_BTS; i := i+1) {
		chan_cleanup := chan_cleanup & { f_est_dchan('13'O, NUM_SDCCH_PER_BTS + i, '00010203040506'O) };
	}

	/* Since only bts 0 is connected, expecting all_allocated to become true for both bts 0 and the "global" bsc
	 * level.
	 * All SDCCH are now occupied. */
	f_all_allocated_expect_counter_change({"all_allocated:sdcch", "all_allocated:static_sdcch"});

	/* Also fill up all remaining (TCH) channels */
	for (i := 0; i < NUM_TCHF_PER_BTS + NUM_TCHH_PER_BTS; i := i+1) {
		chan_cleanup := chan_cleanup & { f_est_dchan('33'O, NUM_SDCCH_PER_BTS + i, '00010203040506'O) };
	}

	/* All TCH are now also occupied */
	f_all_allocated_expect_counter_change({"all_allocated:sdcch", "all_allocated:static_sdcch",
			"all_allocated:tch", "all_allocated:static_tch"});

	/* Clean up SDCCH lchans */
	for (i := 0; i < lengthof(chan_cleanup); i := i + 1) {
		f_perform_clear_test_ct(chan_cleanup[i]);
	}

	f_shutdown_helper();
}

testcase TC_ratectr_all_available_allocated_dyn() runs on test_CT {
	var ASP_RSL_Unitdata rsl_ud;
	var integer i;
	var integer chreq_total, chreq_nochan;

	f_init_vty();
	f_ts_set_chcomb(0, 0, 2, "TCH/F_TCH/H_PDCH");
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");
	/* Now we have 3 TCH/F, 1 OSMO_DYN, 1 TCH/H */

	f_init(1, guard_timeout := 60.0);
	f_sleep(1.0);

	/* The dyn TS wants to activate PDCH mode, ACK that. */
	var RslChannelNr chan_nr;
	chan_nr := valueof(t_RslChanNr_PDCH(2));
	f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(chan_nr));
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, 2342));

	/* Exhaust all dedicated SDCCH lchans.
	/* GSM 44.018 Table 9.1.8.2:
	 * RA = '13'O -> Establishment cause = 0001xxxx (MS dual rate capable and asks for "SDCCH").
	 */
	var DchanTuples chan_cleanup := {};
	for (i := 0; i < NUM_SDCCH_PER_BTS; i := i+1) {
		chan_cleanup := chan_cleanup & { f_est_dchan('13'O, NUM_SDCCH_PER_BTS + i, '00010203040506'O) };
	}

	/* The static SDCCH should now be occupied, while still 3x8 dynamic SDCCH potentially remain. So only
	 * all_allocated:static_sdcch is counted, all_allocated:sdcch remains zero. */
	f_all_allocated_expect_counter_change({"all_allocated:static_sdcch"});

	/* Request more SDCCH, hence convert the first dyn TS to SDCCH8.
	 * Will release them later, so remember all the DchanTuples. */
	var DchanTuples dyn_sddch := {};
	dyn_sddch := dyn_sddch & { f_est_dchan_dyn('33'O, NUM_SDCCH_PER_BTS + i, '00010203040506'O) };

	/* Also occupy the seven other SDCCH of the dyn TS */
	for (i := 0; i < 7; i := i+1) {
		dyn_sddch := dyn_sddch & { f_est_dchan('33'O, NUM_SDCCH_PER_BTS + i, '00010203040506'O) };
	}

	/* Now all dynamic SDCCH are also occupied, so for the first time all_allocated:sdcch will trigger... */
	f_all_allocated_expect_counter_change({"all_allocated:sdcch", "all_allocated:static_sdcch"});

	/* occupy the remaining TCH, three TCH/F and two TCH/H lchans */
	for (i := 0; i < 5; i := i+1) {
		chan_cleanup := chan_cleanup & { f_est_dchan('33'O, NUM_SDCCH_PER_BTS + i, '00010203040506'O) };
	}

	/* All TCH lchans are now also occupied, both static and dynamic */
	f_all_allocated_expect_counter_change({"all_allocated:sdcch", "all_allocated:static_sdcch",
			"all_allocated:tch", "all_allocated:static_tch"});

	/* Starting to release the dyn TS: as soon as the first SDCCH gets released, all_allocated:sdcch stops
	 * incrementing. */
	var BssmapCause cause := 0;
	var DchanTuple dt := dyn_sddch[0];
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(cause)));
	f_exp_chan_rel_and_clear(dt);

	/* one dyn TS SDCCH is free again, so only the static_sdcch should increment. For tch, both static and dynamic
	 * count as occupied, so those still both increment. */
	f_all_allocated_expect_counter_change({"all_allocated:static_sdcch",
			"all_allocated:tch", "all_allocated:static_tch"});

	/* Release the remaining SDCCH of the dyn TS, so it becomes available as TCH again */
	for (i := 1; i < lengthof(dyn_sddch); i := i+1) {
		dt := dyn_sddch[i];
		BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ts_BSSMAP_ClearCommand(cause)));
		f_exp_chan_rel_and_clear(dt);
	}

	/* All SDCCH on the dyn TS are released, the dyn TS wants to activate PDCH again */
	chan_nr := valueof(t_RslChanNr_PDCH(2));
	f_exp_ipa_rx(tr_RSL_CHAN_ACT_PDCH(chan_nr));
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(chan_nr, 2342));

	/* Now all channels are occupied except the dyn TS, so expecting only the static counters to increment */
	f_all_allocated_expect_counter_change({"all_allocated:static_sdcch", "all_allocated:static_tch"});

	/* Clean up SDCCH lchans */
	for (i := 0; i < lengthof(chan_cleanup); i := i + 1) {
		f_perform_clear_test_ct(chan_cleanup[i]);
	}

	/* clean up config */
	f_ts_reset_chcomb(0);

	f_shutdown_helper();
}

testcase TC_assignment_crcx_nack() runs on test_CT {
	f_init(1);

	/* HACK: we don't want to employ MGCP_Emulation here because:
	 * a) there is no way to talk to it from component test_CT;
	 * b) it does not allow us to send ts_MgcpResp_Err (fails). */
	vc_MGCP.stop;
	map(self:MGCP, system:MGCP);
	var Result res := MGCP_CodecPort_CtrlFunct.f_IPL4_connect(MGCP, mp_bsc_ip, 2727,
									mp_test_ip, 2427,
									-1, { udp := { } });
	if (not ispresent(res.connId)) {
		setverdict(fail, "Could not connect MGCP socket, check your configuration");
		mtc.stop;
	}

	/* Establish an SDCCH channel for signalling */
	var DchanTuple dt := f_est_dchan('4C'O, 23, '00000000'O);

	/* MSC sends an Assignment Request */
	var PDU_BSSAP ass_cmd := f_gen_ass_req();
	ass_cmd.pdu.bssmap.assignmentRequest.channelType := valueof(ts_BSSMAP_IE_ChannelType);
	ass_cmd.pdu.bssmap.assignmentRequest.codecList := valueof(ts_BSSMAP_IE_CodecList({ts_CodecFR}));
	BSSAP.send(ts_BSSAP_DATA_req(dt.sccp_conn_id, ass_cmd));

	/* BSC activates a TCH channel */
	var RSL_Message rsl_chan_act := f_exp_ipa_rx(tr_RSL_MsgTypeD(RSL_MT_CHAN_ACTIV));
	f_ipa_tx(ts_RSL_CHAN_ACT_ACK(rsl_chan_act.ies[0].body.chan_nr, 23 + 10));

	/* Send assignment complete over the new channel */
	var PDU_ML3_MS_NW l3_tx := valueof(ts_RRM_AssignmentComplete('00'O));
	f_ipa_tx(ts_RSL_EST_IND(rsl_chan_act.ies[0].body.chan_nr,
				valueof(ts_RslLinkID_DCCH(0)),
				enc_PDU_ML3_MS_NW(l3_tx)));

	var MGCP_RecvFrom mrf;
	MGCP.receive(MGCP_RecvFrom:?) -> value mrf;
	var MgcpCommand mgcp_cmd := mrf.msg.command;
	log("Rx MGCP command: ", mgcp_cmd);

	/* Respond with an error (code=540), osmo-bsc is expected to crash here */
	template MgcpResponse mgcp_resp := ts_MgcpResp_Err(mgcp_cmd.line.trans_id, "540");
	MGCP.send(t_MGCP_Send(res.connId, MgcpMessage:{ response := mgcp_resp }));

	f_perform_clear_test_ct(dt);
	f_shutdown_helper();
}


control {
	/* CTRL interface testing */
	execute( TC_ctrl_msc_connection_status() );
	execute( TC_ctrl_msc0_connection_status() );
	/* In SCCPlite tests, only one MSC is configured. These tests assume that three MSCs are configured, so only run
	 * these in the AoIP test suite. */
	if (mp_bssap_cfg[0].transport == BSSAP_TRANSPORT_AoIP) {
		execute( TC_stat_num_msc_connected_1() );
		execute( TC_stat_num_msc_connected_2() );
		execute( TC_stat_num_msc_connected_3() );
	}
	execute( TC_stat_num_bts_connected_1() );
	execute( TC_stat_num_bts_connected_2() );
	execute( TC_stat_num_bts_connected_3() );
	execute( TC_ctrl() );
	if (mp_bssap_cfg[0].transport == BSSAP_TRANSPORT_SCCPlite_SERVER) {
		execute( TC_ctrl_location() );
	}

	execute( TC_si_default() );
	execute( TC_si2quater_2_earfcns() );
	execute( TC_si2quater_3_earfcns() );
	execute( TC_si2quater_4_earfcns() );
	execute( TC_si2quater_5_earfcns() );
	execute( TC_si2quater_6_earfcns() );
	execute( TC_si2quater_12_earfcns() );
	execute( TC_si2quater_23_earfcns() );
	execute( TC_si2quater_32_earfcns() );
	execute( TC_si2quater_33_earfcns() );
	execute( TC_si2quater_42_earfcns() );
	execute( TC_si2quater_48_earfcns() );
	execute( TC_si2quater_49_earfcns() );
	execute( TC_si_acc_rotate() );
	execute( TC_si_acc_ramp_rotate() );

	/* RSL DCHAN Channel ACtivation / Deactivation */
	execute( TC_chan_act_noreply() );
	execute( TC_chan_act_counter() );
	execute( TC_chan_act_ack_noest() );
	execute( TC_chan_act_ack_noest_emerg() );
	execute( TC_chan_rqd_emerg_deny() );
	execute( TC_chan_act_ack_est_ind_noreply() );
	execute( TC_chan_act_ack_est_ind_refused() );
	execute( TC_chan_act_nack() );
	execute( TC_chan_exhaustion() );
	execute( TC_chan_deact_silence() );
	execute( TC_chan_rel_rll_rel_ind() );
	execute( TC_chan_rel_conn_fail() );
	execute( TC_chan_rel_hard_clear() );
	execute( TC_chan_rel_last_eutran_plmn_hard_clear_no_csfb() );
	execute( TC_chan_rel_last_eutran_plmn_hard_clear_csfb() );
	execute( TC_chan_rel_hard_clear_csfb() );
	execute( TC_chan_rel_hard_rlsd() );
	execute( TC_chan_rel_hard_rlsd_ms_dead() );
	execute( TC_chan_rel_a_reset() );
	execute( TC_chan_rel_sccp_tiar_timeout() );
	execute( TC_chan_rel_rr_cause() );

	execute( TC_outbound_connect() );

	/* Assignment related */
	execute( TC_assignment_cic_only() );
	execute( TC_assignment_csd() );
	execute( TC_assignment_ctm() );
	execute( TC_assignment_sign() );
	if (mp_bssap_cfg[0].transport == BSSAP_TRANSPORT_AoIP) {
		execute( TC_assignment_aoip_tla_v6() );
	}
	execute( TC_assignment_fr_a5_0() );
	execute( TC_assignment_fr_a5_1() );
	if (mp_bssap_cfg[0].transport == BSSAP_TRANSPORT_AoIP) {
		execute( TC_assignment_fr_a5_1_codec_missing() );
	}
	execute( TC_assignment_fr_a5_3() );
	execute( TC_assignment_fr_a5_4() );
	execute( TC_assignment_fr_a5_4_fail() );
	execute( TC_assignment_fr_a5_not_sup() );
	execute( TC_ciph_mode_a5_0() );
	execute( TC_ciph_mode_a5_1() );
	execute( TC_ciph_mode_a5_2_0() );
	execute( TC_ciph_mode_a5_2_1() );
	execute( TC_ciph_mode_a5_3() );
	execute( TC_ciph_mode_a5_4() );

	execute( TC_assignment_codec_fr() );
	execute( TC_assignment_codec_fr_by_mode_modify() );
	execute( TC_assignment_codec_hr() );
	execute( TC_assignment_codec_efr() );
	execute( TC_assignment_codec_amr_f() );
	execute( TC_assignment_codec_amr_h() );

	if (mp_bssap_cfg[0].transport == BSSAP_TRANSPORT_AoIP) {
		execute( TC_assignment_codec_amr_f_S1() );
		execute( TC_assignment_codec_amr_h_S1() );
		execute( TC_assignment_codec_amr_f_S124() );
		execute( TC_assignment_codec_amr_h_S124() );
		execute( TC_assignment_codec_amr_f_S0() );
		execute( TC_assignment_codec_amr_f_S02() );
		execute( TC_assignment_codec_amr_f_S024() );
		execute( TC_assignment_codec_amr_f_S0247() );
		execute( TC_assignment_codec_amr_h_S0() );
		execute( TC_assignment_codec_amr_h_S02() );
		execute( TC_assignment_codec_amr_h_S024() );
		execute( TC_assignment_codec_amr_h_S0247() );
		execute( TC_assignment_codec_amr_f_S01234567() );
		execute( TC_assignment_codec_amr_f_S0234567() );
		execute( TC_assignment_codec_amr_f_zero() );
		execute( TC_assignment_codec_amr_f_unsupp() );
		execute( TC_assignment_codec_amr_h_S7() );
		execute( TC_assignment_codec_amr_f_start_mode_auto() );
		execute( TC_assignment_codec_amr_h_start_mode_auto() );
		execute( TC_assignment_codec_amr_f_start_mode_4() );
		execute( TC_assignment_codec_amr_h_start_mode_4() );
		execute( TC_assignment_codec_amr_startmode_cruft() );
	}

	execute( TC_assignment_codec_fr_exhausted_req_hr() );
	execute( TC_assignment_codec_fr_exhausted_req_fr() );
	execute( TC_assignment_codec_fr_exhausted_req_fr_hr() );
	execute( TC_assignment_codec_fr_exhausted_req_hr_fr() );
	execute( TC_assignment_codec_hr_exhausted_req_fr() );
	execute( TC_assignment_codec_hr_exhausted_req_hr() );
	execute( TC_assignment_codec_hr_exhausted_req_hr_fr() );
	execute( TC_assignment_codec_hr_exhausted_req_fr_hr() );
	execute( TC_assignment_codec_req_hr_fr() );
	execute( TC_assignment_codec_req_fr_hr() );
	execute( TC_assignment_sdcch_exhausted_req_signalling() );
	execute( TC_assignment_sdcch_exhausted_req_signalling_tch_forbidden() );
	execute( TC_assignment_sdcch_exhausted_req_voice_tch_forbidden() );

	execute( TC_assignment_osmux() );

	/* RLL Establish Indication on inactive DCHAN / SAPI */
	execute( TC_rll_est_ind_inact_lchan() );
	execute( TC_rll_est_ind_inval_sapi1() );
	execute( TC_rll_est_ind_inval_sapi3() );
	execute( TC_rll_est_ind_inval_sacch() );

	/* DLCI / RSL Link ID conversion for MO/MT messages on SAPI0/SAPI3 */
	execute( TC_tch_dlci_link_id_sapi() );

	/* SAPI N Reject triggered by RLL establishment failures */
	execute( TC_rll_rel_ind_sapi_n_reject() );
	execute( TC_rll_err_ind_sapi_n_reject() );
	execute( TC_rll_timeout_sapi_n_reject() );
	execute( TC_rll_sapi_n_reject_dlci_cc() );

	/* Paging related tests */
	execute( TC_paging_imsi_nochan() );
	execute( TC_paging_tmsi_nochan() );
	execute( TC_paging_tmsi_any() );
	execute( TC_paging_tmsi_sdcch() );
	execute( TC_paging_tmsi_tch_f() );
	execute( TC_paging_tmsi_tch_hf() );
	execute( TC_paging_imsi_nochan_cgi() );
	execute( TC_paging_imsi_nochan_lac_ci() );
	execute( TC_paging_imsi_nochan_ci() );
	execute( TC_paging_imsi_nochan_lai() );
	execute( TC_paging_imsi_nochan_lac() );
	execute( TC_paging_imsi_nochan_all() );
	execute( TC_paging_imsi_nochan_plmn_lac_rnc() );
	execute( TC_paging_imsi_nochan_rnc() );
	execute( TC_paging_imsi_nochan_lac_rnc() );
	execute( TC_paging_imsi_nochan_lacs() );
	execute( TC_paging_imsi_nochan_lacs_empty() );
	execute( TC_paging_imsi_nochan_cgi_unknown_cid() );
	execute( TC_paging_imsi_a_reset() );
	execute( TC_paging_imsi_load() );
	execute( TC_paging_counter() );
	execute( TC_paging_resp_unsol() );
	execute( TC_paging_500req() );
	execute( TC_paging_450req_no_paging_load_ind() );

	execute( TC_rsl_drop_counter() );
	execute( TC_rsl_unknown_unit_id() );

	execute( TC_oml_unknown_unit_id() );

	execute( TC_classmark() );
	execute( TC_common_id() );
	execute( TC_unsol_ass_fail() );
	execute( TC_unsol_ass_compl() );
	execute( TC_unsol_ho_fail() );
	execute( TC_err_82_short_msg() );
	execute( TC_err_84_unknown_msg() );

	execute( TC_ho_int() );
	execute( TC_ho_int_a5_0() );
	execute( TC_ho_int_a5_1() );
	execute( TC_ho_int_a5_3() );
	execute( TC_ho_int_a5_4() );
	execute( TC_ho_int_radio_link_failure() );

	/* TC_ho_out_of_this_bsc is run last, see comment below */
	execute( TC_ho_out_fail_no_msc_response() );
	execute( TC_ho_out_fail_rr_ho_failure() );
	execute( TC_ho_out_fail_no_result_after_ho_cmd() );

	execute( TC_ho_into_this_bsc() );
	execute( TC_ho_into_this_bsc_a5_0() );
	execute( TC_ho_into_this_bsc_a5_1() );
	execute( TC_ho_into_this_bsc_a5_3() );
	execute( TC_ho_into_this_bsc_a5_4() );
	execute( TC_ho_into_this_bsc_a5_1_3_no_chosen_enc_alg() );
	execute( TC_ho_into_this_bsc_a5_1_3() );
	execute( TC_ho_into_this_bsc_a5_mismatch() );
	if (mp_bssap_cfg[0].transport == BSSAP_TRANSPORT_AoIP) {
		execute( TC_ho_into_this_bsc_tla_v6() );
	}
	execute( TC_srvcc_eutran_to_geran() );
	execute( TC_srvcc_eutran_to_geran_a5_3() );
	execute( TC_srvcc_eutran_to_geran_src_sai() );
	execute( TC_srvcc_eutran_to_geran_ho_out() );
	execute( TC_srvcc_eutran_to_geran_forbid_fast_return() );
	execute( TC_srvcc_eutran_to_geran_ho_out_forbid_fast_return() );
	execute( TC_ho_in_fail_msc_clears() );
	execute( TC_ho_in_fail_msc_clears_after_ho_detect() );
	execute( TC_ho_in_fail_no_detect() );
	execute( TC_ho_in_fail_no_detect2() );
	execute( TC_ho_into_this_bsc_sccp_cr_without_bssap() );

	execute( TC_ho_neighbor_config_1() );
	execute( TC_ho_neighbor_config_2() );
	execute( TC_ho_neighbor_config_3() );
	execute( TC_ho_neighbor_config_4() );
	execute( TC_ho_neighbor_config_5() );
	execute( TC_ho_neighbor_config_6() );
	execute( TC_ho_neighbor_config_7() );

	execute( TC_bssap_rlsd_does_not_cause_bssmap_reset() );
	execute( TC_bssmap_clear_does_not_cause_bssmap_reset() );
	execute( TC_ms_rel_ind_does_not_cause_bssmap_reset() );

	execute( TC_dyn_pdch_ipa_act_deact() );
	execute( TC_dyn_pdch_ipa_act_nack() );
	execute( TC_dyn_pdch_osmo_act_deact() );
	execute( TC_dyn_pdch_osmo_act_nack() );
	execute( TC_dyn_ts_sdcch8_act_deact() );
	execute( TC_dyn_ts_sdcch8_all_subslots_used() );
	execute( TC_dyn_ts_sdcch8_tch_call_act_deact() );
	execute( TC_dyn_ts_sdcch8_act_nack() );

	execute( TC_chopped_ipa_ping() );
	execute( TC_chopped_ipa_payload() );

	/* Power control related */
	execute( TC_assignment_verify_ms_power_params_ie() );
	execute( TC_c0_power_red_mode() );

	/* MSC pooling */
	/* FIXME: in SCCPlite, indicating how many MSCs should be connected does currently not work. Since
	 * RESET->RESET-ACK is unconditionally negotiated for all configured MSCs, they always all appear as connected
	 * to osmo-bsc. The MSC pooling tests however require disconnecting selected MSCs, and hence don't work out as
	 * intended on SCCPlite. So for now, run these only for SCCP/M3UA. */
	if (mp_bssap_cfg[0].transport == BSSAP_TRANSPORT_AoIP) {
		execute( TC_mscpool_L3Compl_on_1_msc() );
		execute( TC_mscpool_L3Complete_by_imsi_round_robin() );
		execute( TC_mscpool_LU_by_tmsi_null_nri_0_round_robin() );
		execute( TC_mscpool_LU_by_tmsi_null_nri_1_round_robin() );
		execute( TC_mscpool_L3Complete_by_tmsi_unassigned_nri_round_robin() );
		execute( TC_mscpool_L3Complete_by_tmsi_valid_nri_msc_not_connected_round_robin() );
		execute( TC_mscpool_L3Complete_by_tmsi_valid_nri_1() );
		execute( TC_mscpool_L3Complete_by_tmsi_valid_nri_2() );
		execute( TC_mscpool_LU_by_tmsi_from_other_PLMN() );
		execute( TC_mscpool_paging_and_response_imsi() );
		execute( TC_mscpool_paging_and_response_tmsi() );
		execute( TC_mscpool_no_allow_attach_round_robin() );
		execute( TC_mscpool_no_allow_attach_valid_nri() );
	}

	execute( TC_early_conn_fail() );
	execute( TC_late_conn_fail() );
	execute( TC_stats_conn_fail() );

	/* Emergency call handling (deny / allow) */
	execute( TC_assignment_emerg_setup_allow() );
	execute( TC_assignment_emerg_setup_deny_msc() );
	execute( TC_assignment_emerg_setup_deny_bts() );
	execute( TC_emerg_premption() );

	/* Frequency hopping parameters handling */
	execute( TC_fh_params_chan_activ() );
	execute( TC_fh_params_imm_ass() );
	execute( TC_fh_params_assignment_cmd() );
	execute( TC_fh_params_handover_cmd() );
	execute( TC_fh_params_si4_cbch() );

	if (mp_enable_lcs_tests) {
		execute( TC_lcs_loc_req_for_active_ms() );
		execute( TC_lcs_loc_req_for_active_ms_ta_req() );
		execute( TC_lcs_loc_req_for_idle_ms() );
		execute( TC_lcs_loc_req_no_subscriber() );
		execute( TC_lcs_loc_req_for_active_ms_le_timeout() );
		execute( TC_lcs_loc_req_for_active_ms_le_timeout2() );
		execute( TC_lcs_loc_req_for_idle_ms_no_pag_resp() );
		execute( TC_cm_service_during_lcs_loc_req() );
		execute( TC_ho_during_lcs_loc_req() );
		execute( TC_emerg_call_and_lcs_loc_req() );
		execute( TC_emerg_call_and_lcs_loc_req_early_lchan_rel_ind() );
		execute( TC_emerg_call_and_lcs_loc_req_early_lchan_conn_fail() );
	}

	execute( TC_no_msc() );

	execute( TC_refuse_chan_act_to_vamos() );
	execute( TC_refuse_mode_modif_to_vamos() );

	execute( TC_reassignment_fr() );

	execute( TC_cm_reestablishment() );

	execute( TC_imm_ass_post_chan_ack() );
	execute( TC_imm_ass_pre_chan_ack() );
	execute( TC_imm_ass_pre_ts_ack() );
	execute( TC_imm_ass_pre_chan_ack_dyn_ts() );
	execute( TC_imm_ass_pre_ts_ack_dyn_ts() );

	execute( TC_ctrl_trx_rf_locked() );

	execute( TC_ratectr_all_available_allocated() );
	execute( TC_ratectr_all_available_allocated_dyn() );

	execute( TC_cm_serv_rej() );

	execute( TC_lost_sdcch_during_assignment() );

	/* Run TC_ho_out_of_this_bsc last, because it may trigger a segfault before osmo-bsc's patch
	 * with change-id I5a3345ab0005a73597f5c27207480912a2f5aae6 */
	execute( TC_ho_out_of_this_bsc() );
}

}