aboutsummaryrefslogtreecommitdiffstats
path: root/bts/BTS_Tests.ttcn
blob: f2861d17e96ce86a2ea067e92af56457165e4a78 (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
module BTS_Tests {

/* Integration Tests for OsmoBTS
 * (C) 2018-2019 by Harald Welte <laforge@gnumonks.org>
 * contributions by Vadim Yanitskiy and sysmocom - s.f.m.c. GmbH
 * 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 OsmoBTS by attaching to the external interfaces
 * such as Abis RSL, PCU, VTY as well as by attaching to a MS L1 implementation
 * using the L1CTL protocol/interface.
 *
 * You can run the tests with
 *  a) osmo-bts-trx + trxcon + fake_trx (without any hardware)
 *  b) any osmo-bts-* + OsmocomBB layer1 + osmocon (with real BTS hardware)
 *  c) osmo-bts-virtual + virt_phy (without any hardware)
 *
 * Some of the tests will only run on a subset of those three configurations
 * due to limitations in the respective L1.
 */

import from Misc_Helpers all;
import from General_Types all;
import from GSM_Types all;
import from GSM_RR_Types all;
import from Osmocom_Types all;
import from GSM_Types all;
import from GSM_SystemInformation all;
import from L1CTL_PortType all;
import from L1CTL_Types all;
import from LAPDm_Types all;
import from LAPDm_RAW_PT all;
import from Osmocom_CTRL_Adapter all;
import from Osmocom_CTRL_Functions all;

import from RSL_Types all;
import from IPA_Types all;
import from IPA_Emulation all;
import from IPA_Testing all;
import from RSL_Emulation all;

import from IPL4asp_Types all;
import from TRXC_Types all;
import from TRXC_CodecPort all;
import from TRXC_CodecPort_CtrlFunct all;

import from PCUIF_Types all;
import from PCUIF_CodecPort all;
import from UD_Types all;

import from MobileL3_CommonIE_Types all;
import from MobileL3_RRM_Types all;
import from MobileL3_Types all;
import from L3_Templates all;
import from L3_Common all;
import from MobileL3_GMM_SM_Types all;

import from Osmocom_VTY_Functions all;
import from TELNETasp_PortType all;
import from BTS_Tests_LAPDm all;

friend module BTS_Tests_SMSCB;
friend module BTS_Tests_virtphy;
friend module BTS_Tests_LAPDm;

/* The tests assume a BTS with the following timeslot configuration:
 * TS0 : Combined CCCH + SDCCH/4
 * TS1 : TCH/F
 * TS2 : TCH/F
 * TS3 : TCH/F_PDCH (IPA Style)
 * TS4 : TCH/F_TCH/H_PDCH (Osmocom Style)
 * TS5 : TCH/H
 * TS6 : SDCCH/8
 * TS7 : PDCH
 */

modulepar {
	charstring mp_rsl_ip := "127.0.0.2";
	integer mp_rsl_port := 3003;
	integer mp_trx0_arfcn := 871;
	charstring mp_bts_trxc_ip := "127.0.0.1";
	integer mp_bts_trxc_port := 5701;
	charstring mp_pcu_socket := PCU_SOCK_DEFAULT;
	charstring mp_ctrl_ip := "127.0.0.1";
	integer mp_ctrl_port := 4238;
	charstring mp_bsc_ctrl_ip := "127.0.0.1";
	integer mp_bsc_ctrl_port := 4249;
	integer mp_tolerance_rxqual := 1;
	integer mp_tolerance_rxlev := 3;
	integer mp_tolerance_timing_offset_256syms := 0;
	integer mp_rxlev_exp := 57;
	integer mp_ul_rxlev_exp := 10;
	integer mp_ms_power_level_exp := 7;
	integer mp_ms_actual_ta_exp := 0;
	integer mp_timing_offset_256syms_exp := 512;
	/* Time to wait for RSL conn from BTS during startup of test */
	float mp_ipa_up_timeout := 15.0;
	float mp_ipa_up_delay := 0.0;
	/* false for now, as only virtphy supports it, not calypso-l1 nor trxcon */
	boolean mp_l1_supports_gprs := false;
}

type record of RslChannelNr ChannelNrs;

type component test_CT extends CTRL_Adapter_CT {
	/* IPA Emulation component underneath RSL */
	var IPA_Emulation_CT vc_IPA;
	/* RSL Emulation component (for ConnHdlr tests) */
	var RSL_Emulation_CT vc_RSL;
	/* Direct RSL_CCHAN_PT */
	port RSL_CCHAN_PT RSL_CCHAN;

	/* L1CTL port (for classic tests) */
	port L1CTL_PT L1CTL;

	/* Optional TRXC connection to FakeTRX (BTS side) */
	port TRXC_CODEC_PT BTS_TRXC;
	var integer g_bts_trxc_conn_id;

	/* VTY connections to both BTS and BSC */
	port TELNETasp_PT BTSVTY;
	port TELNETasp_PT BSCVTY;

	/* PCU Interface of BTS */
	port PCUIF_CODEC_PT PCU;
	var integer g_pcu_conn_id;
	/* Last PCU INFO IND we received */
	var PCUIF_Message g_pcu_last_info;

	/* SI configuration */
	var SystemInformationConfig si_cfg := {
		bcch_extended := false,
		si1_present := false,
		si2bis_present := false,
		si2ter_present := false,
		si2quater_present := false,
		si7_present := false,
		si8_present := false,
		si9_present := false,
		si13_present := false,
		si13alt_present := false,
		si15_present := false,
		si16_present := false,
		si17_present := false,
		si2n_present := false,
		si21_present := false,
		si22_present := false
	};

	/* all logical channels available on the BTS */
	var ChannelNrs g_AllChannels;
	var ChannelNrs g_AllChanTypes;
}

/* an individual call / channel */
type component ConnHdlr extends RSL_DchanHdlr, lapdm_test_CT {
	port L1CTL_PT L1CTL;

	/* Optional TRXC connection to FakeTRX (BTS side) */
	port TRXC_CODEC_PT BTS_TRXC;
	var integer g_bts_trxc_conn_id;

	timer g_Tguard;
	timer g_Tmeas_exp := 2.0; /* >= 103 SACCH multiframe ~ 500ms */

	var ConnHdlrPars g_pars;
	var uint8_t g_next_meas_res_nr := 0;
	var boolean g_first_meas_res := true;

	/* PCU Interface of BTS */
	port PCUIF_CODEC_PT PCU;
}

function f_init_rsl(charstring id) runs on test_CT {
	vc_IPA := IPA_Emulation_CT.create(id & "-RSL-IPA");
	vc_RSL := RSL_Emulation_CT.create(id & "-RSL");

	map(vc_IPA:IPA_PORT, system:IPA_CODEC_PT);
	connect(vc_IPA:IPA_RSL_PORT, vc_RSL:IPA_PT);
	connect(self:RSL_CCHAN, vc_RSL:CCHAN_PT);

	vc_IPA.start(IPA_Emulation.main_server(mp_rsl_ip, mp_rsl_port));
	vc_RSL.start(RSL_Emulation.main(false));
}

type record ConnHdlrPars {
	RslChannelNr chan_nr,
	RSL_IE_ChannelMode chan_mode,
	float t_guard,
	ConnL1Pars l1_pars,
	TestSpecUnion spec optional,
	RSL_IE_EncryptionInfo encr optional,
	BtsBand bts0_band optional
}

/* Test-specific parameters */
type union TestSpecUnion {
	RllTestCase rll
}

template (value) RachControlParameters ts_RachCtrl_default := {
	max_retrans := RACH_MAX_RETRANS_7,
	tx_integer := '1001'B, /* 12 slots */
	cell_barr_access := false,
	re_not_allowed := true,
	acc := '0000010000000000'B
};

template (value) CellSelectionParameters ts_CellSelPar_default := {
	cell_resel_hyst_2dB := 2,
	ms_txpwr_max_cch := mp_ms_power_level_exp,
	acs := '0'B,
	neci := true,
	rxlev_access_min := 0
}

template (value) LocationAreaIdentification ts_LAI_default := {
	mcc_mnc := '262F42'H,
	lac := 42
}

/* Default SYSTEM INFORMATION 3 */
template (value) SystemInformation ts_SI3_default := {
	header := ts_RrHeader(SYSTEM_INFORMATION_TYPE_3, 18),
	payload := {
		si3 := {
			cell_id := 23,
			lai := ts_LAI_default,
			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 := 0, /* 2 multiframes */
				t3212 := 1 /* 6 minutes */
			},
			cell_options := {
				dn_ind := false,
				pwrc := false,
				dtx := MS_MAY_USE_UL_DTX,
				radio_link_tout_div4 := (32/4)-1
			},
			cell_sel_par := ts_CellSelPar_default,
			rach_control := ts_RachCtrl_default,
			rest_octets := '2C2B2B2B'O /* GPRS present */
		}
	}
}

template (value) SystemInformation ts_SI2_default := {
	header := ts_RrHeader(SYSTEM_INFORMATION_TYPE_2, 22),
	payload := {
		si2 := {
			bcch_freq_list := '00000000000000000000000000000000'O,
			ncc_permitted := '11111111'B,
			rach_control := ts_RachCtrl_default
		}
	}
}

template (value) SystemInformation ts_SI4_default := {
	header := ts_RrHeader(SYSTEM_INFORMATION_TYPE_4, 12), /* no CBCH / restoct */
	payload := {
		si4 := {
			lai := ts_LAI_default,
			cell_sel_par := ts_CellSelPar_default,
			rach_control := ts_RachCtrl_default,
			cbch_chan_desc := omit,
			cbch_mobile_alloc := omit,
			rest_octets := ''O
		}
	}
}

function f_rsl_bcch_fill_raw(RSL_IE_SysinfoType rsl_si_type, octetstring si_enc)
runs on test_CT {
	log("Setting ", rsl_si_type, ": ", si_enc);
	RSL_CCHAN.send(ts_RSL_UD(ts_RSL_BCCH_INFO(rsl_si_type, si_enc)));
}

function f_rsl_bcch_fill(RSL_IE_SysinfoType rsl_si_type, template (value) SystemInformation si_dec)
runs on test_CT {
	var octetstring si_enc := enc_SystemInformation(valueof(si_dec));
	log("Setting ", rsl_si_type, ": ", si_dec);
	f_rsl_bcch_fill_raw(rsl_si_type, si_enc);
}

friend function f_init_vty(charstring id) runs on test_CT {
	map(self:BTSVTY, system:BTSVTY);
	f_vty_set_prompts(BTSVTY);
	f_vty_transceive(BTSVTY, "enable");
}

friend function f_init_vty_bsc() runs on test_CT {
	map(self:BSCVTY, system:BSCVTY);
	f_vty_set_prompts(BSCVTY, "OsmoBSC");
	f_vty_transceive(BSCVTY, "enable");
}

/* PCU socket may at any time receive a new INFO.ind */
private altstep as_pcu_info_ind(PCUIF_CODEC_PT pt, integer pcu_conn_id,
				out PCUIF_Message pcu_last_info) {
	var PCUIF_send_data sd;
	[] pt.receive(t_SD_PCUIF(pcu_conn_id, tr_PCUIF_INFO_IND(0, ?))) -> value sd {
		pcu_last_info := sd.data;
		}
	[] pt.receive(t_SD_PCUIF(pcu_conn_id, tr_PCUIF_INFO_IND(?, ?, ?))) -> value sd {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Invalid PCU Version/BTS Number received");
		}
}

private function f_init_pcu(PCUIF_CODEC_PT pt, charstring id,
			    out integer pcu_conn_id, out PCUIF_Message pcu_last_info) {
	timer T := 2.0;
	var PCUIF_send_data sd;
	if (mp_pcu_socket == "") {
		pcu_conn_id := -1;
		return;
	}
	pcu_conn_id := f_pcuif_connect(pt, mp_pcu_socket);

	T.start;
	alt {
	[] as_pcu_info_ind(pt, pcu_conn_id, pcu_last_info);
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for PCU INFO_IND");
		}
	}
}

private function f_init_trxc(TRXC_CODEC_PT pt, charstring id,
			     out integer trxc_conn_id) {
	var Result res;

	res := TRXC_CodecPort_CtrlFunct.f_IPL4_connect(pt, mp_bts_trxc_ip, mp_bts_trxc_port,
						       "", -1, -1, { udp := {} }, {});
	if (not ispresent(res.connId)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					"Could not connect to the control (TRXC) interface " &
					"of FakeTRX, check your configuration");
	}
	trxc_conn_id := res.connId;
}

/* global init function */
function f_init() runs on test_CT {
	var charstring id := testcasename();
	timer T := mp_ipa_up_timeout;
	g_AllChannels := {
		/* TS 1..4: TCH/F */
		valueof(ts_RslChanNr_Bm(1)), valueof(ts_RslChanNr_Bm(2)),
		valueof(ts_RslChanNr_Bm(3)), valueof(ts_RslChanNr_Bm(4)),
		/* TS 5: TCH/H */
		valueof(ts_RslChanNr_Lm(5,0)), valueof(ts_RslChanNr_Lm(5,1)),
		/* TS 0: SDCCH/4 */
		valueof(ts_RslChanNr_SDCCH4(0,0)), valueof(ts_RslChanNr_SDCCH4(0,1)),
		valueof(ts_RslChanNr_SDCCH4(0,2)), valueof(ts_RslChanNr_SDCCH4(0,3)),
		/* TS 6: SDCCH/8 */
		valueof(ts_RslChanNr_SDCCH8(6,0)), valueof(ts_RslChanNr_SDCCH8(6,1)),
		valueof(ts_RslChanNr_SDCCH8(6,2)), valueof(ts_RslChanNr_SDCCH8(6,3)),
		valueof(ts_RslChanNr_SDCCH8(6,4)), valueof(ts_RslChanNr_SDCCH8(6,5)),
		valueof(ts_RslChanNr_SDCCH8(6,6)), valueof(ts_RslChanNr_SDCCH8(6,7))
	};

	/* FIXME: FACCH/H is unreliable with calypso firmware, see OS#3653 */
	if (mp_bts_trxc_port != -1) {
		g_AllChanTypes := {
			/* TS 1..4: TCH/F */
			valueof(ts_RslChanNr_Bm(1)),
			/* TS 5: TCH/H */
			valueof(ts_RslChanNr_Lm(5,1)),
			/* TS 0: SDCCH/4 */
			valueof(ts_RslChanNr_SDCCH4(0,2)),
			/* TS 6: SDCCH/8 */
			valueof(ts_RslChanNr_SDCCH8(6,4))
		};
	} else {
		g_AllChanTypes := {
			/* TS 1..4: TCH/F */
			valueof(ts_RslChanNr_Bm(1)),
			/* TS 0: SDCCH/4 */
			valueof(ts_RslChanNr_SDCCH4(0,2)),
			/* TS 6: SDCCH/8 */
			valueof(ts_RslChanNr_SDCCH8(6,4))
		};
	}
	f_init_rsl(id);
	T.start;
	alt {
	[] RSL_CCHAN.receive(ASP_IPA_Event:{up_down := ASP_IPA_EVENT_UP});
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for ASP_IPA_EVENT_UP");
		}
	}
	f_sleep(0.5);	/* workaround for OS#3000 */
	f_init_vty(id);
	f_ipa_ctrl_start(mp_ctrl_ip, mp_ctrl_port);

	/* Send SI3 to the BTS, it is needed for various computations */
	f_rsl_bcch_fill(RSL_SYSTEM_INFO_3, ts_SI3_default);
	/* SI2 + SI4 are required for SI testing as they are mandatory defaults */
	f_rsl_bcch_fill(RSL_SYSTEM_INFO_2, ts_SI2_default);
	f_rsl_bcch_fill(RSL_SYSTEM_INFO_4, ts_SI4_default);

	map(self:PCU, system:PCU);
	f_init_pcu(PCU, id, g_pcu_conn_id, g_pcu_last_info);

	if (mp_bts_trxc_port != -1) {
		var TrxcMessage ret;

		/* Init TRXC interface to FakeTRX */
		map(self:BTS_TRXC, system:BTS_TRXC);
		f_init_trxc(BTS_TRXC, id, g_bts_trxc_conn_id);

		/* Start with a default moderate timing offset equalling TA=2, and RSSI=-60 */
		ret := f_TRXC_transceive(BTS_TRXC, g_bts_trxc_conn_id, valueof(ts_TRXC_FAKE_TIMING(2*256)));
		ret := f_TRXC_transceive(BTS_TRXC, g_bts_trxc_conn_id, valueof(ts_TRXC_FAKE_RSSI(-60)));
		/* OsmoBTS may have different AB / NB threshold (see MIN_QUAL_NORM, MIN_QUAL_RACH) */
		ret := f_TRXC_transceive(BTS_TRXC, g_bts_trxc_conn_id, valueof(ts_TRXC_FAKE_CI(60)));
	}

	/* Wait some extra time to make sure the BTS emits a stable carrier.
	 * (this is only relevant when running the tests with a physical BTS.) */
	f_sleep(mp_ipa_up_delay);
}

/* Attach L1CTL to master test_CT (classic tests, non-handler mode) */
function f_init_l1ctl() runs on test_CT {
	map(self:L1CTL, system:L1CTL);
	f_connect_reset(L1CTL);
}

type function void_fn(charstring id) runs on ConnHdlr;

/* create a new test component */
function f_start_handler(void_fn fn, ConnHdlrPars pars,
			 boolean pcu_comp := false,
			 boolean trxc_comp := false)
runs on test_CT return ConnHdlr {
	var charstring id := testcasename();
	var ConnHdlr vc_conn;

	vc_conn := ConnHdlr.create(id);
	/* connect to RSL Emulation main component */
	connect(vc_conn:RSL, vc_RSL:CLIENT_PT);
	connect(vc_conn:RSL_PROC, vc_RSL:RSL_PROC);

	/* The ConnHdlr component may want to talk to some ports directly,
	 * so we disconnect it from the test_CT and connect it to the component.
	 * This obviously only works for one component, i.e. no concurrency. */
	if (pcu_comp) {
		unmap(self:PCU, system:PCU);
		map(vc_conn:PCU, system:PCU);
	}
	if (trxc_comp) {
		unmap(self:BTS_TRXC, system:BTS_TRXC);
		map(vc_conn:BTS_TRXC, system:BTS_TRXC);
	}

	vc_conn.start(f_handler_init(fn, id, pars));
	return vc_conn;
}

template ASP_RSL_Unitdata ts_RSL_UD(template RSL_Message rsl, IpaStreamId sid := IPAC_PROTO_RSL_TRX0) := {
	streamId := sid,
	rsl := rsl
}

template ASP_RSL_Unitdata tr_RSL_UD(template RSL_Message rsl,
				    template IpaStreamId sid := IPAC_PROTO_RSL_TRX0) := {
	streamId := sid,
	rsl := rsl
}

private altstep as_Tguard() runs on ConnHdlr {
	[] g_Tguard.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Tguard timeout");
	}
}

friend function f_l1_tune(L1CTL_PT L1CTL, L1ctlCcchMode ccch_mode := CCCH_MODE_COMBINED) {
	f_L1CTL_FBSB(L1CTL, { false, mp_trx0_arfcn }, ccch_mode, mp_rxlev_exp);
}

private function f_trxc_fake_rssi(TRXC_RSSI rssi) runs on ConnHdlr {
	var TrxcMessage ret;
	ret := f_TRXC_transceive(BTS_TRXC, g_bts_trxc_conn_id, valueof(ts_TRXC_FAKE_RSSI(rssi)));
}

private function f_trxc_fake_toffs256(int16_t toffs256) runs on ConnHdlr {
	var TrxcMessage ret;
	ret := f_TRXC_transceive(BTS_TRXC, g_bts_trxc_conn_id, valueof(ts_TRXC_FAKE_TIMING(toffs256)));
}

/* first function started in ConnHdlr component */
private function f_handler_init(void_fn fn, charstring id, ConnHdlrPars pars)
runs on ConnHdlr {
	g_pars := pars;
	g_chan_nr := pars.chan_nr;

	map(self:L1CTL, system:L1CTL);
	f_connect_reset(L1CTL);

	if (mp_bts_trxc_port != -1 and BTS_TRXC.checkstate("Mapped")) {
		f_init_trxc(BTS_TRXC, id, g_bts_trxc_conn_id);
	}

	g_Tguard.start(pars.t_guard);
	activate(as_Tguard());

	f_rslem_register(0, pars.chan_nr);

	/* call the user-supplied test case function */
	fn.apply(id);
}

function f_rsl_transceive_ret(template RSL_Message tx, template RSL_Message exp_rx, charstring id,
				boolean ignore_other := false)
runs on ConnHdlr return RSL_Message {
	var RSL_Message rx;
	timer T := 3.0;
	RSL.send(tx);
	T.start;
	alt {
	[] RSL.receive(exp_rx) -> value rx {
		T.stop;
		setverdict(pass);
		}
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout expecting " & id);
		}
	[not ignore_other] as_l1_sacch();
	[not ignore_other] as_meas_res();
	[not ignore_other] as_l1_dcch();
	[not ignore_other] RSL.receive {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unexpected RSL message received");
		}
	[ignore_other] RSL.receive { repeat; }
	}
	return rx;
}

function f_rsl_transceive(template RSL_Message tx, template RSL_Message exp_rx, charstring id,
			  boolean ignore_other := false)
runs on ConnHdlr {
	var RSL_Message rx := f_rsl_transceive_ret(tx, exp_rx, id, ignore_other);
}

function f_rsl_chan_act(RSL_IE_ChannelMode mode, boolean encr_enable := false, RSL_IE_List more_ies := {},
			RSL_IE_ActivationType act_type := t_RSL_IE_ActType_IA) runs on ConnHdlr {
	var RSL_Message ch_act := valueof(ts_RSL_CHAN_ACT(g_chan_nr, mode, act_type));
	if (encr_enable) {
		/* append encryption related IEs, if requested */
		var RSL_IE_EncryptionInfo encr_info;
		encr_info := valueof(ts_RSL_IE_EncrInfo(g_pars.encr.alg_id, g_pars.encr.key));
		ch_act.ies := ch_act.ies & { valueof(t_RSL_IE(RSL_IE_ENCR_INFO, RSL_IE_Body:{encr_info :=
encr_info})) };
	}
	ch_act.ies := ch_act.ies & more_ies;
	f_rsl_transceive(ch_act, tr_RSL_CHAN_ACT_ACK(g_chan_nr), "RSL CHAN ACT");
}

function f_rsl_chan_deact() runs on ConnHdlr {
	f_rsl_transceive(ts_RSL_RF_CHAN_REL(g_chan_nr), tr_RSL_RF_CHAN_REL_ACK(g_chan_nr),
			"RF CHAN REL", true);
}

friend template ConnHdlrPars t_Pars(template RslChannelNr chan_nr,
					template RSL_IE_ChannelMode chan_mode,
					float t_guard := 20.0) := {
	chan_nr := valueof(chan_nr),
	chan_mode := valueof(chan_mode),
	t_guard := t_guard,
	l1_pars := {
		dtx_enabled := false,
		toa256_enabled := false,
		meas_ul := {
			full := {
				rxlev := mp_ul_rxlev_exp,
				rxqual := 0
			},
			sub := {
				rxlev := mp_ul_rxlev_exp,
				rxqual := 0
			}
		},
		timing_offset_256syms := mp_timing_offset_256syms_exp,
		bs_power_level := 0,
		ms_power_level := mp_ms_power_level_exp,
		ms_actual_ta := mp_ms_actual_ta_exp
	},
	spec := omit,
	encr := omit,
	bts0_band := omit
}

/***********************************************************************
 * Channel Activation / Deactivation
 ***********************************************************************/

/* Stress test: Do 500 channel activations/deactivations in rapid succession */
function f_TC_chan_act_stress(charstring id) runs on ConnHdlr {
	for (var integer i := 0; i < 500; i := i+1) {
		f_rsl_chan_act(g_pars.chan_mode);
		f_rsl_chan_deact();
	}
	setverdict(pass);
}
testcase TC_chan_act_stress() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	f_init();
	vc_conn := f_start_handler(refers(f_TC_chan_act_stress), pars);
	vc_conn.done;
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Test if re-activation of an already active channel fails as expected */
function f_TC_chan_act_react(charstring id) runs on ConnHdlr {
	f_rsl_chan_act(g_pars.chan_mode);
	/* attempt to activate the same lchan again -> expect reject */
	RSL.send(ts_RSL_CHAN_ACT(g_chan_nr, g_pars.chan_mode));
	alt {
	[] RSL.receive(tr_RSL_CHAN_ACT_ACK(g_chan_nr)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unexpected CHAN ACT ACK on double activation");
		}
	[] RSL.receive(tr_RSL_CHAN_ACT_NACK(g_chan_nr)) {
		setverdict(pass);
		}
	}
	f_rsl_chan_deact();
}
testcase TC_chan_act_react() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	f_init();
	vc_conn := f_start_handler(refers(f_TC_chan_act_react), pars);
	vc_conn.done;
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Attempt to de-activate a channel that's not active */
function f_TC_chan_deact_not_active(charstring id) runs on ConnHdlr {
	timer T := 3.0;
	RSL.send(ts_RSL_RF_CHAN_REL(g_chan_nr));
	T.start;
	alt {
	[] RSL.receive(tr_RSL_RF_CHAN_REL_ACK(g_chan_nr)) {
		setverdict(pass);
		}
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout expecting RF_CHAN_REL_ACK");
		}
	}
}
testcase TC_chan_deact_not_active() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	f_init();
	var ConnHdlr vc_conn := f_start_handler(refers(f_TC_chan_deact_not_active), pars);
	vc_conn.done;
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* attempt to activate channel with wrong RSL Channel Nr IE; expect NACK */
function f_TC_chan_act_wrong_nr(charstring id) runs on ConnHdlr {
	RSL.send(ts_RSL_CHAN_ACT(g_chan_nr, g_pars.chan_mode));
	alt {
	[] RSL.receive(tr_RSL_CHAN_ACT_ACK(g_chan_nr)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unexpected CHAN ACT ACK");
		}
	[] RSL.receive(tr_RSL_CHAN_ACT_NACK(g_chan_nr)) {
		setverdict(pass);
		}
	}
}
private type record WrongChanNrCase {
	RslChannelNr	chan_nr,
	charstring	description
}
private type record of WrongChanNrCase WrongChanNrCases;
private template WrongChanNrCase t_WCN(template RslChannelNr chan_nr, charstring desc) := {
	chan_nr := chan_nr,
	description := desc
}

testcase TC_chan_act_wrong_nr() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;

	f_init();

	var WrongChanNrCases wrong := {
		valueof(t_WCN(t_RslChanNr_RACH(0), "RACH is not a dedicated channel")),
		valueof(t_WCN(t_RslChanNr_RACH(1), "RACH doesn't exist on timeslot")),
		valueof(t_WCN(t_RslChanNr_BCCH(0), "BCCH is not a dedicated channel")),
		valueof(t_WCN(t_RslChanNr_PCH_AGCH(0), "PCH/AGCH is not a dedicated channel")),
		valueof(t_WCN(t_RslChanNr_Bm(0), "TS0 cannot be TCH/F")),
		valueof(t_WCN(t_RslChanNr_Lm(0, 0), "TS0 cannot be TCH/H")),
		valueof(t_WCN(t_RslChanNr_Lm(0, 1), "TS0 cannot be TCH/H")),
		valueof(t_WCN(t_RslChanNr_PDCH(0), "TS0 cannot be PDCH")),
		valueof(t_WCN(t_RslChanNr_SDCCH8(0, 0), "TS0 cannot be SDCCH/8")),
		valueof(t_WCN(t_RslChanNr_SDCCH8(0, 7), "TS0 cannot be SDCCH/8")),
		valueof(t_WCN(t_RslChanNr_SDCCH4(7, 0), "TS7 cannot be SDCCH/4")),
		valueof(t_WCN(t_RslChanNr_SDCCH4(7, 3), "TS7 cannot be SDCCH/4")),
		valueof(t_WCN(t_RslChanNr_Lm(1, 0), "TS1 cannot be TCH/H"))
	};

	for (var integer i := 0; i < sizeof(wrong); i := i+1) {
		pars := valueof(t_Pars(wrong[i].chan_nr, ts_RSL_ChanMode_SIGN));
		vc_conn := f_start_handler(refers(f_TC_chan_act_wrong_nr), pars);
		vc_conn.done;
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* execute the same callback function on a variety of logical channels */
friend function f_testmatrix_each_chan(ConnHdlrPars pars, void_fn fn) runs on test_CT {
	var ConnHdlr vc_conn;
	f_init();

	/* test on each of the channels we have */
	for (var integer i := 0; i < sizeof(g_AllChanTypes); i := i+1) {
		pars.chan_nr := valueof(g_AllChanTypes[i]);

		log(testcasename(), ": XXX Starting on ", g_AllChanTypes[i]);
		vc_conn := f_start_handler(fn, pars);
		vc_conn.done;
	}

	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/***********************************************************************
 * SACCH handling
 ***********************************************************************/

private function f_exp_sacch(boolean exp) runs on ConnHdlr {
	timer T_sacch := 3.0;
	T_sacch.start;
	alt {
	[not exp] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(0))) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Received SACCH when not expecting it");
		}
	[not exp] T_sacch.timeout {
		setverdict(pass);
		}
	[exp] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(0))) {
		setverdict(pass);
		}
	[exp] T_sacch.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Timeout waiting for SACCH on ", g_chan_nr));
		}
	[] L1CTL.receive { repeat; }
	[] RSL.receive { repeat; }
	}
}

/* Test if DEACTIVATE SACCH actualy deactivates its transmission (TS 48.058 4.6) */
private function f_TC_deact_sacch(charstring id) runs on ConnHdlr {
	f_l1_tune(L1CTL);
	RSL.clear;

	/* activate the logical channel */
	f_est_dchan();
	L1CTL.clear;

	/* check that SACCH actually are received as expected */
	f_exp_sacch(true);

	/* deactivate SACCH on the logical channel */
	RSL.send(ts_RSL_DEACT_SACCH(g_chan_nr));
	f_sleep(1.0);
	L1CTL.clear;

	/* check that no SACCH are received anymore */
	f_exp_sacch(false);

	/* release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
}
testcase TC_deact_sacch() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	for (var integer i := 0; i < sizeof(g_AllChannels); i := i+1) {
	//for (var integer i := 0; i < 1; i := i+1) {
		pars := valueof(t_Pars(g_AllChannels[i], ts_RSL_ChanMode_SIGN));
		log(testcasename(), ": Starting for ", g_AllChannels[i]);
		vc_conn := f_start_handler(refers(f_TC_deact_sacch), pars);
		vc_conn.done;
	}
	/* TODO: do the above in parallel, rather than sequentially? */
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* verify that given SACCH payload is present */
private function f_sacch_present(template octetstring l3_exp) runs on ConnHdlr {
	var L1ctlDlMessage dl;
	/* check that the specified SI5 value is actually sent */
	timer T_sacch := 3.0;
	L1CTL.clear;
	T_sacch.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(0))) -> value dl {
		var octetstring l3 := substr(dl.payload.data_ind.payload, 4, 19);
		if (match(l3, l3_exp)) {
			setverdict(pass);
		} else {
			repeat;
		}
		}
	[] L1CTL.receive { repeat; }
	[] T_sacch.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Timeout waiting for SACCH ", l3_exp));
		}
	}
}

/* verify that given SACCH payload is not present */
private function f_sacch_missing(template octetstring l3_exp) runs on ConnHdlr {
	var L1ctlDlMessage dl;
	/* check that the specified SI5 value is actually sent */
	timer T_sacch := 3.0;
	L1CTL.clear;
	T_sacch.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(0))) -> value dl {
		var octetstring l3 := substr(dl.payload.data_ind.payload, 4, 19);
		if (match(l3, l3_exp)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Received unexpected SACCH ", dl));
		} else {
			repeat;
		}
		}
	[] L1CTL.receive { repeat; }
	[] T_sacch.timeout {
		setverdict(pass);
		}
	}
}

/* Test for default SACCH FILL transmitted in DL SACCH (all channel types) */
private function f_TC_sacch_filling(charstring id) runs on ConnHdlr {
	/* Set a known default SACCH filling for SI5 */
	var octetstring si5 := f_rnd_octstring(19);
	RSL.send(ts_RSL_SACCH_FILL(RSL_SYSTEM_INFO_5, si5));

	f_l1_tune(L1CTL);
	RSL.clear;

	/* activate the logical channel */
	f_est_dchan();

	/* check that the specified SI5 value is actually sent */
	f_sacch_present(si5);

	/* release the channel */
	RSL.clear;
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
}
testcase TC_sacch_filling() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	for (var integer i := 0; i < sizeof(g_AllChannels); i := i+1) {
		pars := valueof(t_Pars(g_AllChannels[i], ts_RSL_ChanMode_SIGN));
		log(testcasename(), ": Starting for ", g_AllChannels[i]);
		vc_conn := f_start_handler(refers(f_TC_sacch_filling), pars);
		vc_conn.done;
	}
	/* TODO: do the above in parallel, rather than sequentially? */
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Test for lchan-specific SACCH INFO MODIFY (TS 48.058 4.12) */
private function f_TC_sacch_info_mod(charstring id) runs on ConnHdlr {
	/* Set a known default SACCH filling for SI5 */
	var octetstring si5 := f_rnd_octstring(19);
	var octetstring si5_diff := f_rnd_octstring(19);
	RSL.send(ts_RSL_SACCH_FILL(RSL_SYSTEM_INFO_5, si5));

	f_l1_tune(L1CTL);
	RSL.clear;

	log("Activating channel, expecting standard SI5");
	/* activate the logical channel */
	f_est_dchan();
	/* check that the specified SI5 value is actually sent */
	f_sacch_present(si5);

	/* set channel-specific different SI5 */
	log("Setting channel specific SACCH INFO, expecting it");
	RSL.send(ts_RSL_SACCH_INF_MOD(g_chan_nr, RSL_SYSTEM_INFO_5, si5_diff))
	/* check that the specified lchan-specific value is now used */
	f_sacch_present(si5_diff);

	/* deactivate the channel and re-activate it, this should result in default SI5  */
	log("De-activating and re-activating channel, expecting standard SI5");
	f_rsl_chan_deact();
	f_rsl_chan_act(valueof(ts_RSL_ChanMode_SIGN));
	/* Verify that the TRX-wide default SACCH filling is present again */
	f_sacch_present(si5);

	/* release the channel */
	RSL.clear;
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
}
testcase TC_sacch_info_mod() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	for (var integer i := 0; i < sizeof(g_AllChannels); i := i+1) {
		pars := valueof(t_Pars(g_AllChannels[i], ts_RSL_ChanMode_SIGN));
		log(testcasename(), ": Starting for ", g_AllChannels[i]);
		vc_conn := f_start_handler(refers(f_TC_sacch_info_mod), pars);
		vc_conn.done;
	}
	/* TODO: do the above in parallel, rather than sequentially? */
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Test SACCH scheduling of multiple different SI message types */
private function f_TC_sacch_multi(charstring id) runs on ConnHdlr {
	var octetstring si5 := f_rnd_octstring(19);
	var octetstring si5bis := f_rnd_octstring(19);
	var octetstring si5ter := f_rnd_octstring(19);
	var octetstring si6 := f_rnd_octstring(19);

	RSL.send(ts_RSL_SACCH_FILL(RSL_SYSTEM_INFO_5, si5));
	RSL.send(ts_RSL_SACCH_FILL(RSL_SYSTEM_INFO_5bis, si5bis));
	RSL.send(ts_RSL_SACCH_FILL(RSL_SYSTEM_INFO_5ter, si5ter));
	RSL.send(ts_RSL_SACCH_FILL(RSL_SYSTEM_INFO_6, si6));

	f_l1_tune(L1CTL);
	RSL.clear;

	/* activate the logical channel */
	f_est_dchan();
	L1CTL.clear;

	/* check that SACCH actually are received as expected */
	f_sacch_present(si5);
	f_sacch_present(si5bis);
	f_sacch_present(si5ter);
	f_sacch_present(si6);

	/* release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
}
testcase TC_sacch_multi() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	for (var integer i := 0; i < sizeof(g_AllChannels); i := i+1) {
		pars := valueof(t_Pars(g_AllChannels[i], ts_RSL_ChanMode_SIGN));
		log(testcasename(), ": Starting for ", g_AllChannels[i]);
		vc_conn := f_start_handler(refers(f_TC_sacch_multi), pars);
		vc_conn.done;
	}
	/* TODO: do the above in parallel, rather than sequentially? */
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Test if SACH information is modified as expected */
private function f_TC_sacch_multi_chg(charstring id) runs on ConnHdlr {
	var octetstring si5 := f_rnd_octstring(19);
	var octetstring si6 := f_rnd_octstring(19);

	/* First, configure both SI5 and SI6 to be transmitted */
	RSL.send(ts_RSL_SACCH_FILL(RSL_SYSTEM_INFO_5, si5));
	RSL.send(ts_RSL_SACCH_FILL(RSL_SYSTEM_INFO_6, si6));

	f_l1_tune(L1CTL);
	RSL.clear;

	/* activate the logical channel */
	f_est_dchan();
	L1CTL.clear;

	/* check that SACCH actually are received as expected */
	f_sacch_present(si5);
	f_sacch_present(si6);

	/* disable SI6 */
	RSL.send(ts_RSL_SACCH_FILL(RSL_SYSTEM_INFO_6, ''O));

	/* check that SI5 is still transmitted */
	f_sacch_present(si5);
	/* check if SI6 is now gone */
	f_sacch_missing(si6);

	/* release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
}
testcase TC_sacch_multi_chg() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	for (var integer i := 0; i < sizeof(g_AllChannels); i := i+1) {
		pars := valueof(t_Pars(g_AllChannels[i], ts_RSL_ChanMode_SIGN));
		log(testcasename(), ": Starting for ", g_AllChannels[i]);
		vc_conn := f_start_handler(refers(f_TC_sacch_multi_chg), pars);
		vc_conn.done;
	}
	/* TODO: do the above in parallel, rather than sequentially? */
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Test for SACCH information present in RSL CHAN ACT (overrides FILLING) */
private function f_TC_sacch_chan_act(charstring id) runs on ConnHdlr {
	var octetstring si5 := f_rnd_octstring(19);
	var octetstring si6 := f_rnd_octstring(19);
	var octetstring si5_specific := f_rnd_octstring(19);
	var octetstring si6_specific := f_rnd_octstring(19);

	/* First, configure both SI5 and SI6 to be transmitted */
	RSL.send(ts_RSL_SACCH_FILL(RSL_SYSTEM_INFO_5, si5));
	RSL.send(ts_RSL_SACCH_FILL(RSL_SYSTEM_INFO_6, si6));

	f_l1_tune(L1CTL);
	RSL.clear;

	/* activate channel with different SACCH filling */
	var RSL_SacchInfo sacch_info := valueof(ts_RSL_SacchInfo({
				ts_RSL_SacchInfoElem(RSL_SYSTEM_INFO_5, si5_specific),
				ts_RSL_SacchInfoElem(RSL_SYSTEM_INFO_6, si6_specific)
				}));
	var RSL_IE_List addl_ies := { valueof(t_RSL_IE(RSL_IE_SACCH_INFO,
							RSL_IE_Body:{sacch_info := sacch_info})) };
	f_est_dchan(more_ies := addl_ies);

	/* check that SACCH actually are received as expected */
	f_sacch_present(si5_specific);
	f_sacch_present(si6_specific);

	/* release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
}
testcase TC_sacch_chan_act() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();

	for (var integer i := 0; i < sizeof(g_AllChannels); i := i+1) {
		pars := valueof(t_Pars(g_AllChannels[i], ts_RSL_ChanMode_SIGN));
		log(testcasename(), ": Starting for ", g_AllChannels[i]);
		vc_conn := f_start_handler(refers(f_TC_sacch_chan_act), pars);
		vc_conn.done;
	}
	/* TODO: do the above in parallel, rather than sequentially? */
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* verify that SACCH DL transmission is started only if MS power IE present
 * see section 4.1.3 of 3GPP TS 48.058 */
private function f_TC_sacch_chan_act_ho_async(charstring id) runs on ConnHdlr {
	var octetstring si5 := f_rnd_octstring(19);

	f_l1_tune(L1CTL);
	RSL.clear;

	/* Step 1: Activate ASYNC HO channel without MS power IE */

	/* Activate channel on BTS side */
	f_rsl_chan_act(g_pars.chan_mode, act_type := t_RSL_IE_ActType_HO_ASYNC);
	/* don't perform immediate assignment here, as we're testing non-IA case */
	/* enable dedicated mode */
	f_L1CTL_DM_EST_REQ(L1CTL, {false, mp_trx0_arfcn }, g_pars.chan_nr, 7);

	/* Verify that no DL SACCH is being received */
	f_sacch_missing(?);

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);


	/* Step 2: Activate ASYNC HO channel with MS power IE */

	/* Activate channel on BTS side */
	var RSL_IE_List addl_ies := {
		valueof(t_RSL_IE(RSL_IE_MS_POWER, RSL_IE_Body:{ms_power := ts_RSL_IE_MS_Power(0)}))
		};
	f_rsl_chan_act(g_pars.chan_mode, more_ies := addl_ies, act_type := t_RSL_IE_ActType_HO_ASYNC);
	/* don't perform immediate assignment here, as we're testing non-IA case */
	/* enable dedicated mode */
	f_L1CTL_DM_EST_REQ(L1CTL, {false, mp_trx0_arfcn }, g_pars.chan_nr, 7);

	/* Verify that DL SACCH is being received */
	f_sacch_present(si5);

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
}
testcase TC_sacch_chan_act_ho_async() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();

	for (var integer i := 0; i < sizeof(g_AllChannels); i := i+1) {
		pars := valueof(t_Pars(g_AllChannels[i], ts_RSL_ChanMode_SIGN));
		log(testcasename(), ": Starting for ", g_AllChannels[i]);
		vc_conn := f_start_handler(refers(f_TC_sacch_chan_act_ho_async), pars);
		vc_conn.done;
	}
	/* TODO: do the above in parallel, rather than sequentially? */
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* verify that SACCH DL transmission is started only if TA + MS power IEs present,
 * see section 4.1.4 of 3GPP TS 48.058 */
private function f_TC_sacch_chan_act_ho_sync(charstring id) runs on ConnHdlr {
	var octetstring si5 := f_rnd_octstring(19);
	var RSL_IE_List addl_ies;

	f_l1_tune(L1CTL);
	RSL.clear;

	/* Step 1: Activate SYNC HO channel without MS power IE */

	/* Activate channel on BTS side */
	f_rsl_chan_act(g_pars.chan_mode, act_type := t_RSL_IE_ActType_HO_SYNC);
	/* don't perform immediate assignment here, as we're testing non-IA case */
	/* enable dedicated mode */
	f_L1CTL_DM_EST_REQ(L1CTL, {false, mp_trx0_arfcn }, g_pars.chan_nr, 7);

	/* Verify that no DL SACCH is being received */
	f_sacch_missing(?);

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);


	/* Step 2a: Activate SYNC HO channel with only MS power IE */

	/* Activate channel on BTS side */
	addl_ies := {
		valueof(t_RSL_IE(RSL_IE_MS_POWER, RSL_IE_Body:{ms_power := ts_RSL_IE_MS_Power(0)}))
		};
	f_rsl_chan_act(g_pars.chan_mode, more_ies := addl_ies, act_type := t_RSL_IE_ActType_HO_SYNC);
	/* don't perform immediate assignment here, as we're testing non-IA case */
	/* enable dedicated mode */
	f_L1CTL_DM_EST_REQ(L1CTL, {false, mp_trx0_arfcn }, g_pars.chan_nr, 7);

	/* Verify that no DL SACCH is being received */
	f_sacch_missing(?);

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);


	/* Step 2b: Activate SYNC HO channel with TA IE */

	/* Activate channel on BTS side */
	addl_ies := {
		valueof(t_RSL_IE(RSL_IE_TIMING_ADVANCE, RSL_IE_Body:{timing_adv := 0}))
		};
	f_rsl_chan_act(g_pars.chan_mode, more_ies := addl_ies, act_type := t_RSL_IE_ActType_HO_SYNC);
	/* don't perform immediate assignment here, as we're testing non-IA case */
	/* enable dedicated mode */
	f_L1CTL_DM_EST_REQ(L1CTL, {false, mp_trx0_arfcn }, g_pars.chan_nr, 7);

	/* Verify that no DL SACCH is being received */
	f_sacch_missing(?);

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);


	/* Step 3: Activate SYNC HO channel with MS power IE and TA IE */

	/* Activate channel on BTS side */
	addl_ies := {
		valueof(t_RSL_IE(RSL_IE_TIMING_ADVANCE, RSL_IE_Body:{timing_adv := 0})),
		valueof(t_RSL_IE(RSL_IE_MS_POWER, RSL_IE_Body:{ms_power := ts_RSL_IE_MS_Power(0)}))
		};
	f_rsl_chan_act(g_pars.chan_mode, more_ies := addl_ies, act_type := t_RSL_IE_ActType_HO_SYNC);
	/* don't perform immediate assignment here, as we're testing non-IA case */
	/* enable dedicated mode */
	f_L1CTL_DM_EST_REQ(L1CTL, {false, mp_trx0_arfcn }, g_pars.chan_nr, 7);

	/* Verify that DL SACCH is being received */
	f_sacch_present(si5);

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
}
testcase TC_sacch_chan_act_ho_sync() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();

	for (var integer i := 0; i < sizeof(g_AllChannels); i := i+1) {
		pars := valueof(t_Pars(g_AllChannels[i], ts_RSL_ChanMode_SIGN));
		log(testcasename(), ": Starting for ", g_AllChannels[i]);
		vc_conn := f_start_handler(refers(f_TC_sacch_chan_act_ho_sync), pars);
		vc_conn.done;
	}
	/* TODO: do the above in parallel, rather than sequentially? */
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}


/***********************************************************************
 * RACH Handling
 ***********************************************************************/

/* like L1SAP_IS_PACKET_RACH */
private function ra_is_ps(OCT1 ra) return boolean {
	if ((ra and4b 'F0'O == '70'O) and (ra and4b '0F'O != '0F'O)) {
		return true;
	}
	return false;
}

/* generate a random RACH for circuit-switched */
private function f_rnd_ra_cs() return OCT1 {
	var OCT1 ra;
	do {
		ra := f_rnd_octstring(1);
	} while (ra_is_ps(ra));
	return ra;
}

/* generate a random RACH for packet-switched */
private function f_rnd_ra_ps() return OCT1 {
	var OCT1 ra;
	do {
		ra := f_rnd_octstring(1);
	} while (not ra_is_ps(ra));
	return ra;
}

/* generate a random 11-bit RA (packet-switched only) */
private function f_rnd_ra11_ps() return BIT11 {
	var integer ra11 := f_rnd_int(bit2int('11111111111'B));
	return int2bit(ra11, 11);
}

/* Send 1000 RACH requests and check their RA+FN on the RSL side */
testcase TC_rach_content() runs on test_CT {
	f_init();
	f_init_l1ctl();
	f_l1_tune(L1CTL);

	var GsmFrameNumber fn_last := 0;
	var boolean test_failed := false;
	for (var integer i := 0; i < 1000; i := i+1) {
		var OCT1 ra := f_rnd_ra_cs();
		var GsmFrameNumber fn := f_L1CTL_RACH(L1CTL, oct2int(ra));
		if (fn == fn_last) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Two RACH in same FN?!?");
		}
		fn_last := fn;

		timer T := 5.0;
		T.start;
		alt {
		[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_CHAN_RQD(ra, fn, t_RslChanNr_RACH(0)))) {
			T.stop;
			}
		[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_CHAN_RQD(?, ?, ?, ?))) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unexpected CHAN RQD");
			}
		[] RSL_CCHAN.receive { repeat; }
		[] T.timeout {
			test_failed := true;
			log("[", i, "] Timeout waiting for CHAN RQD FN=", fn, " RA=", ra);
			}
		}
	}
	if (test_failed) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Some out of 1000 RACH requests timed out"));
	}
	setverdict(pass);
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Send 1000 RACH Requests (flood ~ 89/s) and count if count(Abis) == count(Um) */
testcase TC_rach_count() runs on test_CT {
	f_init();
	f_init_l1ctl();
	f_sleep(1.0);
	f_l1_tune(L1CTL);

	var GsmFrameNumber fn_last := 0;
	for (var integer i := 0; i < 1000; i := i+1) {
		var OCT1 ra := f_rnd_ra_cs();
		var GsmFrameNumber fn := f_L1CTL_RACH(L1CTL, oct2int(ra));
		if (fn == fn_last) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Two RACH in same FN?!?");
		}
		fn_last := fn;
	}
	var integer rsl_chrqd := 0;
	timer T := 3.0;
	T.start;
	alt {
	[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_CHAN_RQD(?,?))) {
		rsl_chrqd := rsl_chrqd + 1;
		f_timer_safe_restart(T);
		repeat;
		}
	[] RSL_CCHAN.receive { repeat; }
	[] T.timeout { }
	}
	if (rsl_chrqd == 1000) {
		setverdict(pass);
	} else {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Received only ", rsl_chrqd, " out of 1000 RACH"));
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

private function f_vty_load_ind_thresh(integer period := 10, integer bts_nr := 0) runs on test_CT {
	var charstring bts_str := "bts " & int2str(bts_nr);
	f_vty_config2(BSCVTY, {"network", bts_str}, "ccch load-indication-threshold " & int2str(period));
}

/* empirical value: Number of RACH slots per reporting interval (1s) on combined CCCH */
private template integer tr_rach_slots_per_interval := (90 .. 130);

/* Expect 0 RACH load on an idle BTS that has just started up */
testcase TC_rach_load_idle_thresh0() runs on test_CT {
	var ASP_RSL_Unitdata rx_ud;

	f_init_vty_bsc();
	/* send load indications even at 0% load */
	f_vty_load_ind_thresh(0);
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");
	f_sleep(2.0);

	f_init();

	timer T := 5.0;
	T.start;
	alt {
	[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_RACH_LOAD_IND(tr_rach_slots_per_interval, 0, 0))) {
		setverdict(pass);
		repeat;
		}
	[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_RACH_LOAD_IND(?, ?, ?))) -> value rx_ud {
		setverdict(fail, "Unexpected RACH LOAD IND: ", rx_ud);
		repeat;
		}
	[] RSL_CCHAN.receive {
		repeat;
		}
	[] T.timeout { }
	}

	f_vty_load_ind_thresh(10);
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Expect no RACH load indications on an idle BTS that has just started up (default threshold 10%) */
testcase TC_rach_load_idle_below_thresh() runs on test_CT {
	var ASP_RSL_Unitdata rx_ud;

	f_init_vty_bsc();
	f_init();

	timer T := 5.0;
	T.start;
	alt {
	[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_RACH_LOAD_IND(?, ?, ?))) -> value rx_ud {
		setverdict(fail, "Unexpected RACH LOAD IND: ", rx_ud);
		repeat;
		}
	[] RSL_CCHAN.receive {
		repeat;
		}
	[] T.timeout {
		setverdict(pass);
		}
	}

	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Expect 0 RACH load on an idle BTS that has just started up */
testcase TC_rach_load_count() runs on test_CT {
	var ASP_RSL_Unitdata rx_ud;
	var integer load_access_count := 0;

	f_init_vty_bsc();
	/* send load indications even at 0% load */
	f_vty_load_ind_thresh(0);
	f_vty_transceive(BSCVTY, "drop bts connection 0 oml");
	f_sleep(2.0);
	f_init();

	f_init_l1ctl();
	f_sleep(1.0);
	f_l1_tune(L1CTL);

	var GsmFrameNumber fn_last := 0;
	for (var integer i := 0; i < 1000; i := i+1) {
		var OCT1 ra := f_rnd_ra_cs();
		var GsmFrameNumber fn := f_L1CTL_RACH(L1CTL, oct2int(ra));
		if (fn == fn_last) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Two RACH in same FN?!?");
		}
		fn_last := fn;
	}

	timer T := 5.0;
	T.start;
	alt {
	[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_RACH_LOAD_IND(tr_rach_slots_per_interval, ?, ?)))
										-> value rx_ud {
		var RSL_IE_Body ie;
		f_rsl_find_ie(rx_ud.rsl, RSL_IE_RACH_LOAD, ie);
		load_access_count := load_access_count + ie.rach_load.access_count;
		if (ie.rach_load.busy_count < ie.rach_load.access_count) {
			setverdict(fail, "Access count cannot be < Busy count");
		}
		repeat;
		}
	[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_RACH_LOAD_IND(?, ?, ?))) -> value rx_ud {
		setverdict(fail, "Unexpected RACH LOAD IND: ", rx_ud);
		repeat;
		}
	[] RSL_CCHAN.receive {
		repeat;
		}
	[] T.timeout { }
	}
	if (load_access_count == 1000) {
		setverdict(pass);
	} else {
		setverdict(fail, "Load reports state ", load_access_count, " RACH, but we sent 1000");
	}

	f_vty_load_ind_thresh(10);
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

private function f_rach_toffs(int16_t toffs256, boolean expect_pass) runs on test_CT {
	var TrxcMessage ret;
	/* tell fake_trx to use a given timing offset for all bursts */
	ret := f_TRXC_transceive(BTS_TRXC, g_bts_trxc_conn_id, valueof(ts_TRXC_FAKE_TIMING(toffs256)));
	f_sleep(0.5);

	/* Transmit RACH request + wait for confirmation */
	var OCT1 ra := f_rnd_ra_cs();
	var GsmFrameNumber fn := f_L1CTL_RACH(L1CTL, oct2int(ra));

	/* Check for expected result */
	timer T := 1.5;
	T.start;
	alt {
	[expect_pass] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_CHAN_RQD(ra, fn))) {
		setverdict(pass);
		}
	[not expect_pass] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_CHAN_RQD(ra, fn))) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("RACH passed but was expected to be dropped: ", toffs256));
		}
	[] RSL_CCHAN.receive { repeat; }
	[not expect_pass] T.timeout {
		setverdict(pass);
		}
	[expect_pass] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Timeout waiting for CHAN RQD: FN=", fn, " RA=", ra));
		}
	}
}

/* Test if dropping of RACH Based on NM_ATT_MAX_TA works */
testcase TC_rach_max_ta() runs on test_CT {
	f_init();
	f_init_l1ctl();
	f_l1_tune(L1CTL);
	f_sleep(1.0);

	/* default max-ta is 63 (full range of GSM timing advance */

	/* We allow early arrival up to 2 symbols */
	f_rach_toffs(-1*256, true);
	f_rach_toffs(-2*256, true);
	f_rach_toffs(-10*256, false);

	/* 0 / 32 / 63 bits is legal / permitted */
	f_rach_toffs(0, true);
	f_rach_toffs(32*256, true);
	f_rach_toffs(63*256, true);

	/* more than 63 bits is not legal / permitted */
	f_rach_toffs(64*256, false);
	f_rach_toffs(127*256, false);
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

function f_TC_ho_rach(charstring id) runs on ConnHdlr {
	var GsmFrameNumber fn;
	var RSL_Message rm;

	f_l1_tune(L1CTL);
	RSL.clear;

	/* Generate a random Handover Reference */
	var integer ho_ref := oct2int(f_rnd_octstring(1));

	/* Handover Reference IE (see 3GPP TS 48.058, 9.3.9) */
	var RSL_IE ho_ref_ie := valueof(t_RSL_IE(RSL_IE_HANDO_REF,
					RSL_IE_Body:{ handover_ref := ho_ref }));

	/* Activate a channel on the BTS side (no encryption) */
	f_rsl_chan_act(g_pars.chan_mode, more_ies := { ho_ref_ie },
		       act_type := t_RSL_IE_ActType_HO_SYNC);

	/* Switch the MS side (e.g. trxcon) to a dedicated channel without
	 * waiting for Immediate Assignment and sending Access Burst */
	f_L1CTL_DM_EST_REQ(L1CTL, { false, mp_trx0_arfcn }, g_pars.chan_nr, 7);

	/* Send handover Access Burst */
	fn := f_L1CTL_RACH(L1CTL, ho_ref, chan_nr := g_pars.chan_nr);

	/* TODO: test mismatching Handover Reference, and missing IE */

	/* Wait for handover detection */
	timer T := 3.0;
	T.start;
	alt {
	[] RSL.receive(tr_RSL_HANDO_DET(g_pars.chan_nr)) -> value rm {
		log("Handover RACH has been detected: ", rm);
		setverdict(pass);
		}
	[] RSL.receive(tr_RSL_CHAN_RQD(?, ?, ?, ?)) -> value rm {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			log2str("RSL_CHAN_RQD was not expected: ", rm));
		}
	[] RSL.receive { repeat; }
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			log2str("Timeout waiting for handover RACH: FN=", fn, " RA=", ho_ref));
		}
	}

	/* Release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
}

/* Test handover RACH detection */
testcase TC_ho_rach() runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;

	f_init();

	for (var integer i := 0; i < sizeof(g_AllChannels); i := i + 1) {
		pars := valueof(t_Pars(g_AllChannels[i], ts_RSL_ChanMode_SIGN));
		log(testcasename(), ": Starting for ", g_AllChannels[i]);
		vc_conn := f_start_handler(refers(f_TC_ho_rach), pars);
		vc_conn.done;
	}

	/* TODO: do the above in parallel, rather than sequentially? */
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/***********************************************************************
 * Measurement Processing / Reporting
 ***********************************************************************/

template LapdmAddressField ts_LapdmAddr(LapdmSapi sapi, boolean c_r) := {
	spare := '0'B,
	lpd := 0,
	sapi := sapi,
	c_r := c_r,
	ea := true
}

template LapdmFrameAB ts_LAPDm_AB(LapdmSapi sapi, boolean c_r, boolean p, octetstring pl) := {
	addr := ts_LapdmAddr(sapi, c_r),
	ctrl := ts_LapdmCtrlUI(p),
	len := 0, /* overwritten */
	m := false,
	el := 1,
	payload := pl
}

/* handle incoming downlink SACCH and respond with uplink SACCH (meas res) */
altstep as_l1_sacch() runs on ConnHdlr {
	var L1ctlDlMessage l1_dl;
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(?))) -> value l1_dl {
		log("SACCH received: ", l1_dl.payload.data_ind.payload);
		var GsmRrL3Message meas_rep := valueof(ts_MEAS_REP(true, mp_rxlev_exp, mp_rxlev_exp, 0, 0, omit));
		var LapdmFrameAB lb := valueof(ts_LAPDm_AB(0, false, false, enc_GsmRrL3Message(meas_rep)));
		log("LAPDm: ", lb);

		var template (value) SacchL1Header l1h := ts_SacchL1Header(
			g_pars.l1_pars.ms_power_level, false,
			g_pars.l1_pars.ms_actual_ta);

		/* TODO: we can use an extension of TTCN-3 for that, i.e. PADDING('2B'O) */
		var octetstring l2 := f_pad_oct(enc_LapdmFrameAB(lb), 21, '2B'O);

		log("Sending Measurement Report: ", l1h, l2);
		L1CTL.send(ts_L1CTL_DATA_REQ_SACCH(g_chan_nr, ts_RslLinkID_SACCH(0), l1h, l2));
		repeat;
		}
}

altstep as_l1_dcch() runs on ConnHdlr {
	var L1ctlDlMessage l1_dl;
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_DCCH(?))) -> value l1_dl {
		log("DCCH received: ", l1_dl.payload.data_ind.payload);
		var octetstring pl := '010301'O;
		L1CTL.send(ts_L1CTL_DATA_REQ(g_chan_nr, ts_RslLinkID_DCCH(0),
			f_pad_oct(pl, 23, '2B'O)));
		repeat;
		}
}

type record MeasElem {
	uint6_t rxlev,
	uint3_t rxqual
}

type record MeasElemFS {
	MeasElem full,
	MeasElem sub
}

type record ConnL1Pars {
	boolean dtx_enabled,
	boolean toa256_enabled,
	MeasElemFS meas_ul,
	int16_t timing_offset_256syms,
	uint5_t bs_power_level,
	uint5_t ms_power_level,
	uint8_t ms_actual_ta
}

/* Convert tiing offset from 1/256th symbol to RSL Timing Offset */
private function toffs256s_to_rsl(int16_t toffs256s) return uint8_t {
	return 63 + (toffs256s/256);
}

private function f_max(integer a, integer b) return integer {
	if (a > b) {
		return a;
	} else {
		return b;
	}
}

private function f_min(integer a, integer b) return integer {
	if (a < b) {
		return a;
	} else {
		return b;
	}
}

/* compute negative tolerance val-tolerance, ensure >= min */
private function f_tolerance_neg(integer val, integer min, integer tolerance) return integer {
	val := val - tolerance;
	return f_max(val, min);
}

/* compute positive tolerance val+tolerance, ensure <= max */
private function f_tolerance_pos(integer val, integer max, integer tolerance) return integer {
	val := val + tolerance;
	return f_min(val, max);
}

/* return a template of (val-tolerance .. val+tolerance) ensuring it is within (min .. max) */
private function f_tolerance(integer val, integer min, integer max, integer tolerance)
return template integer {
	var template integer ret;
	ret := (f_tolerance_neg(val, min, tolerance) .. f_tolerance_pos(val, max, tolerance));
	return ret;
}


/* build a template for matching measurement results against */
private function f_build_meas_res_tmpl() runs on ConnHdlr return template RSL_Message {
	var ConnL1Pars l1p := g_pars.l1_pars;
	var template RSL_IE_UplinkMeas ul_meas := {
		len := 3,
		rfu := '0'B,
		dtx_d := l1p.dtx_enabled,
		rxlev_f_u := f_tolerance(l1p.meas_ul.full.rxlev, 0, 63, mp_tolerance_rxlev),
		reserved1 := '00'B,
		rxlev_s_u := f_tolerance(l1p.meas_ul.sub.rxlev, 0, 63, mp_tolerance_rxlev),
		reserved2 := '00'B,
		rxq_f_u := f_tolerance(l1p.meas_ul.full.rxqual, 0, 7, mp_tolerance_rxqual),
		rxq_s_u := f_tolerance(l1p.meas_ul.sub.rxqual, 0, 7, mp_tolerance_rxqual),
		supp_meas_info := omit
	};
	if (l1p.toa256_enabled) {
		ul_meas.len := (3+8);
		ul_meas.supp_meas_info := {
			toa256_mean := f_tolerance(l1p.timing_offset_256syms, -63*256, 192*256, mp_tolerance_timing_offset_256syms),
			toa256_min := ?,
			toa256_max := ?,
			toa256_std_dev := ?
		}
	}
	var template RSL_IE_BS_Power bs_power := {
		reserved := 0,
		epc := false,
		fpc := false,
		power_level := l1p.bs_power_level
	};
	var template RSL_IE_L1Info l1_info := {
		ms_power_lvl := l1p.ms_power_level,
		fpc := false,
		reserved := 0,
		actual_ta := f_tolerance(l1p.ms_actual_ta, 0, 63, mp_tolerance_timing_offset_256syms/256)
	};
	var uint8_t offs := toffs256s_to_rsl(l1p.timing_offset_256syms);
	var template uint8_t t_toffs := f_tolerance(offs, 0, 255, mp_tolerance_timing_offset_256syms/256);
	return tr_RSL_MEAS_RES_OSMO(g_chan_nr, g_next_meas_res_nr, ul_meas, bs_power, l1_info,
				    ?, t_toffs);
}

/* verify we regularly receive measurement reports with incrementing numbers */
altstep as_meas_res(boolean verify_meas := true) runs on ConnHdlr {
	var RSL_Message rsl;
	[not verify_meas] RSL.receive(tr_RSL_MEAS_RES(?)) { repeat; }
	[] RSL.receive(f_build_meas_res_tmpl()) -> value rsl {
		/* increment counter of next to-be-expected meas rep */
		g_next_meas_res_nr := (g_next_meas_res_nr + 1) mod 256;
		/* Re-start the timer expecting the next MEAS RES */
		f_timer_safe_restart(g_Tmeas_exp);
		repeat;
		}
	[] RSL.receive(tr_RSL_MEAS_RES(g_chan_nr, g_next_meas_res_nr)) -> value rsl {
		/* increment counter of next to-be-expected meas rep */
		g_next_meas_res_nr := (g_next_meas_res_nr + 1) mod 256;
		if (g_first_meas_res) {
			g_first_meas_res := false;
			repeat;
		} else {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Received unspecific MEAS RES ", rsl));
		}
		}
	[] RSL.receive(tr_RSL_MEAS_RES(?)) -> value rsl {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Received unexpected MEAS RES ", rsl));
		}
	[g_Tmeas_exp.running] g_Tmeas_exp.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Didn't receive expected measurement result")
		}
}

private function f_alg_id_to_l1ctl(RSL_AlgId rsl_alg_id) return uint8_t {
	select (rsl_alg_id) {
	case (RSL_ALG_ID_A5_0) { return 0; }
	case (RSL_ALG_ID_A5_1) { return 1; }
	case (RSL_ALG_ID_A5_2) { return 2; }
	case (RSL_ALG_ID_A5_3) { return 3; }
	case (RSL_ALG_ID_A5_4) { return 4; }
	case (RSL_ALG_ID_A5_5) { return 5; }
	case (RSL_ALG_ID_A5_6) { return 6; }
	case (RSL_ALG_ID_A5_7) { return 7; }
	case else {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unknwon Algorithm ID");
		/* Make compiler happy by calling mtc.stop here. It is already
		 * called in f_shutdown */
		mtc.stop;
		}
	}
}

private function f_alg_id_to_l3(RSL_AlgId rsl_alg_id) return BIT3 {
	select (rsl_alg_id) {
	case (RSL_ALG_ID_A5_1) { return '000'B; }
	case (RSL_ALG_ID_A5_2) { return '001'B; }
	case (RSL_ALG_ID_A5_3) { return '010'B; }
	case (RSL_ALG_ID_A5_4) { return '011'B; }
	case (RSL_ALG_ID_A5_5) { return '100'B; }
	case (RSL_ALG_ID_A5_6) { return '101'B; }
	case (RSL_ALG_ID_A5_7) { return '110'B; }
	case else {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unknwon Algorithm ID");
		/* Make compiler happy by calling mtc.stop here. It is already
		 * called in f_shutdown */
		mtc.stop;
		}
	}
}

/* Send RACH request through l1CTL and wait for ChanReq on RSL BST->BSC */
private function f_rach_req_wait_chan_rqd(integer ra) runs on ConnHdlr return GsmFrameNumber {
	var GsmFrameNumber fn;
	timer T := 8.0;

	/* advertise to RSL Emulation that we expect to receive confirmation from RACH */
	RSL.send(ts_RSLDC_ChanRqd_anyFN(int2oct(ra,1)));

	f_L1CTL_PARAM(L1CTL, g_pars.l1_pars.ms_actual_ta, g_pars.l1_pars.ms_power_level);
	/* Send the actual RACH */
	fn := f_L1CTL_RACH(L1CTL, ra);

	T.start;
	alt {
	[] RSL.receive(tr_RSL_CHAN_RQD(int2oct(ra,1), fn)) { setverdict(pass, "Received CHAN-RQD from RACH REQ") }
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Timeout waiting for CHAN-RQD from RACH REQ <", ra, ", ", fn, ">"));
		}
	}
	T.stop
	return fn;
}

/* Establish dedicated channel: L1CTL + RSL side */
private function f_est_dchan(boolean encr_enable := false, RSL_IE_List more_ies := {}) runs on ConnHdlr {
	var GsmFrameNumber fn;
	var ImmediateAssignment imm_ass;
	var integer ra := 23;

	/* Send RACH request and wait for ChanReq */
	fn := f_rach_req_wait_chan_rqd(ra);

	/* Activate channel on BTS side */
	f_rsl_chan_act(g_pars.chan_mode, encr_enable, more_ies);

	/* Send IMM.ASS via CCHAN */
	var ChannelDescription ch_desc := {
		chan_nr := g_pars.chan_nr,
		tsc := 7,
		h := false,
		arfcn := mp_trx0_arfcn,
		maio_hsn := omit
	};
	var MobileAllocation ma := {
		len := 0,
		ma := ''B
	};
	var GsmRrMessage rr_msg := valueof(ts_IMM_ASS(ra, fn, 0, ch_desc, ma));
	RSL.send(ts_RSL_IMM_ASSIGN(enc_GsmRrMessage(rr_msg)));

	/* receive IMM.ASS on MS side */
	var ImmediateAssignment ia_um;
	ia_um := f_L1CTL_WAIT_IMM_ASS(L1CTL, ra, fn);
	/* enable dedicated mode */
	f_L1CTL_DM_EST_REQ_IA(L1CTL, ia_um);
	/* enable encryption, if requested */
	if (encr_enable) {
		var uint8_t alg_id := f_alg_id_to_l1ctl(g_pars.encr.alg_id);
		f_L1CTL_CRYPTO_REQ(L1CTL, g_pars.chan_nr, alg_id, g_pars.encr.key);
	}

	g_first_meas_res := true;
}

/* establish DChan, verify existance + contents of measurement reports */
function f_TC_meas_res_periodic(charstring id) runs on ConnHdlr {
	f_l1_tune(L1CTL);
	RSL.clear;

	if (mp_bts_trxc_port != -1) {
		f_trxc_fake_rssi(rxlev2dbm(mp_ul_rxlev_exp));
		f_trxc_fake_toffs256(g_pars.l1_pars.timing_offset_256syms);
	}

	f_est_dchan();

	/* run for a number of seconds, send SACCH + FACCH from MS side and verify
	 * RSL measurement reports on Abis side */
	timer T := 8.0;
	T.start;
	alt {
	[] as_l1_sacch();
	[] as_meas_res();
	[] as_l1_dcch();
	[] L1CTL.receive { repeat; }
	[g_Tmeas_exp.running] T.timeout {
		/* as_meas_res() would have done Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail) in case
		 * of any earlier errors, so if we reach this timeout, we're good */
		setverdict(pass);
		}
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "No MEAS RES received at all");
		}
	}
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
}

function f_check_meas_bs_power_level(integer level) runs on ConnHdlr {
	timer T := 8.0;
	T.start;
	var RSL_Message rsl;
	alt {
	[] as_l1_sacch();
	[] L1CTL.receive { repeat; }
	[] RSL.receive(tr_RSL_MEAS_RES(g_chan_nr, ?, ?, ?)) -> value rsl {
		if (rsl.ies[3].body.bs_power.power_level == level) {
			setverdict(pass)
		} else {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Received wrong BS power level in MEAS RES ", rsl));
		}
		}
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "No MEAS RES received at all");
		}
	}
}

/* see if the rsl meas res contains our expeced bs power level
bs power set during assignment */
function f_TC_rsl_bs_pwr_static_ass(charstring id) runs on ConnHdlr {
	f_l1_tune(L1CTL);
	RSL.clear;

	if (mp_bts_trxc_port != -1) {
		f_trxc_fake_rssi(rxlev2dbm(mp_ul_rxlev_exp));
		f_trxc_fake_toffs256(g_pars.l1_pars.timing_offset_256syms);
	}

	var uint5_t pwr_var := 1;
	var template (value) RSL_IE_BS_Power bs_power := ts_RSL_IE_BS_Power(pwr_var);
	var template (value) RSL_IE pwr := t_RSL_IE(RSL_IE_BS_POWER, RSL_IE_Body:{bs_power := bs_power});

	f_est_dchan(more_ies :={valueof(pwr)});

	f_check_meas_bs_power_level(pwr_var);

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
}

/* see if the rsl meas res contains our expeced bs power level
bs power set after assignment */
function f_TC_rsl_bs_pwr_static_power_control(charstring id) runs on ConnHdlr {
	f_l1_tune(L1CTL);
	RSL.clear;

	if (mp_bts_trxc_port != -1) {
		f_trxc_fake_rssi(rxlev2dbm(mp_ul_rxlev_exp));
		f_trxc_fake_toffs256(g_pars.l1_pars.timing_offset_256syms);
	}

	var uint5_t pwr_var := 1;
	var template (value) RSL_IE_BS_Power bs_power := ts_RSL_IE_BS_Power(pwr_var);

	f_est_dchan();

	RSL.send(ts_RSL_BS_PWR_CTRL(g_chan_nr, bs_power));

	f_check_meas_bs_power_level(pwr_var);

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
}

testcase TC_rsl_bs_pwr_static_ass() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	for (var integer tn := 1; tn <= 4; tn := tn+1) {
		pars := valueof(t_Pars(t_RslChanNr_Bm(tn), ts_RSL_ChanMode_SIGN));
		vc_conn := f_start_handler(refers(f_TC_rsl_bs_pwr_static_ass), pars,
					   pcu_comp := false, trxc_comp := true);
		vc_conn.done;
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_rsl_bs_pwr_static_power_control() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	for (var integer tn := 1; tn <= 4; tn := tn+1) {
		pars := valueof(t_Pars(t_RslChanNr_Bm(tn), ts_RSL_ChanMode_SIGN));
		vc_conn := f_start_handler(refers(f_TC_rsl_bs_pwr_static_power_control), pars,
					   pcu_comp := false, trxc_comp := true);
		vc_conn.done;
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* target level -100, first rssi -90, ms power 7, expected increase to 7+6 within 6 seconds,
second rssi -110, ms power 7+6, expected decrease to 7 within 6 seconds,
These power levels are valid for all bands and require no special handling */
function f_TC_rsl_ms_pwr_dyn_ass_updown(charstring id) runs on ConnHdlr {
	var uint5_t pwr_var := 7;
	var L1ctlDlMessage l1_dl;

	f_trxc_fake_rssi(rxlev2dbm(10));
	f_l1_tune(L1CTL);
	RSL.clear;

	var RSL_IE_List addl_ies;
	var template (value)  RSL_IE_MS_Power_Parameters pp := (ts_RSL_IE_MS_Power_Parameters(''O));

	addl_ies := {
		valueof(t_RSL_IE(RSL_IE_MS_POWER, RSL_IE_Body:{ms_power := ts_RSL_IE_MS_Power(pwr_var)})),
		valueof(t_RSL_IE(RSL_IE_MS_POWER_PARAM, RSL_IE_Body:{ms_power_params := pp}))
	};

	/* establish with power parameters */
	f_est_dchan(more_ies := addl_ies);

	/* set a high value to ensure L1 power control level increases */
	f_trxc_fake_rssi(rxlev2dbm(20));

	timer T2 := 6.0;
	T2.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(?))) -> value l1_dl {
		if( not(oct2int(l1_dl.payload.data_ind.payload[0]) > (pwr_var+6))){
			repeat;
			}
		T2.stop;
		}
	[] L1CTL.receive { repeat; }
	[] T2.timeout {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			"Power Level in L1 header has not increased sufficiently");
		}
	}

	/* set a low value to ensure L1 power control level decreases */
	f_trxc_fake_rssi(rxlev2dbm(0));

	timer T4 := 6.0;
	T4.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(?))) -> value l1_dl {
		if( not(oct2int(l1_dl.payload.data_ind.payload[0]) <= (pwr_var))){
			repeat;
			}
		T4.stop;
		setverdict(pass, "Power level in L1 decreased/increased as expected");
		}
	[] L1CTL.receive { repeat; }
	[] T4.timeout {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			"Power Level in L1 header has not decreased sufficiently");
		}
	}

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);

}

/* check that we do not exceed the max power */
function f_TC_rsl_ms_pwr_dyn_max(charstring id) runs on ConnHdlr {
	var uint5_t pwr_var := 7;
	var L1ctlDlMessage l1_dl;

	/* set a low value to ensure power increases */
	f_trxc_fake_rssi(rxlev2dbm(10));
	f_l1_tune(L1CTL);
	RSL.clear;

	var RSL_IE_List addl_ies;
	var template (value)  RSL_IE_MS_Power_Parameters pp := (ts_RSL_IE_MS_Power_Parameters(''O));

	addl_ies := {
		valueof(t_RSL_IE(RSL_IE_MS_POWER, RSL_IE_Body:{ms_power := ts_RSL_IE_MS_Power(pwr_var)})),
		valueof(t_RSL_IE(RSL_IE_MS_POWER_PARAM, RSL_IE_Body:{ms_power_params := pp}))
	};

	/* establish with power parameters */
	f_est_dchan(more_ies := addl_ies);

	timer T1 := 10.0;
	T1.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(?))) -> value l1_dl { repeat; }
	[] L1CTL.receive { repeat; }
	[] T1.timeout {
		if( oct2int(l1_dl.payload.data_ind.payload[0]) != pwr_var){
			setverdict(fail, "Power level in L1 header should not have changed");
		}
		}
	}

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);

}

/* see if we reach the band max power */
function f_TC_rsl_ms_pwr_dyn_up(charstring id) runs on ConnHdlr {
	var L1ctlDlMessage l1_dl;
	var uint5_t pwr_var := 15;
	var uint5_t pwr_max_var := f_get_max_power_from_band();

	/* set a low value to ensure power increases */
	f_trxc_fake_rssi(rxlev2dbm(10));
	f_l1_tune(L1CTL);
	RSL.clear;

	var template (value) RSL_IE_MS_Power ms_power := ts_RSL_IE_MS_Power(pwr_var);
	var template (value) RSL_IE pwr := t_RSL_IE(RSL_IE_MS_POWER, RSL_IE_Body:{ms_power := ms_power});

	/* establish with fixed power level */
	f_est_dchan(more_ies :={valueof(pwr)});

	/* check our initial power level */
	f_wait_for_l1_power_level(pwr_var);

	/* update power param to enable power loop
	48.058 The maximum power to be used is indicated in the BS and MS Power elements respectively. */
	RSL.send(ts_RSL_MS_PWR_CTRL_with_pp(g_chan_nr, pwr_max_var));

	/* wait, then check that our power level was reduced */
	timer T1 := 10.0;
	T1.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(?))) -> value l1_dl { repeat; }
	[] L1CTL.receive { repeat; }
	[] T1.timeout {
		var int8_t rcv := oct2int(l1_dl.payload.data_ind.payload[0]);
		if( f_power_level_is_highest_dbm(rcv) ){
			setverdict(pass, "Power level in L1 header reduced as expected");
		} else {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			log2str("Power Level in L1 header did not reach the expected value, e:",pwr_max_var," r:",rcv));
		}
		}
	}

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);

}

/* see if we reach the band min power */
function f_TC_rsl_ms_pwr_dyn_down(charstring id) runs on ConnHdlr {
	var L1ctlDlMessage l1_dl;

	/* set a high value to ensure power decreases */
	f_trxc_fake_rssi(rxlev2dbm(50));
	f_l1_tune(L1CTL);
	RSL.clear;

	var uint5_t pwr_var := 5;
	var uint5_t pwr_target_val := 15;

	var template (value) RSL_IE_MS_Power ms_power := ts_RSL_IE_MS_Power(pwr_var);
	var template (value) RSL_IE pwr := t_RSL_IE(RSL_IE_MS_POWER, RSL_IE_Body:{ms_power := ms_power});

	/* establish with fixed power level */
	f_est_dchan(more_ies :={valueof(pwr)});

	/* check our initial power level */
	f_wait_for_l1_power_level(pwr_var);

	/* update power param to enable power loop
	 as per spec the supplied ms power IE should set the max allowed power...*/
	RSL.send(ts_RSL_MS_PWR_CTRL_with_pp(g_chan_nr, pwr_var));

	/* wait, then check that our power level was increased */
	timer T1 := 10.0;
	T1.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(?))) -> value l1_dl { repeat; }
	[] L1CTL.receive { repeat; }
	[] T1.timeout {
		if( f_power_level_is_lowest_dbm(oct2int(l1_dl.payload.data_ind.payload[0])) ){
			setverdict(pass, "Power level in L1 header increased to lowest power value");
		} else {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			"Power level in L1 header NOT increased to lowest power value");
		}
		}
	}

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);

}

/* see if we change the power level without receiving power parameters, which should not happen
rsl chan act WITHOUT power parameters */
function f_TC_rsl_ms_pwr_dyn_active(charstring id) runs on ConnHdlr {
	var L1ctlDlMessage l1_dl;

	/* set a high value to ensure power decreases */
	f_trxc_fake_rssi(rxlev2dbm(50));
	f_l1_tune(L1CTL);
	RSL.clear;

	var uint5_t pwr_var := 5;

	var template (value) RSL_IE_MS_Power ms_power := ts_RSL_IE_MS_Power(pwr_var);
	var template (value) RSL_IE pwr := t_RSL_IE(RSL_IE_MS_POWER, RSL_IE_Body:{ms_power := ms_power});

	/* establish with fixed power level */
	f_est_dchan(more_ies :={valueof(pwr)});

	/* check our initial power level */
	f_wait_for_l1_power_level(pwr_var);

	/* wait, then check that our power level did not change */
	timer T1 := 10.0;
	T1.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(?))) -> value l1_dl {
		if ( oct2int(l1_dl.payload.data_ind.payload[0]) != pwr_var) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			"BS power control should not be active unless we receive a power parameters IE!");
		}
		repeat;
		}
	[] L1CTL.receive { repeat; }
	[] T1.timeout { setverdict(pass); }
	}

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);

}

/* see if we change the power level without receiving power parameters, which should not happen
ms power control WITHOUT power parameters */
function f_TC_rsl_ms_pwr_dyn_active2(charstring id) runs on ConnHdlr {
	var L1ctlDlMessage l1_dl;

	/* set a high value to ensure power decreases */
	f_trxc_fake_rssi(rxlev2dbm(50));
	f_l1_tune(L1CTL);
	RSL.clear;

	var uint5_t pwr_var := 5;

	var template (value) RSL_IE_MS_Power ms_power := ts_RSL_IE_MS_Power(pwr_var);
	var template (value) RSL_IE pwr := t_RSL_IE(RSL_IE_MS_POWER, RSL_IE_Body:{ms_power := ms_power});

	/* establish with fixed power level */
	f_est_dchan(more_ies :={valueof(pwr)});

	/* check our initial power level */
	f_wait_for_l1_power_level(pwr_var);

	/* pwr control without power params IE, should NOT activate MS power control*/
	RSL.send(ts_RSL_MS_PWR_CTRL(g_chan_nr, ms_power));

	/* wait, then check that our power level did not change */
	timer T1 := 10.0;
	T1.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(?))) -> value l1_dl {
		if ( oct2int(l1_dl.payload.data_ind.payload[0]) != pwr_var) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			"BS power control should not be active unless we receive a power parameters IE!");
		}
		repeat;
		}
	[] L1CTL.receive { repeat; }
	[] T1.timeout { setverdict(pass); }
	}

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);

}

function f_wait_for_l1_power_level(integer level) runs on ConnHdlr {
	var L1ctlDlMessage l1_dl;
	timer T0 := 10.0;
	T0.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(?))) -> value l1_dl {
		if (not (l1_dl.payload.data_ind.payload[0] == int2oct(level, 1))) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			"Power level in L1 header != signaled (RSL) power level.");
		}
		}
	[] L1CTL.receive { repeat; }
	[] T0.timeout {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			"Timeout waiting for initial power level");
		}
	}
	T0.stop;
}

private function f_power_level_is_lowest_dbm(integer level) runs on ConnHdlr return boolean  {
	var IntegerRecord min_dbm_level;
	var IntegerRecord max_dbm_level;
	var IntegerRecord x := f_power_from_band(g_pars.bts0_band, min_dbm_level, max_dbm_level);

	for (var integer i := 0; i < sizeof(min_dbm_level); i := i+1) {
		if (min_dbm_level[i] == level) {
			return true;
		}
	}
	return false;
}

private function f_power_level_is_highest_dbm(integer level) runs on ConnHdlr return boolean {
	var IntegerRecord min_dbm_level;
	var IntegerRecord max_dbm_level;
	var IntegerRecord x := f_power_from_band(g_pars.bts0_band, min_dbm_level, max_dbm_level);

	for (var integer i := 0; i < sizeof(max_dbm_level); i := i+1) {
		if (max_dbm_level[i] == level) {
			return true;
		}
	}
	return false;
}

private function f_get_max_power_from_band() runs on ConnHdlr return integer {
	var IntegerRecord min_dbm_level;
	var IntegerRecord max_dbm_level;
	var IntegerRecord x := f_power_from_band(g_pars.bts0_band, min_dbm_level, max_dbm_level);
	return max_dbm_level[0];
}

type charstring BtsBand ("GSM450","GSM480","GSM750","GSM810","GSM850","GSM900","DCS1800","PCS1900");
template charstring BtsBand_allGSM:= pattern "GSM???";
private function f_power_from_band(in BtsBand band, out IntegerRecord min_dbm_level, out IntegerRecord max_dbm_level) return IntegerRecord {
	// 45.005 4.1.1
	var IntegerRecord gsm_power :={31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19,
	 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3,
	 2, 1, 0};
	var IntegerRecord dcs_power :={28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15,
	 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 31, 30, 29};
	var IntegerRecord pcs_power :={15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 31, 30};
	var IntegerRecord rv;

	select(band){
	case (BtsBand_allGSM){
		rv := gsm_power;
		min_dbm_level := {31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19} ;
		max_dbm_level := {2, 1, 0};
	}
	case("DCS1800"){
		rv := dcs_power;
		min_dbm_level := {28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15};
		max_dbm_level := {0, 29}; // let's cheat here, assume MS_TXPWR_MAX_CCH might be being broadcast, so maybe no 29,30,31
	}
	case("PCS1900"){
		rv := pcs_power;
		min_dbm_level := {15};
		max_dbm_level := {30};
	}
	}

	return rv;
}

private function f_vty_get_bts0_band() runs on test_CT return BtsBand {
	return f_vty_transceive_match_regex(BTSVTY, "show bts 0", "BTS 0 is of \w+ type in band (\w+),*", 0);
}

testcase TC_rsl_ms_pwr_dyn_ass_updown() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	f_vty_config(BTSVTY, "phy 0", "osmotrx ms-power-loop -100");
	for (var integer tn := 1; tn <= 1; tn := tn+1) {
		pars := valueof(t_Pars(t_RslChanNr_Bm(tn), ts_RSL_ChanMode_SIGN));
		pars.bts0_band := f_vty_get_bts0_band();
		vc_conn := f_start_handler(refers(f_TC_rsl_ms_pwr_dyn_ass_updown), pars, trxc_comp := true);
		vc_conn.done;
	}
	f_vty_config(BTSVTY, "phy 0", "no osmotrx ms-power-loop");
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_rsl_ms_pwr_dyn_up() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	f_vty_config(BTSVTY, "phy 0", "osmotrx ms-power-loop -10");
	for (var integer tn := 1; tn <= 1; tn := tn+1) {
		pars := valueof(t_Pars(t_RslChanNr_Bm(tn), ts_RSL_ChanMode_SIGN));
		pars.bts0_band := f_vty_get_bts0_band();
		vc_conn := f_start_handler(refers(f_TC_rsl_ms_pwr_dyn_up), pars, trxc_comp := true);
		vc_conn.done;
	}
	f_vty_config(BTSVTY, "phy 0", "no osmotrx ms-power-loop");
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_rsl_ms_pwr_dyn_max() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	f_vty_config(BTSVTY, "phy 0", "osmotrx ms-power-loop -10");
	for (var integer tn := 1; tn <= 1; tn := tn+1) {
		pars := valueof(t_Pars(t_RslChanNr_Bm(tn), ts_RSL_ChanMode_SIGN));
		pars.bts0_band := f_vty_get_bts0_band();
		vc_conn := f_start_handler(refers(f_TC_rsl_ms_pwr_dyn_max), pars, trxc_comp := true);
		vc_conn.done;
	}
	f_vty_config(BTSVTY, "phy 0", "no osmotrx ms-power-loop");
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_rsl_ms_pwr_dyn_down() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	f_vty_config(BTSVTY, "phy 0", "osmotrx ms-power-loop -100");
	for (var integer tn := 1; tn <= 1; tn := tn+1) {
		pars := valueof(t_Pars(t_RslChanNr_Bm(tn), ts_RSL_ChanMode_SIGN));
		pars.bts0_band := f_vty_get_bts0_band();
		vc_conn := f_start_handler(refers(f_TC_rsl_ms_pwr_dyn_down), pars, trxc_comp := true);
		vc_conn.done;
	}
	f_vty_config(BTSVTY, "phy 0", "no osmotrx ms-power-loop");
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_rsl_ms_pwr_dyn_active() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	f_vty_config(BTSVTY, "phy 0", "osmotrx ms-power-loop -100");
	for (var integer tn := 1; tn <= 1; tn := tn+1) {
		pars := valueof(t_Pars(t_RslChanNr_Bm(tn), ts_RSL_ChanMode_SIGN));
		pars.bts0_band := f_vty_get_bts0_band();
		vc_conn := f_start_handler(refers(f_TC_rsl_ms_pwr_dyn_active), pars, trxc_comp := true);
		vc_conn.done;
	}
	f_vty_config(BTSVTY, "phy 0", "no osmotrx ms-power-loop");
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_rsl_ms_pwr_dyn_active2() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	f_vty_config(BTSVTY, "phy 0", "osmotrx ms-power-loop -100");
	for (var integer tn := 1; tn <= 1; tn := tn+1) {
		pars := valueof(t_Pars(t_RslChanNr_Bm(tn), ts_RSL_ChanMode_SIGN));
		pars.bts0_band := f_vty_get_bts0_band();
		vc_conn := f_start_handler(refers(f_TC_rsl_ms_pwr_dyn_active2), pars, trxc_comp := true);
		vc_conn.done;
	}
	f_vty_config(BTSVTY, "phy 0", "no osmotrx ms-power-loop");
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_meas_res_sign_tchf() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	for (var integer tn := 1; tn <= 4; tn := tn+1) {
		pars := valueof(t_Pars(t_RslChanNr_Bm(tn), ts_RSL_ChanMode_SIGN));
		vc_conn := f_start_handler(refers(f_TC_meas_res_periodic), pars,
					   pcu_comp := false, trxc_comp := true);
		vc_conn.done;
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}
testcase TC_meas_res_sign_tchh() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	for (var integer ss := 0; ss <= 1; ss := ss+1) {
		pars := valueof(t_Pars(t_RslChanNr_Lm(5, ss), ts_RSL_ChanMode_SIGN));
		vc_conn := f_start_handler(refers(f_TC_meas_res_periodic), pars,
					   pcu_comp := false, trxc_comp := true);
		vc_conn.done;
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}
testcase TC_meas_res_sign_sdcch4() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	for (var integer ss := 0; ss <= 3; ss := ss+1) {
		pars := valueof(t_Pars(t_RslChanNr_SDCCH4(0, ss), ts_RSL_ChanMode_SIGN));
		vc_conn := f_start_handler(refers(f_TC_meas_res_periodic), pars,
					   pcu_comp := false, trxc_comp := true);
		vc_conn.done;
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}
testcase TC_meas_res_sign_sdcch8() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	for (var integer ss := 0; ss <= 7; ss := ss+1) {
		pars := valueof(t_Pars(t_RslChanNr_SDCCH8(6, ss), ts_RSL_ChanMode_SIGN));
		vc_conn := f_start_handler(refers(f_TC_meas_res_periodic), pars,
					   pcu_comp := false, trxc_comp := true);
		vc_conn.done;
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}
testcase TC_meas_res_sign_tchh_toa256() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	f_vty_config(BTSVTY, "bts 0", "supp-meas-info toa256");
	for (var integer ss := 0; ss <= 1; ss := ss+1) {
		pars := valueof(t_Pars(t_RslChanNr_Lm(5, ss), ts_RSL_ChanMode_SIGN));
		pars.l1_pars.toa256_enabled := true;
		vc_conn := f_start_handler(refers(f_TC_meas_res_periodic), pars);
		vc_conn.done;
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* establish DChan, and send MS POWER CONTROL messages via RSL, verify that
 * the BTS is forwarding those values to the MS via the SACCH L1 header. */
function f_tc_rsl_ms_pwr_ctrl(charstring id) runs on ConnHdlr {
	var L1ctlDlMessage l1_dl;
	var RSL_IE_MS_Power ms_power;
	var RSL_Message rsl;
	var uint5_t power_level := 0;

	f_l1_tune(L1CTL);
	RSL.clear;

	f_est_dchan();

	ms_power.reserved := 0;
	ms_power.fpc_epc := false;

	/* Send the first power control command. This will disable any BTS/TRX
	 * internal power control and switch the MS (which is not in scope of
	 * this test) to a constant power level. We start with a power level
	 * of 0 */
	ms_power.power_level := power_level;
	rsl := valueof(ts_RSL_MS_PWR_CTRL(g_chan_nr, ms_power));
	RSL.send(rsl);

	alt {

	/* Pick all SACCH blocks for checking */
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(?))) -> value l1_dl {

		/* The first byte of the L1 header contains the power level.
		 * The reserved bits and the fpc bit is set to 0, so we may
		 * compare directly. */
		if (not (l1_dl.payload.data_ind.payload[0] == int2oct(power_level, 1))) {
			setverdict(fail, "Power level in L1 header does not match the signaled (RSL) power level.");
		}

		/* Signal a new power level via RSL for the next turn. */
		if (power_level < 31) {
			power_level := power_level + 1;
			ms_power.power_level := power_level;
			rsl := valueof(ts_RSL_MS_PWR_CTRL(g_chan_nr, ms_power));
			RSL.send(rsl);
			repeat;
		}

		}

	/* Ignore all other blocks */
	[] L1CTL.receive { repeat; }

	}

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);

	setverdict(pass);
}

testcase TC_rsl_ms_pwr_ctrl() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();

	for (var integer tn := 1; tn <= 4; tn := tn+1) {
		pars := valueof(t_Pars(t_RslChanNr_Bm(tn), ts_RSL_ChanMode_SIGN));
		vc_conn := f_start_handler(refers(f_tc_rsl_ms_pwr_ctrl), pars);
		vc_conn.done;
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* establish DChan, verify that the BTS sets the TA in the first SACCH L1 header. 
TA for the IMM ASS messages is still controlled by g_pars.l1_pars.ms_actual_ta! */
function f_tc_rsl_chan_initial_ta(charstring id) runs on ConnHdlr {
	var L1ctlDlMessage l1_dl;
	var uint5_t ta_to_test := 16;


	f_l1_tune(L1CTL);
	RSL.clear;

	/* tell fake_trx to use a given timing offset for all bursts */
	f_trxc_fake_toffs256(ta_to_test*256);

	f_est_dchan(more_ies :={valueof(t_RSL_IE(RSL_IE_TIMING_ADVANCE, RSL_IE_Body:{timing_adv := ta_to_test}))} );


	alt {

	/* Pick all SACCH blocks for checking */
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(?))) -> value l1_dl {

		/* The second byte of the L1 header contains the TA. */
		if (not (l1_dl.payload.data_ind.payload[1] == int2oct(ta_to_test, 1))) {
			setverdict(fail, "TA in L1 header does not match the signaled (RSL) TA.");
		}

		}

	/* Ignore all other blocks */
	[] L1CTL.receive { repeat; }

	}

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);

	setverdict(pass);
}

testcase TC_rsl_chan_initial_ta() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_tc_rsl_chan_initial_ta), pars,
				   pcu_comp := false, trxc_comp := true);
	vc_conn.done;
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* establish DChan, verify that the BTS sets MS power in the first SACCH L1 header. */
function f_tc_rsl_chan_initial_ms_pwr(charstring id) runs on ConnHdlr {
	var L1ctlDlMessage l1_dl;
	var uint5_t ms_power_level := 7;

	var RSL_IE_MS_Power ms_power;
	ms_power.reserved := 0;
	ms_power.fpc_epc := false;
	ms_power.power_level := ms_power_level;

	f_l1_tune(L1CTL);
	RSL.clear;

	f_est_dchan(more_ies :={valueof(t_RSL_IE(RSL_IE_MS_POWER, RSL_IE_Body:{ms_power := ms_power}))} );

	timer T := 1.0;
	T.start;
	alt {
	/* Pick all SACCH blocks for checking */
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, tr_RslLinkID_SACCH(?))) -> value l1_dl {
		/* The first byte of the L1 header contains the power level.. */
		if (not (l1_dl.payload.data_ind.payload[0] == int2oct(ms_power_level, 1))) {
			setverdict(fail, "Power Level in L1 header does not match the signaled (RSL) MS Power Level.");
		}
		}
	/* Ignore all other blocks */
	[] L1CTL.receive { repeat; }
	[] T.timeout {
		setverdict(fail, "Power Level in L1 header does not match the signaled (RSL) MS Power Level.");
		}
	}

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
	setverdict(pass);
}

testcase TC_rsl_chan_initial_ms_pwr() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	f_testmatrix_each_chan(pars, refers(f_tc_rsl_chan_initial_ms_pwr));
}

/* Test if a channel without valid uplink bursts generates RSL CONN FAIL IND (TS 48.058 4.10) */
private function f_TC_conn_fail_crit(charstring id) runs on ConnHdlr {
	f_l1_tune(L1CTL);
	RSL.clear;

	f_est_dchan();
	f_sleep(2.0);
	L1CTL.send(ts_L1CTL_DM_REL_REQ(g_chan_nr));

	timer T := 40.0;
	T.start;
	alt {
	[] RSL.receive(tr_RSL_CONN_FAIL_IND(g_chan_nr, ?)) {
		setverdict(pass)
		}
	[] RSL.receive { repeat };
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "No CONN FAIL IND received");
		}
	}
	f_rsl_chan_deact();
}
testcase TC_conn_fail_crit() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	f_init();
	pars := valueof(t_Pars(t_RslChanNr_SDCCH8(6, 3), ts_RSL_ChanMode_SIGN));
	pars.t_guard := 60.0;
	vc_conn := f_start_handler(refers(f_TC_conn_fail_crit), pars);
	vc_conn.done;
}

/***********************************************************************
 * Paging
 ***********************************************************************/

function tmsi_is_dummy(TMSIP_TMSI_V tmsi) return boolean {
	if (tmsi == 'FFFFFFFF'O) {
		return true;
	} else {
		return false;
	}
}

type record allowedFn { integer frame_nr }
template allowedFn bs_ag_blks_res_0  := { frame_nr := (6, 12, 16, 22, 26, 32, 36, 42, 46) }
template allowedFn bs_ag_blks_res_1  := { frame_nr := (12, 16, 22, 26, 32, 36, 42, 46) }
template allowedFn bs_ag_blks_res_2  := { frame_nr := (16, 22, 26, 32, 36, 42, 46) }
template allowedFn bs_ag_blks_res_3  := { frame_nr := (22, 26, 32, 36, 42, 46) }
template allowedFn bs_ag_blks_res_4  := { frame_nr := (26, 32, 36, 42, 46) }
template allowedFn bs_ag_blks_res_5  := { frame_nr := (32, 36, 42, 46) }
template allowedFn bs_ag_blks_res_6  := { frame_nr := (36, 42, 46) }
template allowedFn bs_ag_blks_res_7  := { frame_nr := (42, 46) }
function check_pch_fn(integer frame_nr, integer bs_ag_blks_res) runs on test_CT
{
	var integer frame_nr_51;
	frame_nr_51 := frame_nr mod 51

	var allowedFn fn_check;
	fn_check.frame_nr := frame_nr_51;

	if (bs_ag_blks_res < 0 or bs_ag_blks_res > 7) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "bs_ag_blks_res out of valid range (0..7)");
		return;
	}

	if (bs_ag_blks_res == 0 and match(fn_check, bs_ag_blks_res_0)) {
		return;
	}
	if (bs_ag_blks_res == 1 and match(fn_check, bs_ag_blks_res_1)) {
		return;
	}
	if (bs_ag_blks_res == 2 and match(fn_check, bs_ag_blks_res_2)) {
		return;
	}
	if (bs_ag_blks_res == 3 and match(fn_check, bs_ag_blks_res_3)) {
		return;
	}
	if (bs_ag_blks_res == 4 and match(fn_check, bs_ag_blks_res_4)) {
		return;
	}
	if (bs_ag_blks_res == 5 and match(fn_check, bs_ag_blks_res_5)) {
		return;
	}
	if (bs_ag_blks_res == 6 and match(fn_check, bs_ag_blks_res_6)) {
		return;
	}
	if (bs_ag_blks_res == 7 and match(fn_check, bs_ag_blks_res_7)) {
		return;
	}

	Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "received paging on AGCH");
	return;
}

altstep as_l1_count_paging(inout integer num_paging_rcv_msgs, inout integer num_paging_rcv_ids, PagingTestCfg cfg)
runs on test_CT {
	var L1ctlDlMessage dl;
	[] L1CTL.receive(tr_L1CTL_DATA_IND(t_RslChanNr_PCH_AGCH(0), ?, c_DummyUI)) {
		repeat;
	}
	[] L1CTL.receive(tr_L1CTL_DATA_IND(t_RslChanNr_PCH_AGCH(0))) -> value dl {
		var octetstring without_plen :=
			substr(dl.payload.data_ind.payload, 1, lengthof(dl.payload.data_ind.payload)-1);
		var PDU_ML3_NW_MS rr := dec_PDU_ML3_NW_MS(without_plen);

		check_pch_fn(dl.dl_info.frame_nr, cfg.bs_ag_blks_res);

		if (match(rr, tr_PAGING_REQ1)) {
			num_paging_rcv_msgs := num_paging_rcv_msgs + 1;
			num_paging_rcv_ids := num_paging_rcv_ids + 1;
			if (isvalue(rr.msgs.rrm.pagingReq_Type1.mobileIdentity2)) {
				num_paging_rcv_ids := num_paging_rcv_ids + 1;
			}
		} else if (match(rr, tr_PAGING_REQ2)) {
			num_paging_rcv_msgs := num_paging_rcv_msgs + 1;
			if (not tmsi_is_dummy(rr.msgs.rrm.pagingReq_Type2.mobileIdentity1)) {
				num_paging_rcv_ids := num_paging_rcv_ids + 1;
			}
			if (not tmsi_is_dummy(rr.msgs.rrm.pagingReq_Type2.mobileIdentity2)) {
				num_paging_rcv_ids := num_paging_rcv_ids + 1;
			}
			if (isvalue(rr.msgs.rrm.pagingReq_Type2.mobileIdentity3)) {
				num_paging_rcv_ids := num_paging_rcv_ids + 1;
			}
		} else if (match(rr, tr_PAGING_REQ3)) {
			num_paging_rcv_msgs := num_paging_rcv_msgs + 1;
			if (not tmsi_is_dummy(rr.msgs.rrm.pagingReq_Type3.mobileIdentity1)) {
				num_paging_rcv_ids := num_paging_rcv_ids + 1;
			}
			if (not tmsi_is_dummy(rr.msgs.rrm.pagingReq_Type3.mobileIdentity2)) {
				num_paging_rcv_ids := num_paging_rcv_ids + 1;
			}
			if (not tmsi_is_dummy(rr.msgs.rrm.pagingReq_Type3.mobileIdentity3)) {
				num_paging_rcv_ids := num_paging_rcv_ids + 1;
			}
			if (not tmsi_is_dummy(rr.msgs.rrm.pagingReq_Type3.mobileIdentity4)) {
				num_paging_rcv_ids := num_paging_rcv_ids + 1;
			}
		}
		repeat;
	}
}

type record PagingTestCfg {
	boolean combined_ccch,
	integer bs_ag_blks_res,
	float load_factor,
	boolean exp_load_ind,
	boolean exp_overload,
	boolean use_tmsi
}

type record PagingTestState {
	integer num_paging_sent,
	integer num_paging_rcv_msgs,
	integer num_paging_rcv_ids,
	integer num_overload
}

/* receive + ignore RSL RF RES IND */
altstep as_rsl_res_ind() runs on test_CT {
	[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_RF_RES_IND)) {
		repeat;
	}
}

/* Helper function for paging related testing */
private function f_TC_paging(PagingTestCfg cfg) runs on test_CT return PagingTestState {
	f_init();
	f_init_l1ctl();
	f_l1_tune(L1CTL);

	var PagingTestState st := {
		num_paging_sent := 0,
		num_paging_rcv_msgs := 0,
		num_paging_rcv_ids := 0,
		num_overload := 0
	};

	var float max_pch_blocks_per_sec := f_pch_block_rate_est(cfg.combined_ccch, cfg.bs_ag_blks_res);
	var float max_pch_imsi_per_sec;
	if (cfg.use_tmsi) {
		max_pch_imsi_per_sec := max_pch_blocks_per_sec * 4.0; /* Type 3 */
	} else {
		max_pch_imsi_per_sec := max_pch_blocks_per_sec * 2.0; /* Type 1 */
	}
	var float pch_blocks_per_sec := max_pch_imsi_per_sec * cfg.load_factor;
	var float interval := 1.0 / pch_blocks_per_sec;
	var float time_total := 20.0;
	var integer pkt_total := float2int(time_total * pch_blocks_per_sec);
	log("pch_blocks_total=", pkt_total," pch_blocks_per_sec=", pch_blocks_per_sec, " interval=", interval);

	timer T_total := 300.0; /* big value (far bigger than time_total), used to count elapsed time */
	T_total.start;

	timer T_itv := 0.0;
	T_itv.start;
	while (st.num_paging_sent < pkt_total) {
		alt {
		/* check for presence of CCCH LOAD IND (paging load) */
		[cfg.exp_overload] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_PAGING_LOAD_IND(0))) {
			st.num_overload := st.num_overload + 1;
			repeat;
			}
		[not cfg.exp_overload]  RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_PAGING_LOAD_IND(0))) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unexpected PCH Overload");
			}
		[cfg.exp_load_ind] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_PAGING_LOAD_IND)) {
			log("Rx LOAD_IND");
			/* FIXME: analyze/verify interval + contents */
			repeat;
			}
		/* check if paging requests arrive on Um side */
		[] as_l1_count_paging(st.num_paging_rcv_msgs, st.num_paging_rcv_ids, cfg);
		[] L1CTL.receive { repeat; }
		[] T_itv.timeout {
			/* Send paging cmds based on elapsed time */
			var integer new_sent := f_min(pkt_total, float2int(T_total.read * pch_blocks_per_sec) + 1);
			while (st.num_paging_sent < new_sent) {
				/* build mobile Identity */
				var MobileL3_CommonIE_Types.MobileIdentityLV mi;
				if (cfg.use_tmsi) {
					mi := valueof(ts_MI_TMSI_LV(f_rnd_octstring(4)));
				} else {
					mi := valueof(ts_MI_IMSI_LV(f_gen_imsi(st.num_paging_sent)));
				}
				var octetstring mi_enc_lv := enc_MobileIdentityLV(mi);
				var octetstring mi_enc := substr(mi_enc_lv, 1, lengthof(mi_enc_lv)-1);

				/* Send RSL PAGING COMMAND */
				RSL_CCHAN.send(ts_RSL_UD(ts_RSL_PAGING_CMD(mi_enc, st.num_paging_sent mod 4)));

				st.num_paging_sent := st.num_paging_sent + 1;
			}
			if (st.num_paging_sent < pkt_total) {
				/* Wait for interval to next PAGING COMMAND */
				var float time_now := T_total.read;
				var float next_sched := int2float(st.num_paging_sent)*interval;
				if (next_sched > time_now) {
					T_itv.start(next_sched - time_now);
				} else {
					T_itv.start(0.0);
				}
			} else {
				/* We are done, no need to keep counting */
				T_total.stop;
			}
			}
		[] T_total.timeout { }
		[] as_rsl_res_ind();
		}
	}

	/* wait for max 18s for paging queue to drain (size: 200, ~ 13 per s -> 15s) */
	timer T_wait := 18.0;
	T_wait.start;
	alt {
	[] as_l1_count_paging(st.num_paging_rcv_msgs, st.num_paging_rcv_ids, cfg);
	[] L1CTL.receive { repeat; }
	/* 65535 == empty paging queue, we can terminate*/
	[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_PAGING_LOAD_IND(65535))) { }
	[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_PAGING_LOAD_IND)) { repeat; }
	[] T_wait.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Waiting for empty paging queue");
		}
	[] as_rsl_res_ind();
	}

	log("num_paging_sent=", st.num_paging_sent, " rcvd_msgs=", st.num_paging_rcv_msgs,
	    " rcvd_ids=", st.num_paging_rcv_ids);
	return st;
}

/* Create ~ 80% paging load (IMSI only) sustained for about 20s, verifying that
 *  - the number of Mobile Identities on Um PCH match the number of pages on RSL
 *  - that CCCH LOAD IND (PCH) are being generated
 *  - that CCCH LOAD IND (PCH) [no load] is received after paging flood is over */
testcase TC_paging_imsi_80percent() runs on test_CT {
	var SystemInformation si3 := valueof(ts_SI3_default);
	var PagingTestCfg cfg := {
		combined_ccch := true,
		bs_ag_blks_res := si3.payload.si3.ctrl_chan_desc.bs_ag_blks_res,
		load_factor := 0.8,
		exp_load_ind := true,
		exp_overload := false,
		use_tmsi := false
	};
	var PagingTestState st := f_TC_paging(cfg);
	if (st.num_paging_sent != st.num_paging_rcv_ids) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Expected ", st.num_paging_sent, " pagings but have ",
			   st.num_paging_rcv_ids));
	} else {
		setverdict(pass);
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Create ~ 80% paging load (TMSI only) sustained for about 20s, verifying that
 *  - the number of Mobile Identities on Um PCH match the number of pages on RSL
 *  - that CCCH LOAD IND (PCH) are being generated
 *  - that CCCH LOAD IND (PCH) [no load] is received after paging flood is over */
testcase TC_paging_tmsi_80percent() runs on test_CT {
	var SystemInformation si3 := valueof(ts_SI3_default);
	var PagingTestCfg cfg := {
		combined_ccch := true,
		bs_ag_blks_res := si3.payload.si3.ctrl_chan_desc.bs_ag_blks_res,
		load_factor := 0.8,
		exp_load_ind := true,
		exp_overload := false,
		use_tmsi := true
	};
	var PagingTestState st := f_TC_paging(cfg);
	if (st.num_paging_sent != st.num_paging_rcv_ids) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Expected ", st.num_paging_sent, " pagings but have ",
			   st.num_paging_rcv_ids));
	} else {
		setverdict(pass);
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Create ~ 200% paging load (IMSI only) sustained for about 20s, verifying that
 *  - the number of Mobile Identities on Um PCH are ~ 82% of the number of pages on RSL
 *  - that CCCH LOAD IND (PCH) are being generated and reach 0 at some point
 *  - that CCCH LOAD IND (PCH) [no load] is received after paging flood is over */
testcase TC_paging_imsi_200percent() runs on test_CT {
	var SystemInformation si3 := valueof(ts_SI3_default);
	var PagingTestCfg cfg := {
		combined_ccch := true,
		bs_ag_blks_res := si3.payload.si3.ctrl_chan_desc.bs_ag_blks_res,
		load_factor := 2.0,
		exp_load_ind := true,
		exp_overload := true,
		use_tmsi := false
	};
	var PagingTestState st := f_TC_paging(cfg);
	/* We expect about 80-85% to pass, given that we can fill the paging buffer of 200
	 * slots and will fully drain that buffer before returning */
	var template integer tpl := (st.num_paging_sent*78/100 .. st.num_paging_sent *85/100);
	if (not match(st.num_paging_rcv_ids, tpl)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Expected ", tpl, " pagings but have ", st.num_paging_rcv_ids));
	} else {
		setverdict(pass);
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Create ~ 200% paging load (TMSI only) sustained for about 20s, verifying that
 *  - the number of Mobile Identities on Um PCH are ~ 82% of the number of pages on RSL
 *  - that CCCH LOAD IND (PCH) are being generated and reach 0 at some point
 *  - that CCCH LOAD IND (PCH) [no load] is received after paging flood is over */
testcase TC_paging_tmsi_200percent() runs on test_CT {
	var SystemInformation si3 := valueof(ts_SI3_default);
	var PagingTestCfg cfg := {
		combined_ccch := true,
		bs_ag_blks_res := si3.payload.si3.ctrl_chan_desc.bs_ag_blks_res,
		load_factor := 2.0,
		exp_load_ind := true,
		exp_overload := true,
		use_tmsi := true
	};
	var PagingTestState st := f_TC_paging(cfg);
	/* We expect about 70% to pass, given that we can fill the paging buffer of 200
	 * slots and will fully drain that buffer before returning */
	var template integer tpl := (st.num_paging_sent*64/100 .. st.num_paging_sent *72/100);
	if (not match(st.num_paging_rcv_ids, tpl)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Expected ", tpl, " pagings but have ", st.num_paging_rcv_ids));
	} else {
		setverdict(pass);
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}


/***********************************************************************
 * Immediate Assignment / AGCH
 ***********************************************************************/
const MobileAllocation c_MA_null := {
	len := 0,
	ma := ''B
}

template (value) ChannelDescription ts_ChanDesc(template (value) RslChannelNr chan_nr, uint3_t tsc := 7,
						uint12_t arfcn := 871) := {
	chan_nr := chan_nr,
	tsc := tsc,
	h := false,
	arfcn := arfcn,
	maio_hsn := omit
}

private function f_fmt_ia_stats(integer num_tx, integer num_rx, integer num_del) return charstring {
	return int2str(num_tx) & " sent, "
		  & int2str(num_rx) & " received, "
		  & int2str(num_del) & " deleted";
}

private function f_TC_imm_ass(integer num_total, float sleep_s, float exp_pass) runs on test_CT {
	var L1ctlDlMessage l1_dl;
	timer T := 10.0;
	var integer num_tx := 0;
	var integer num_rx := 0;
	var integer num_del := 0;
	var charstring res_str;
	var float rx_ratio;

	f_init();
	f_init_l1ctl();
	f_l1_tune(L1CTL);

	for (var integer i := 0; i < num_total; i := i+1) {
		var ChannelDescription ch_desc := valueof(ts_ChanDesc(valueof(t_RslChanNr_SDCCH4(0, 0))));
		var GsmRrMessage ia := valueof(ts_IMM_ASS(42, i, 5, ch_desc, c_MA_null));
		var octetstring ia_enc := enc_GsmRrMessage(ia);
		RSL_CCHAN.send(ts_RSL_UD(ts_RSL_IMM_ASSIGN(ia_enc, 0)));
		num_tx := num_tx+1;
		f_sleep(sleep_s);
	}
	/* FIXME: check if imm.ass arrive on Um side */
	T.start;
	alt {
	[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_DELETE_IND(?, 0))) {
		num_del := num_del+1;
		repeat;
		}
	[] RSL_CCHAN.receive {
		repeat;
		}
	[] L1CTL.receive(tr_L1CTL_DATA_IND(t_RslChanNr_PCH_AGCH(0), ?)) -> value l1_dl {
		/* somehow dec_SystemInformation will try to decode even non-RR as SI */
		var GsmRrMessage rr := dec_GsmRrMessage(l1_dl.payload.data_ind.payload);
		if (not match(rr, tr_IMM_ASS(42, ?, 5, ?, ?))) {
			/* FIXME: Why are we seeing paging requests on PCH/AGCH? */
			//Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Unexpected IMM-ASS values on AGCH: ", rr));
		} else {
			num_rx := num_rx+1;
		}
		repeat;
		}
	[] L1CTL.receive { repeat; }
	[] T.timeout { }
	}
	res_str := f_fmt_ia_stats(num_tx, num_rx, num_del);
	log("AGCH test: " & res_str);
	if (num_rx + num_del != num_tx) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "RX + DEL != TX ?!?: " & res_str);
	}
	rx_ratio := int2float(num_rx) / int2float(num_tx);
	if (rx_ratio < exp_pass*0.8 or rx_ratio > exp_pass*1.2) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "RX ratio ("&float2str(rx_ratio)&") far from expected ("&float2str(exp_pass)&") " & res_str);
	} else {
		setverdict(pass);
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* send a long burst of 1000 IMM.ASS with 20ms spacing (50 per s); expect 75% of them to be deleted */
testcase TC_imm_ass_1000_20ms() runs on test_CT {
	f_TC_imm_ass(1000, 0.02, 0.25);
}

/* send a short burst of 200 IMM.ASS without any spacing; expect 95% of them to be deleted */
testcase TC_imm_ass_200_0ms() runs on test_CT {
	f_TC_imm_ass(200, 0.0, 0.05);
}

/* send 150 IMM.ASS at rate of 13/s; expect none of them to be deleted */
testcase TC_imm_ass_200_76ms() runs on test_CT {
	f_TC_imm_ass(150, 0.076, 1.00);
}



/***********************************************************************
 * BCCH
 ***********************************************************************/

/* tuple of Frame Number + decoded SI */
type record SystemInformationFn {
	GsmFrameNumber frame_number,
	SystemInformation si
}

/* an arbitrary-length vector of decoded SI + gsmtap header */
type record of SystemInformationFn SystemInformationVector;

/* an array of SI-vectors indexed by TC value */
type SystemInformationVector SystemInformationVectorPerTc[8];

/* determine if a given SI vector contains given SI type at least once */
function f_si_vecslot_contains(SystemInformationVector arr, RrMessageType key, boolean bcch_ext := false) return boolean {
	for (var integer i:= 0; i< sizeof(arr); i := i + 1) {
		var integer fn_mod51 := arr[i].frame_number mod 51;
		if (not bcch_ext and fn_mod51 == 2 or
		        bcch_ext and fn_mod51 == 6) {
			if (arr[i].si.header.message_type == key) {
				return true;
			}
		}
	}
	return false;
}

/* ensure a given TC slot of the SI vector contains given SI type at least once at TC */
function f_ensure_si_vec_contains(SystemInformationVectorPerTc arr, integer tc, RrMessageType key, boolean ext_bcch := false) {
	if (not f_si_vecslot_contains(arr[tc], key, ext_bcch)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("No ", key, " in TC=", tc, "!"));
	}
}

/* check if a given SI vector contains given SI type at least once on any TC */
function f_si_vec_contains(SystemInformationVectorPerTc arr, RrMessageType key) return boolean {
	for (var integer tc:= 0; tc < sizeof(arr); tc := tc + 1) {
		if (f_si_vecslot_contains(arr[tc], key) or
		    f_si_vecslot_contains(arr[tc], key, true)) {
			return true;
		}
	}
	return false;
}

/* determine if a given SI vector contains given SI type at least N of M times */
function f_si_vecslot_contains_n_of_m(SystemInformationVector arr, RrMessageType key, boolean bcch_ext := false, integer n := 1, integer m := 4) return boolean {
	var integer count := 0;
	if (sizeof(arr) < m) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Error: Insufficient SI in array");
	}
	for (var integer i:= 0; i < m; i := i + 1) {
		var integer fn_mod51 := arr[i].frame_number mod 51;
		if (not bcch_ext and fn_mod51 == 2 or
		        bcch_ext and fn_mod51 == 6) {
			if (arr[i].si.header.message_type == key) {
				count := count + 1;
			}
		}
	}
	if (count >= n) {
		return true;
	} else {
		return false;
	}
}

/* ensure a given TC slot of the SI vector contains given SI type at least N out of M times at TC */
function f_ensure_si_vec_contains_n_of_m(SystemInformationVectorPerTc arr, integer tc, RrMessageType key, boolean ext_bcch := false, integer n, integer m) {
	if (not f_si_vecslot_contains_n_of_m(arr[tc], key, ext_bcch, n, m)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Not ", n, "/", m, " of ", key, " in TC=", tc, "!"));
	}
}

/* determine if a given SI vector contains given SI type at least once */
function f_si_vecslot_contains_only(SystemInformationVector arr, RrMessageType key, boolean bcch_ext := false) return boolean {
	for (var integer i:= 0; i< sizeof(arr); i := i + 1) {
		var integer fn_mod51 := arr[i].frame_number mod 51;
		if (not bcch_ext and fn_mod51 == 2 or
		        bcch_ext and fn_mod51 == 6) {
			if (arr[i].si.header.message_type != key) {
				return false;
			}
		}
	}
	return true;
}

/* ensure a given TC slot of the SI vector contains only given SI type */
function f_ensure_si_vec_contains_only(SystemInformationVectorPerTc arr, integer tc, RrMessageType key, boolean ext_bcch := false) {
	if (not f_si_vecslot_contains_only(arr[tc], key, ext_bcch)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Not all ", key, " in TC=", tc, "!"));
	}
}

/* SI configuration of cell, against which we validate actual SI messages */
type set SystemInformationConfig {
	boolean bcch_extended,
	boolean si1_present,
	boolean si2bis_present,
	boolean si2ter_present,
	boolean si2quater_present,
	boolean si7_present,
	boolean si8_present,
	boolean si9_present,
	boolean si13_present,
	boolean si13alt_present,
	boolean si15_present,
	boolean si16_present,
	boolean si17_present,
	boolean si2n_present,
	boolean si21_present,
	boolean si22_present
}

/* validate the SI scheduling according to TS 45.002 version 14.1.0 Release 14, Section 6.3.1.3 */
function f_validate_si_scheduling(SystemInformationConfig cfg, SystemInformationVectorPerTc si_per_tc) {
	var integer i;
	for (i := 0; i < sizeof(si_per_tc); i := i + 1) {
		if (sizeof(si_per_tc[i]) == 0) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("No SI messages for TC=", i));
		}
	}
	if (cfg.si1_present) {
		/* ii) System Information Type 1 needs to be sent if frequency hopping is in use or
		 * when the NCH is present in a cell. If the MS finds another message on BCCH Norm
		 * when TC = 0, it can assume that System Information Type 1 is not in use. */
		f_ensure_si_vec_contains(si_per_tc, 0, SYSTEM_INFORMATION_TYPE_1);
		/* make sure *ALL* contain SI1 */
		f_ensure_si_vec_contains_only(si_per_tc, 0, SYSTEM_INFORMATION_TYPE_1);
	}
	f_ensure_si_vec_contains(si_per_tc, 1, SYSTEM_INFORMATION_TYPE_2);
	/* iii) A SI 2 message will be sent at least every time TC = 1 */
	f_ensure_si_vec_contains(si_per_tc, 2, SYSTEM_INFORMATION_TYPE_3);
	f_ensure_si_vec_contains(si_per_tc, 6, SYSTEM_INFORMATION_TYPE_3);
	f_ensure_si_vec_contains(si_per_tc, 3, SYSTEM_INFORMATION_TYPE_4);
	f_ensure_si_vec_contains(si_per_tc, 7, SYSTEM_INFORMATION_TYPE_4);

	/*  iii) System information type 2 bis or 2 ter messages are sent if needed, as determined by the
	 *  system operator. If only one of them is needed, it is sent when TC = 5. If both are
	 *  needed, 2bis is sent when TC = 5 and 2ter is sent at least once within any of 4
	 *  consecutive occurrences of TC = 4. */
	if (cfg.si2bis_present and not cfg.si2ter_present) {
		f_ensure_si_vec_contains(si_per_tc, 5, SYSTEM_INFORMATION_TYPE_2bis);
	} else if (cfg.si2ter_present and not cfg.si2bis_present) {
		f_ensure_si_vec_contains(si_per_tc, 5, SYSTEM_INFORMATION_TYPE_2ter);
	} else if (cfg.si2ter_present and cfg.si2bis_present) {
		f_ensure_si_vec_contains(si_per_tc, 5, SYSTEM_INFORMATION_TYPE_2bis);
		f_ensure_si_vec_contains_n_of_m(si_per_tc, 4, SYSTEM_INFORMATION_TYPE_2ter, false, 1, 4);
	}

	if (cfg.si7_present or cfg.si8_present) {
		/* vi) Use of System Information type 7 and 8 is not always necessary. It is necessary
		 * if System Information type 4 does not contain all information needed for cell
		 * selection and reselection. */
		if (not cfg.bcch_extended) {
			testcase.stop("Error: SI7/SI8 require BCCH Extd.");
		}
		if (cfg.si7_present) {
			f_ensure_si_vec_contains(si_per_tc, 7, SYSTEM_INFORMATION_TYPE_7, true);
		}
		if (cfg.si8_present) {
			f_ensure_si_vec_contains(si_per_tc, 3, SYSTEM_INFORMATION_TYPE_8, true);
		}
	}

	if (cfg.si2quater_present) {
		/*  iii) System information type 2 quater is sent if needed, as determined by the system
		 *  operator.  If sent on BCCH Norm, it shall be sent when TC = 5 if neither of 2bis
		 *  and 2ter are used, otherwise it shall be sent at least once within any of 4
		 *  consecutive occurrences of TC = 4. If sent on BCCH Ext, it is sent at least once
		 *  within any of 4 consecutive occurrences of TC = 5. */
		if (not (cfg.bcch_extended)) {
			if (not (cfg.si2bis_present or cfg.si2ter_present)) {
				f_ensure_si_vec_contains(si_per_tc, 5, SYSTEM_INFORMATION_TYPE_2quater);
			} else {
				f_ensure_si_vec_contains_n_of_m(si_per_tc, 4, SYSTEM_INFORMATION_TYPE_2quater, false, 1, 4);
			}
		} else {
			f_ensure_si_vec_contains_n_of_m(si_per_tc, 5, SYSTEM_INFORMATION_TYPE_2quater, true, 1, 4);
		}
	}
	if (cfg.si9_present) {
		/* vi) System Information type 9 is sent in those blocks with TC = 4 which are specified
		 * in system information type 3 as defined in 3GPP TS 44.018. */
		f_ensure_si_vec_contains(si_per_tc, 4, SYSTEM_INFORMATION_TYPE_9); // FIXME SI3
	}
	if (cfg.si13_present) {
		/* vii) System Information type 13 is only related to the GPRS service. System Information
		 * Type 13 need only be sent if GPRS support is indicated in one or more of System
		 * Information Type 3 or 4 or 7 or 8 messages. These messages also indicate if the
		 * message is sent on the BCCH Norm or if the message is transmitted on the BCCH Ext.
		 * In the case that the message is sent on the BCCH Norm, it is sent at least once
		 * within any of 4 consecutive occurrences of TC=4. */
		if (not cfg.bcch_extended) {
			log("not-bccch-extended");
			f_ensure_si_vec_contains_n_of_m(si_per_tc, 4, SYSTEM_INFORMATION_TYPE_13, false, 1, 4);
		} else {
			log("bccch-extended");
			f_ensure_si_vec_contains(si_per_tc, 0, SYSTEM_INFORMATION_TYPE_13, true);
		}
		if (f_si_vec_contains(si_per_tc, SYSTEM_INFORMATION_TYPE_13alt)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Cannot have SI13alt and SI13");
		}
	}
	if (cfg.si16_present or cfg.si17_present) {
		/* viii) System Information type 16 and 17 are only related to the SoLSA service. They
		 * should not be sent in a cell where network sharing is used (see rule xv). */
		if (cfg.si22_present) {
			testcase.stop("Error: Cannot have SI16/SI17 and SI22!");
		}
		if (f_si_vec_contains(si_per_tc, SYSTEM_INFORMATION_TYPE_22)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Cannot have SI16/SI17 and SI22!");
		}
		if (not cfg.bcch_extended) {
			testcase.stop("Error: SI16/SI17 requires BCCH Extd!");
		}
		if (cfg.si16_present) {
			f_ensure_si_vec_contains(si_per_tc, 6, SYSTEM_INFORMATION_TYPE_16, true);
		}
		if (cfg.si17_present) {
			f_ensure_si_vec_contains(si_per_tc, 2, SYSTEM_INFORMATION_TYPE_17, true);
		}
	}

		/* ix) System Information type 18 and 20 are sent in order to transmit non-GSM
		 * broadcast information. The frequency with which they are sent is determined by the
		 * system operator. System Information type 9 identifies the scheduling of System
		 * Information type 18 and 20 messages. */

		/* x) System Information Type 19 is sent if COMPACT neighbours exist. If System
		 * Information Type 19 is present, then its scheduling shall be indicated in System
		 * Information Type 9. */

	if (cfg.si15_present) {
		/* xi) System Information Type 15 is broadcast if dynamic ARFCN mapping is used in the
		 * PLMN. If sent on BCCH Norm, it is sent at least once within any of 4 consecutive
		 * occurrences of TC = 4. If sent on BCCH Ext, it is sent at least once within any of
		 * 4 consecutive occurrences of TC = 1. */
		if (not cfg.bcch_extended) {
			f_ensure_si_vec_contains_n_of_m(si_per_tc, 4, SYSTEM_INFORMATION_TYPE_15, false, 1, 4);
		} else {
			f_ensure_si_vec_contains_n_of_m(si_per_tc, 1, SYSTEM_INFORMATION_TYPE_15, true, 1, 4);
		}
	}
	if (cfg.si13alt_present) {
		/* xii) System Information type 13 alt is only related to the GERAN Iu mode. System
		 * Information Type 13 alt need only be sent if GERAN Iu mode support is indicated in
		 * one or more of System Information Type 3 or 4 or 7 or 8 messages and SI 13 is not
		 * broadcast. These messages also indicate if the message is sent on the BCCH Norm or
		 * if the message is transmitted on the BCCH Ext. In the case that the message is sent
		 * on the BCCH Norm, it is sent at least once within any of 4 consecutive occurrences
		 * of TC = 4. */
		if (cfg.si13_present) {
			testcase.stop("Error: Cannot have SI13alt and SI13");
		}
		if (f_si_vec_contains(si_per_tc, SYSTEM_INFORMATION_TYPE_13)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Cannot have SI13alt and SI13");
		}
		if (not cfg.bcch_extended) {
			f_ensure_si_vec_contains_n_of_m(si_per_tc, 4, SYSTEM_INFORMATION_TYPE_13alt, false, 1, 4);
		} else {
			f_ensure_si_vec_contains(si_per_tc, 0, SYSTEM_INFORMATION_TYPE_13alt, true);
		}
	}
	if (cfg.si2n_present) {
		/* xiii) System Information Type 2n is optionally sent on BCCH Norm or BCCH Ext if needed,
		 * as determined by the system operator. In the case that the message is sent on the
		 * BCCH Norm, it is sent at least once within any of 4 consecutive occurrences of TC =
		 * 4. If the message is sent on BCCH Ext, it is sent at least once within any of 2
		 * consecutive occurrences of TC = 4. */
		if (not cfg.bcch_extended) {
			f_ensure_si_vec_contains_n_of_m(si_per_tc, 4, SYSTEM_INFORMATION_TYPE_2n, false, 1, 4);
		} else {
			f_ensure_si_vec_contains_n_of_m(si_per_tc, 4, SYSTEM_INFORMATION_TYPE_2n, true, 2, 4);
		}
	}
	if (cfg.si21_present) {
		/* xiv) System Information Type 21 is optionally sent on BCCH Norm or BCCH Ext, as
		 * determined by the system operator. If Extended Access Barring is in use in the cell
		 * then this message is sent at least once within any of 4 consecutive occurrences of
		 * TC = 4 regardless if it is sent on BCCH Norm or BCCH Ext. If BCCH Ext is used in a
		 * cell then this message shall only be sent on BCCH Ext. */
		if (not cfg.bcch_extended) {
			f_ensure_si_vec_contains_n_of_m(si_per_tc, 4, SYSTEM_INFORMATION_TYPE_21, false, 1, 4);
		} else {
			f_ensure_si_vec_contains_n_of_m(si_per_tc, 4, SYSTEM_INFORMATION_TYPE_21, true, 1, 4);
			if (f_si_vecslot_contains(si_per_tc[4], SYSTEM_INFORMATION_TYPE_21)) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Cannot have SI21 on BCCH Norm if BCCH Extd enabled!");
			}
		}
	}
	if (cfg.si22_present) {
		/* xv) System Information Type 22 is sent if network sharing is in use in the cell. It
		 * should not be sent in a cell where SoLSA is used (see rule viii). System
		 * Information Type 22 instances shall be sent on BCCH Ext within any occurrence of TC
		 * =2 and TC=6. */
		if (cfg.si16_present or cfg.si17_present) {
			testcase.stop("Error: Cannot have SI16/SI17 and SI22!");
		}
		if (f_si_vec_contains(si_per_tc, SYSTEM_INFORMATION_TYPE_16) or
		    f_si_vec_contains(si_per_tc, SYSTEM_INFORMATION_TYPE_17)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Cannot have SI16/SI17 and SI22!");
		}
		if (not cfg.bcch_extended) {
			testcase.stop("Error: SI22 requires BCCH Extd!");
		} else {
			f_ensure_si_vec_contains_only(si_per_tc, 2, SYSTEM_INFORMATION_TYPE_22, true);
			f_ensure_si_vec_contains_only(si_per_tc, 6, SYSTEM_INFORMATION_TYPE_22, true);
		}
	}
}

/* sample Systme Information for specified duration via L1CTL */
function f_l1_sample_si(L1CTL_PT pt, float duration := 8.0) return SystemInformationVectorPerTc {
	timer T := duration;
	var SystemInformationVectorPerTc si_per_tc;
	var L1ctlDlMessage l1_dl;

	/* initialize all per-TC vectors empty */
	for (var integer i:= 0; i < sizeof(si_per_tc); i := i+1) {
		si_per_tc[i] := {};
	}

	/* flush all previous L1 queued msgs */
	pt.clear;

	T.start;
	alt {
	[] pt.receive(tr_L1CTL_DATA_IND(t_RslChanNr_BCCH(0), ?)) -> value l1_dl {
		/* somehow dec_SystemInformation will try to decode even non-RR as SI */
		if (not (l1_dl.payload.data_ind.payload[1] ==  '06'O)) {
			log("Ignoring non-RR SI ", l1_dl);
			repeat;
		}
		var SystemInformationFn sig := {
			frame_number := l1_dl.dl_info.frame_nr,
			si := dec_SystemInformation(l1_dl.payload.data_ind.payload)
		}
		var integer tc := f_gsm_compute_tc(sig.frame_number);
		log("SI received at TC=", tc, ": ", sig.si);
		/* append to the per-TC bucket */
		si_per_tc[tc] := si_per_tc[tc] & { sig };
		repeat;
		}
	[] pt.receive { repeat; }
	[] T.timeout { }
	}

	for (var integer i:= 0; i < sizeof(si_per_tc); i := i+1) {
		log(testcasename(), ": TC=", i, " has #of SI=", sizeof(si_per_tc[i]));
	}
	log("si_per_tc=", si_per_tc);
	return si_per_tc;
}

/* helper function: Set given SI via RSL + validate scheduling.
 * CALLER MUST MAKE SURE TO CHANGE GLOBAL si_cfg! */
function f_TC_si_sched() runs on test_CT {
	var SystemInformationVectorPerTc si_per_tc;
	f_init_l1ctl();
	f_l1_tune(L1CTL);

	/* Sample + Validate Scheduling */
	si_per_tc := f_l1_sample_si(L1CTL);
	f_validate_si_scheduling(si_cfg, si_per_tc);

	setverdict(pass);
}

testcase TC_si_sched_default() runs on test_CT {
	f_init();
	/* 2+3+4 are mandatory and set in f_init() */
	f_TC_si_sched();
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_si_sched_1() runs on test_CT {
	f_init();
	si_cfg.si1_present := true;
	f_rsl_bcch_fill_raw(RSL_SYSTEM_INFO_1, '5506198fb38000000000000000000000000000e504002b'O);
	f_TC_si_sched();
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_si_sched_2bis() runs on test_CT {
	f_init();
	si_cfg.si2bis_present := true;
	f_rsl_bcch_fill_raw(RSL_SYSTEM_INFO_2bis, '550602bfe809b3ff00000000000000000000007900002b'O);
	f_TC_si_sched();
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_si_sched_2ter() runs on test_CT {
	f_init();
	si_cfg.si2ter_present := true;
	f_rsl_bcch_fill_raw(RSL_SYSTEM_INFO_2ter, '010603bf66b0aa0a00000002000000000000002b2b2b2b'O);
	f_TC_si_sched();
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_si_sched_2ter_2bis() runs on test_CT {
	f_init();
	si_cfg.si2bis_present := true;
	f_rsl_bcch_fill_raw(RSL_SYSTEM_INFO_2bis, '550602bfe809b3ff00000000000000000000007900002b'O);
	si_cfg.si2ter_present := true;
	f_rsl_bcch_fill_raw(RSL_SYSTEM_INFO_2ter, '010603bf66b0aa0a00000002000000000000002b2b2b2b'O);
	f_TC_si_sched();
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_si_sched_2quater() runs on test_CT {
	f_init();
	si_cfg.si2quater_present := true;
	f_rsl_bcch_fill_raw(RSL_SYSTEM_INFO_2quater, '050607a8a0364aa698d72ff424feee0506d5e7fff02043'O);
	f_TC_si_sched();
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_si_sched_13() runs on test_CT {
	f_init();
	si_cfg.si13_present := true;
	f_rsl_bcch_fill_raw(RSL_SYSTEM_INFO_13, '0106009000185a6fc9e08410ab2b2b2b2b2b2b2b2b2b2b'O);
	f_TC_si_sched();
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

testcase TC_si_sched_13_2bis_2ter_2quater() runs on test_CT {
	f_init();
	si_cfg.si2bis_present := true;
	f_rsl_bcch_fill_raw(RSL_SYSTEM_INFO_2bis, '550602bfe809b3ff00000000000000000000007900002b'O);
	si_cfg.si2ter_present := true;
	f_rsl_bcch_fill_raw(RSL_SYSTEM_INFO_2ter, '010603bf66b0aa0a00000002000000000000002b2b2b2b'O);
	si_cfg.si2quater_present := true;
	f_rsl_bcch_fill_raw(RSL_SYSTEM_INFO_2quater, '050607a8a0364aa698d72ff424feee0506d5e7fff02043'O);
	si_cfg.si13_present := true;
	f_rsl_bcch_fill_raw(RSL_SYSTEM_INFO_13, '0106009000185a6fc9e08410ab2b2b2b2b2b2b2b2b2b2b'O);
	f_TC_si_sched();
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}


testcase TC_bcch_info() runs on test_CT {
	f_init();
	/* FIXME: enable / disable individual BCCH info */
	//ts_RSL_BCCH_INFO(si_type, info);
	/* expect no ERROR REPORT after either of them *
	/* negative test: ensure ERROR REPORT on unsupported types */
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/***********************************************************************
 * Low-Level Protocol Errors / ERROR REPORT
 ***********************************************************************/

private function f_exp_err_rep(template RSL_Cause cause) runs on test_CT {
	timer T := 5.0;
	T.start;
	alt {
	[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_ERROR_REPORT(cause))) {
		setverdict(pass);
		}
	[] RSL_CCHAN.receive(tr_RSL_UD(tr_RSL_ERROR_REPORT(?))) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Wrong cause in RSL ERR REP");
		}
	[] RSL_CCHAN.receive {
		repeat;
		}
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for RSL ERR REP");
		}
	}
}

/* Provoke a protocol error (message too short) and match on ERROR REPORT */
testcase TC_rsl_protocol_error() runs on test_CT {
	f_init();
	var RSL_Message rsl := valueof(ts_RSL_BCCH_INFO(RSL_SYSTEM_INFO_1, ''O));
	rsl.ies := omit;
	RSL_CCHAN.send(ts_RSL_UD(rsl));

	f_exp_err_rep(RSL_ERR_PROTO);
}

/* Provoke a mandatory IE error and match on ERROR REPORT */
testcase TC_rsl_mand_ie_error() runs on test_CT {
	f_init();

	var RSL_Message rsl := valueof(ts_RSL_BCCH_INFO(RSL_SYSTEM_INFO_1, ''O));
	rsl.ies := { rsl.ies[0] };
	RSL_CCHAN.send(ts_RSL_UD(rsl));

	f_exp_err_rep(RSL_ERR_MAND_IE_ERROR);
}

/* Provoke an IE content error and match on ERROR REPORT */
testcase TC_rsl_ie_content_error() runs on test_CT {
	f_init();
	var RSL_Message rsl := valueof(ts_RSL_BCCH_INFO(RSL_SYSTEM_INFO_1, ''O));
	rsl.ies[1].body.sysinfo_type := RSL_SYSTEM_INFO_5;
	RSL_CCHAN.send(ts_RSL_UD(rsl));

	f_exp_err_rep(RSL_ERR_IE_CONTENT);
}

/* attempt to activate channel with wrong RSL Message Discriminator IE */
function f_TC_chan_act_wrong_mdisc(charstring id) runs on ConnHdlr {
	var template RSL_Message rsl := ts_RSL_CHAN_ACT(g_chan_nr, g_pars.chan_mode);
	rsl.msg_disc := ts_RSL_MsgDisc(RSL_MDISC_RESERVED, false);
	RSL.send(rsl);
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_err_rep_wrong_mdisc() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars := valueof(t_Pars(ts_RslChanNr_SDCCH4(0,0), ts_RSL_ChanMode_SIGN));

	f_init();

	vc_conn := f_start_handler(refers(f_TC_chan_act_wrong_mdisc), pars);
	vc_conn.done;
	f_exp_err_rep(RSL_ERR_MSG_DISCR);

	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Send messages with wrong message type */
function f_TC_wrong_msg_type_dchan(charstring id) runs on ConnHdlr {
	var template (value) RSL_Message rsl_tx;
	rsl_tx := ts_RSL_CHAN_ACT(g_chan_nr, g_pars.chan_mode);
	rsl_tx.msg_type := RSL_MT_NOT_CMD;
	RSL.send(rsl_tx);
	f_rslem_unregister(0, g_chan_nr);
}
function f_TC_wrong_msg_type_rll(charstring id) runs on ConnHdlr {
	var template (value) RSL_Message rsl_tx;
	/* we first have to activate the dedicated channel */
	f_rsl_chan_act(g_pars.chan_mode);
	/* ... to then send an invalid RLL message */
	rsl_tx := ts_RSL_UNITDATA_REQ(g_chan_nr, ts_RslLinkID_DCCH(0), '0102'O);
	rsl_tx.msg_type := RSL_MT_CBCH_LOAD_IND;
	RSL.send(rsl_tx);
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_err_rep_wrong_msg_type() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars := valueof(t_Pars(ts_RslChanNr_SDCCH4(0,0), ts_RSL_ChanMode_SIGN));
	var template (value) RSL_Message rsl_tx;

	f_init();

	/* Common Channel with wrong message type */
	RSL_CCHAN.clear;
	rsl_tx := valueof(ts_RSL_BCCH_INFO(RSL_SYSTEM_INFO_1, ''O));
	rsl_tx.msg_type := RSL_MT_LOCATION_INFO;
	RSL_CCHAN.send(ts_RSL_UD(rsl_tx));
	f_exp_err_rep(RSL_ERR_MSG_TYPE);

	/* TRX Management */
	RSL_CCHAN.clear;
	rsl_tx := ts_RSL_SACCH_FILL(RSL_SYSTEM_INFO_5, ''O);
	rsl_tx.msg_type := RSL_MT_UNIT_DATA_IND;
	RSL_CCHAN.send(ts_RSL_UD(rsl_tx));
	f_exp_err_rep(RSL_ERR_MSG_TYPE);

	/* Dedicated Channel */
	RSL_CCHAN.clear;
	vc_conn := f_start_handler(refers(f_TC_wrong_msg_type_dchan), pars);
	vc_conn.done;
	f_exp_err_rep(RSL_ERR_MSG_TYPE);

	/* RLL */
	RSL_CCHAN.clear;
	vc_conn := f_start_handler(refers(f_TC_wrong_msg_type_rll), pars);
	vc_conn.done;
	f_exp_err_rep(RSL_ERR_MSG_TYPE);
}

/* Send messages in wrong sequence (RLL to an inactive lchan) */
function f_TC_err_rep_wrong_sequence(charstring id) runs on ConnHdlr {
	RSL.send(ts_RSL_UNITDATA_REQ(g_chan_nr, ts_RslLinkID_DCCH(0), '0102'O));
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_err_rep_wrong_sequence() runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars := valueof(t_Pars(ts_RslChanNr_SDCCH4(0,0), ts_RSL_ChanMode_SIGN));

	f_init();

	RSL_CCHAN.clear;
	vc_conn := f_start_handler(refers(f_TC_err_rep_wrong_sequence), pars);
	vc_conn.done;
	f_exp_err_rep(RSL_ERR_MSG_SEQ);
}

/***********************************************************************
 * IPA CRCX/MDCX/DLCS media stream handling
 ***********************************************************************/

/* Send IPA DLCX to inactive lchan */
function f_TC_ipa_dlcx_not_active(charstring id) runs on ConnHdlr {
	f_rsl_transceive(ts_RSL_IPA_DLCX(g_chan_nr, 0), tr_RSL_IPA_DLCX_ACK(g_chan_nr, ?, ?),
			 "IPA DLCX ACK");
}
testcase TC_ipa_dlcx_not_active() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	f_init();
	var ConnHdlr vc_conn := f_start_handler(refers(f_TC_ipa_dlcx_not_active), pars);
	vc_conn.done;
}

/* Send IPA CRCX twice to inactive lchan */
function f_TC_ipa_crcx_twice_not_active(charstring id) runs on ConnHdlr {
	f_rsl_transceive(ts_RSL_IPA_CRCX(g_chan_nr), tr_RSL_IPA_CRCX_ACK(g_chan_nr, ?, ?, ?),
			 "IPA CRCX ACK");
	f_rsl_transceive(ts_RSL_IPA_CRCX(g_chan_nr), tr_RSL_IPA_CRCX_NACK(g_chan_nr, RSL_ERR_RES_UNAVAIL),
			 "IPA CRCX NACK");
}
testcase TC_ipa_crcx_twice_not_active() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	f_init();
	var ConnHdlr vc_conn := f_start_handler(refers(f_TC_ipa_crcx_twice_not_active), pars);
	vc_conn.done;
}

/* Regular sequence of CRCX/MDCX/DLCX */
function f_TC_ipa_crcx_mdcx_dlcx_not_active(charstring id) runs on ConnHdlr {
	f_rsl_transceive(ts_RSL_IPA_CRCX(g_chan_nr), tr_RSL_IPA_CRCX_ACK(g_chan_nr, ?, ?, ?),
			 "IPA CRCX ACK");
	var uint32_t remote_ip := f_rnd_int(c_UINT32_MAX);
	var uint16_t remote_port := f_rnd_int(c_UINT16_MAX);
	var uint7_t rtp_pt2 := f_rnd_int(127);
	var uint16_t fake_conn_id := 23; /* we're too lazy to read it out from the CRCX ACK above */
	f_rsl_transceive(ts_RSL_IPA_MDCX(g_chan_nr, fake_conn_id, remote_ip, remote_port, rtp_pt2),
			 tr_RSL_IPA_MDCX_ACK(g_chan_nr, ?, ?, ?, rtp_pt2),
			 "IPA MDCX ACK");
	f_rsl_transceive(ts_RSL_IPA_DLCX(g_chan_nr, fake_conn_id), tr_RSL_IPA_DLCX_ACK(g_chan_nr, ?, ?),
			 "IPA DLCX ACK");
}
testcase TC_ipa_crcx_mdcx_dlcx_not_active() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	f_init();
	var ConnHdlr vc_conn := f_start_handler(refers(f_TC_ipa_crcx_mdcx_dlcx_not_active), pars);
	vc_conn.done;
}

/* Sequence of CRCX, 2x MDCX, DLCX */
function f_TC_ipa_crcx_mdcx_mdcx_dlcx_not_active(charstring id) runs on ConnHdlr {
	f_rsl_transceive(ts_RSL_IPA_CRCX(g_chan_nr), tr_RSL_IPA_CRCX_ACK(g_chan_nr, ?, ?, ?),
			 "IPA CRCX ACK");
	var uint32_t remote_ip := f_rnd_int(c_UINT32_MAX);
	var uint16_t remote_port := f_rnd_int(c_UINT16_MAX);
	var uint7_t rtp_pt2 := f_rnd_int(127);
	var uint16_t fake_conn_id := 23; /* we're too lazy to read it out from the CRCX ACK above */
	f_rsl_transceive(ts_RSL_IPA_MDCX(g_chan_nr, fake_conn_id, remote_ip, remote_port, rtp_pt2),
			 tr_RSL_IPA_MDCX_ACK(g_chan_nr, ?, ?, ?, rtp_pt2),
			 "IPA MDCX ACK");
	/* Second MDCX */
	remote_ip := f_rnd_int(c_UINT32_MAX);
	remote_port := f_rnd_int(c_UINT16_MAX);
	f_rsl_transceive(ts_RSL_IPA_MDCX(g_chan_nr, fake_conn_id, remote_ip, remote_port, rtp_pt2),
			 tr_RSL_IPA_MDCX_ACK(g_chan_nr, ?, ?, ?, rtp_pt2),
			 "IPA MDCX ACK");
	f_rsl_transceive(ts_RSL_IPA_DLCX(g_chan_nr, fake_conn_id), tr_RSL_IPA_DLCX_ACK(g_chan_nr, ?, ?),
			 "IPA DLCX ACK");
}
testcase TC_ipa_crcx_mdcx_mdcx_dlcx_not_active() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	f_init();
	var ConnHdlr vc_conn := f_start_handler(refers(f_TC_ipa_crcx_mdcx_mdcx_dlcx_not_active), pars);
	vc_conn.done;
}

/* IPA CRCX on SDCCH/4 and SDCCH/8 (doesn't make sense) */
function f_TC_ipa_crcx_sdcch_not_active(charstring id) runs on ConnHdlr {
	f_rsl_transceive(ts_RSL_IPA_CRCX(g_chan_nr), tr_RSL_IPA_CRCX_NACK(g_chan_nr, ?),
			 "IPA CRCX NACK");
}
testcase TC_ipa_crcx_sdcch_not_active() runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;
	f_init();

	pars := valueof(t_Pars(t_RslChanNr_SDCCH4(0,1), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_TC_ipa_crcx_sdcch_not_active), pars);
	vc_conn.done;

	pars := valueof(t_Pars(t_RslChanNr_SDCCH8(6,5), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_TC_ipa_crcx_sdcch_not_active), pars);
	vc_conn.done;
}


/***********************************************************************
 * PCU Socket related tests
 ***********************************************************************/

/* Verify no RTS before ACT_REQ; verify RTS after ACT_REQ */
friend function f_TC_pcu_act_req(uint8_t bts_nr, uint8_t trx_nr, uint8_t ts_nr, boolean exp_success)
runs on test_CT {
	timer T := 3.0;

	/* we don't expect any RTS.req before PDCH are active */
	T.start;
	alt {
	[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_RTS_REQ(bts_nr))) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "PCU RTS.req before PDCH active?");
		}
	[] PCU.receive { repeat; }
	[] T.timeout { }
	}

	/* Send PDCH activate request for known PDCH timeslot */
	PCU.send(t_SD_PCUIF(g_pcu_conn_id, ts_PCUIF_ACT_REQ(bts_nr, trx_nr, ts_nr)));

	/* we now expect RTS.req for this timeslot (only) */
	T.start;
	alt {
	[exp_success] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_RTS_REQ(bts_nr, trx_nr, ts_nr))) {
		setverdict(pass);
		}
	[not exp_success] PCU.receive(t_SD_PCUIF(g_pcu_conn_id,
						 tr_PCUIF_RTS_REQ(bts_nr, trx_nr, ts_nr))) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unexpected RTS.req for supposedly failing activation");
		}
	[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_RTS_REQ)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "RTS.req for wrong TRX/TS");
		}
	[] PCU.receive { repeat; }
	[exp_success] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for PCU RTS.req");
		}
	[not exp_success] T.timeout {
		setverdict(pass);
		}
	}
}

/* verify no more RTS after DEACT_REQ */
friend function f_TC_pcu_deact_req(uint8_t bts_nr, uint8_t trx_nr, uint8_t ts_nr)
runs on test_CT {
	timer T := 3.0;

	/* Send PDCH activate request for known PDCH timeslot */
	PCU.send(t_SD_PCUIF(g_pcu_conn_id, ts_PCUIF_DEACT_REQ(bts_nr, trx_nr, ts_nr)));

	PCU.clear;
	/* we now expect no RTS.req for this timeslot */
	T.start;
	alt {
	[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_RTS_REQ(bts_nr, trx_nr, ts_nr))) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Received unexpected PCU RTS.req");
		}
	[] PCU.receive { repeat; }
	[] T.timeout {
		setverdict(pass);
		}
	}
}

friend function f_init_pcu_test() runs on test_CT {
	f_init();
	PCU.send(t_SD_PCUIF(g_pcu_conn_id, ts_PCUIF_TXT_IND(0, PCU_VERSION, testcasename())));
}

/* PDCH activation via PCU socket; check for presence of RTS.req */
testcase TC_pcu_act_req() runs on test_CT {
	f_init_pcu_test();

	f_TC_pcu_act_req(0, 0, 7, true);
}

/* PDCH activation via PCU socket on non-PDCU timeslot */
testcase TC_pcu_act_req_wrong_ts() runs on test_CT {
	f_init_pcu_test();

	f_TC_pcu_act_req(0, 0, 1, false);
}

/* PDCH activation via PCU socket on wrong BTS */
testcase TC_pcu_act_req_wrong_bts() runs on test_CT {
	f_init_pcu_test();

	f_TC_pcu_act_req(23, 0, 7, false);
}

/* PDCH activation via PCU socket on wrong TRX */
testcase TC_pcu_act_req_wrong_trx() runs on test_CT {
	f_init_pcu_test();

	f_TC_pcu_act_req(0, 23, 7, false);
}

/* PDCH deactivation via PCU socket; check for absence of RTS.req */
testcase TC_pcu_deact_req() runs on test_CT {
	f_init_pcu_test();

	/* Activate PDCH */
	f_TC_pcu_act_req(0, 0, 7, true);
	f_sleep(1.0);
	/* and De-Activate again */
	f_TC_pcu_deact_req(0, 0, 7);
}

/* Attempt to deactivate a PDCH on a non-PDCH timeslot */
testcase TC_pcu_deact_req_wrong_ts() runs on test_CT {
	f_init_pcu_test();

	f_TC_pcu_deact_req(0, 0, 1);
}

/* Test the PCU->BTS Version and BTS->PCU SI13 handshake */
testcase TC_pcu_ver_si13() runs on test_CT {
	const octetstring si13 := '00010203040506070909'O;
	var PCUIF_send_data sd;
	timer T:= 3.0;
	f_init_pcu_test();

	/* Set SI13 via RSL */
	f_rsl_bcch_fill_raw(RSL_SYSTEM_INFO_13, si13);

	T.start;
	alt {
	[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_DATA_IND(0, 0, 0, ?, PCU_IF_SAPI_BCCH))) -> value sd {
		if (substr(sd.data.u.data_ind.data, 0, lengthof(si13)) == si13) {
			setverdict(pass);
		} else {
			repeat;
		}
		}
	[] PCU.receive { repeat; }
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for SI13");
		}
	}
}

private const octetstring c_PCU_DATA := '000102030405060708090a0b0c0d0e0f10111213141516'O;

/* helper function to send a PCU DATA.req */
friend function f_pcu_data_req(uint8_t bts_nr, uint8_t trx_nr, uint8_t ts_nr,
				uint8_t block_nr, uint32_t fn, PCUIF_Sapi sapi, octetstring data)
runs on test_CT
{
	PCU.send(t_SD_PCUIF(g_pcu_conn_id,
			ts_PCUIF_DATA_REQ(bts_nr, trx_nr, ts_nr, block_nr, fn, sapi, data)));
}

/* helper function to wait for RTS.ind for given SAPI on given BTS/TRX/TS and then send */
friend function f_pcu_wait_rts_and_data_req(uint8_t bts_nr, uint8_t trx_nr, uint8_t ts_nr,
					    PCUIF_Sapi sapi, octetstring data)
runs on test_CT
{
	var PCUIF_send_data sd;

	timer T := 3.0;
	T.start;
	alt {
	[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id,
				tr_PCUIF_RTS_REQ(bts_nr, trx_nr, ts_nr, sapi))) -> value sd {
		f_pcu_data_req(bts_nr, trx_nr, ts_nr, sd.data.u.rts_req.block_nr,
				  sd.data.u.rts_req.fn, sapi, data);
		}
	[] PCU.receive { repeat; }
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for RTS.ind");
		}
	}
}

/* Send DATA.req on invalid BTS */
testcase TC_pcu_data_req_wrong_bts() runs on test_CT {
	var TfiUsfArr tua := f_TfiUsfArrInit();
	var octetstring data := '0000'O & f_rnd_octstring(21);

	f_virtphy_common();

	f_TC_pcu_act_req(0, 0, 7, true);
	f_TfiUsfArrSet(tua, 7, 0);
	f_L1CTL_TBF_CFG(L1CTL, false, tua);
	f_sleep(1.0);

	f_pcu_to_l1(23, 0, 7, PCU_IF_SAPI_PDTCH, data, false, false);
}

/* Send DATA.req on invalid TRX */
testcase TC_pcu_data_req_wrong_trx() runs on test_CT {
	var TfiUsfArr tua := f_TfiUsfArrInit();
	var octetstring data := '0000'O & f_rnd_octstring(21);

	f_virtphy_common();

	f_TC_pcu_act_req(0, 0, 7, true);
	f_TfiUsfArrSet(tua, 7, 0);
	f_L1CTL_TBF_CFG(L1CTL, false, tua);
	f_sleep(1.0);

	f_pcu_to_l1(0, 100, 7, PCU_IF_SAPI_PDTCH, data, false, false);
}

/* Send DATA.req on invalid timeslot */
testcase TC_pcu_data_req_wrong_ts() runs on test_CT {
	var TfiUsfArr tua := f_TfiUsfArrInit();
	var octetstring data := '0000'O & f_rnd_octstring(21);

	f_virtphy_common();

	f_TC_pcu_act_req(0, 0, 7, true);
	f_TfiUsfArrSet(tua, 7, 0);
	f_L1CTL_TBF_CFG(L1CTL, false, tua);
	f_sleep(1.0);

	f_pcu_to_l1(0, 0, 70, PCU_IF_SAPI_PDTCH, data, false, false);
}

/* Send DATA.req on timeslot that hasn't been activated */
testcase TC_pcu_data_req_ts_inactive() runs on test_CT {
	var TfiUsfArr tua := f_TfiUsfArrInit();
	var octetstring data := '0000'O & f_rnd_octstring(21);

	f_virtphy_common();

	f_TfiUsfArrSet(tua, 7, 0);
	f_L1CTL_TBF_CFG(L1CTL, false, tua);
	f_sleep(1.0);

	f_pcu_to_l1(0, 0, 7, PCU_IF_SAPI_PDTCH, data, false, false);
}

private function f_pcu_to_l1(uint8_t bts_nr, uint8_t trx_nr, uint8_t ts_nr,
			     PCUIF_Sapi sapi, octetstring data, boolean expect_data := true,
			     boolean wait_rts := true)
runs on test_CT {
	timer T := 5.0;
	var L1ctlDlMessage rx_dl;

	PCU.clear;
	if (wait_rts) {
		f_pcu_wait_rts_and_data_req(bts_nr, trx_nr, ts_nr, sapi, data);
	} else {
		f_pcu_data_req(bts_nr, trx_nr, ts_nr, 0, 0, sapi, data);
	}

	T.start;
	alt {
	[expect_data] L1CTL.receive(tr_L1CTL_DATA_IND(t_RslChanNr_PDCH(ts_nr), ?, data)) {
		/* FIXME: why is fn of DATA_IND different to fn of RTS / DATA_REQ above? */
		setverdict(pass);
		}
	[not expect_data] L1CTL.receive(tr_L1CTL_DATA_IND(t_RslChanNr_PDCH(ts_nr), ?, data)) -> value rx_dl {
		setverdict(fail, "Received unexpected ", rx_dl);
		}
	[] L1CTL.receive {
		repeat;
		}
	[expect_data] T.timeout {
		setverdict(fail, "Timeout waiting for ", data);
		}
	[not expect_data] T.timeout {
		setverdict(pass);
		}
	}
}

private function f_disable_dynamic_ts() runs on test_CT
{
	f_init_vty_bsc();
	/* I'm not quite sure why we need this with osmo-bts-virtual.  Somehow it deosn't seem to
	 * support dynamic timeslots?  But it uses the same scheduler as osmo-bts-trx ?!? */
	f_vty_config2(BSCVTY, {"network", "bts 0", "trx 0", "timeslot 3"}, "phys_chan_config TCH/F");
	f_vty_config2(BSCVTY, {"network", "bts 0", "trx 0", "timeslot 4"}, "phys_chan_config TCH/F");
	f_init_pcu_test();
}

private function f_virtphy_common() runs on test_CT {
	f_disable_dynamic_ts();
	f_init_l1ctl();
	f_l1_tune(L1CTL);
}

testcase TC_pcu_data_req_pdtch() runs on test_CT {
	var TfiUsfArr tua := f_TfiUsfArrInit();
	var octetstring data := '0000'O & f_rnd_octstring(21);

	f_virtphy_common();

	f_TC_pcu_act_req(0, 0, 7, true);
	f_TfiUsfArrSet(tua, 7, 0);
	f_L1CTL_TBF_CFG(L1CTL, false, tua);
	f_sleep(1.0);

	f_pcu_to_l1(0, 0, 7, PCU_IF_SAPI_PDTCH, data); //c_PCU_DATA);
}

testcase TC_pcu_data_req_ptcch() runs on test_CT {
	var TfiUsfArr tua := f_TfiUsfArrInit();
	var octetstring data := '0000'O & f_rnd_octstring(21);

	f_virtphy_common();

	f_TC_pcu_act_req(0, 0, 7, true);
	f_TfiUsfArrSet(tua, 7, 0);
	f_L1CTL_TBF_CFG(L1CTL, false, tua);
	f_sleep(1.0);

	f_pcu_to_l1(0, 0, 7, PCU_IF_SAPI_PTCCH, data);
}

/* Send AGCH from PCU; check it appears on Um side */
testcase TC_pcu_data_req_agch() runs on test_CT {
	timer T := 3.0;
	f_init_pcu_test();
	f_init_l1ctl();
	f_l1_tune(L1CTL);

	f_TC_pcu_act_req(0, 0, 7, true);
	f_pcu_data_req(0, 0, 7, 0, 0, PCU_IF_SAPI_AGCH, c_PCU_DATA);

	T.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(t_RslChanNr_PCH_AGCH(0), ?, c_PCU_DATA)) {
		setverdict(pass);
		}
	[] L1CTL.receive { repeat; }
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for PCU-originated AGCH block on Um");
		}
	}
}

/* Send AGCH from PCU; check it appears on Um side */
testcase TC_pcu_data_req_pch() runs on test_CT {
	timer T := 3.0;
	f_init_pcu_test();
	f_init_l1ctl();
	f_l1_tune(L1CTL);

	f_TC_pcu_act_req(0, 0, 7, true);
	/* three characters prefix: last 3 digits of IMSI as ASCII */
	f_pcu_data_req(0, 0, 7, 0, 0, PCU_IF_SAPI_PCH, '313233'O & c_PCU_DATA);

	T.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(t_RslChanNr_PCH_AGCH(0), ?, c_PCU_DATA)) {
		setverdict(pass);
		}
	[] L1CTL.receive { repeat; }
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for PCU-originated PCH block on Um");
		}
	}
}

/* Send IMM.ASS from PCU for PCH; check it appears on Um side */
testcase TC_pcu_data_req_imm_ass_pch() runs on test_CT {
	var octetstring imm_ass := f_rnd_octstring(23);
	f_init_pcu_test();
	f_init_l1ctl();
	f_l1_tune(L1CTL);

	/* append 3 last imsi digits so BTS can compute pagng group */
	var uint32_t fn := f_PCUIF_tx_imm_ass_pch(PCU, g_pcu_conn_id, imm_ass, '123459987'H);

	timer T := 0.5;
	T.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(t_RslChanNr_PCH_AGCH(0), ?, imm_ass)) {
		/* TODO: verify paging group */
		setverdict(pass);
		}
	[] L1CTL.receive { repeat; }
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for PCU-originated AGCH block on Um");
		}
	}
}

/* Send RACH from Um side, expect it to show up on PCU socket */
testcase TC_pcu_rach_content() runs on test_CT {
	f_init_pcu_test();
	f_init_l1ctl();
	f_l1_tune(L1CTL);

	var GsmFrameNumber fn_last := 0;
	for (var integer i := 0; i < 1000; i := i+1) {
		var OCT1 ra := f_rnd_ra_ps();
		var GsmFrameNumber fn := f_L1CTL_RACH(L1CTL, oct2int(ra));
		if (fn == fn_last) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Two RACH in same FN?!?");
		}
		fn_last := fn;

		timer T := 2.0;
		T.start;
		alt {
		[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_RACH_IND(0, oct2int(ra), 0, ?, fn))) {
			T.stop;
			}
		[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_RACH_IND)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unexpected RACH IND");
			}
		[] PCU.receive { repeat; }
		[] T.timeout {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for RACH IND");
			}
		}
	}
	setverdict(pass);
}

/* Send extended (11-bit, TS1 & TS2) RACH bursts from the Um side,
 * expect them to show up on PCU socket (with proper BURST_TYPE_*). */
testcase TC_pcu_ext_rach_content() runs on test_CT {
	var template PCUIF_Message pcu_rach_ind;
	var GsmFrameNumber fn_last := 0;
	var L1ctlRachSynchSeq synch_seq;
	var PCUIF_BurstType pcu_bt;
	var GsmFrameNumber fn;
	var BIT11 ra11;

	f_init_pcu_test();
	f_init_l1ctl();
	f_l1_tune(L1CTL);

	for (var integer i := 0; i < 1000; i := i+1) {
		/* We need to test both TS1 & TS2 */
		if (i rem 2 == 0) {
			synch_seq := RACH_SYNCH_SEQ_TS1;
			pcu_bt := BURST_TYPE_1;
		} else {
			synch_seq := RACH_SYNCH_SEQ_TS2;
			pcu_bt := BURST_TYPE_2;
		}

		ra11 := f_rnd_ra11_ps();
		fn := f_L1CTL_EXT_RACH(L1CTL, bit2int(ra11), synch_seq);
		if (fn == fn_last) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						"Two RACH in same FN?!?");
		}
		fn_last := fn;

		/* Compose the expected message */
		pcu_rach_ind := tr_PCUIF_RACH_IND(
			bts_nr := 0,
			ra := bit2int(ra11),
			is_11bit := 1,
			burst_type := pcu_bt,
			fn := fn);

		timer T := 2.0;
		T.start;
		alt {
		[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, pcu_rach_ind)) {
			T.stop;
			}
		[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_RACH_IND)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unexpected RACH IND");
			}
		[] PCU.receive { repeat; }
		[] T.timeout {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for RACH IND");
			}
		}
	}
	setverdict(pass);
}

private function f_TC_pcu_data_ind_lqual_cb(int16_t lqual_cb_exp, int16_t thresh)
runs on test_CT {
	var template PCUIF_send_data sdt;
	var PCUIF_send_data sd;
	var int16_t lqual_cb;
	timer T := 1.0;

	/* PCUIF_DATA.ind is encapsulated into a supplementary record */
	sdt := t_SD_PCUIF_MSGT(g_pcu_conn_id, PCU_IF_MSG_DATA_IND);

	/* Send a random PDTCH frame over Um */
	L1CTL.send(ts_L1CTL_TRAFFIC_REQ(ts_RslChanNr_PDCH(7), ts_RslLinkID_DCCH(0),
					'0000'O & f_rnd_octstring(21)));

	T.start;
	alt {
	/* If expected link quality is above the threshold */
	[lqual_cb_exp >= thresh] PCU.receive(sdt) -> value sd {
		lqual_cb := sd.data.u.data_ind.lqual_cb;
		log("Rx PCUIF_DATA.ind (lqual_cb=", lqual_cb, ")");

		/* Make sure the actual link quality matches the expected value */
		if (not match(lqual_cb, lqual_cb_exp)) {
			setverdict(fail, log2str("Link quality ", lqual_cb, " does not match ",
						 "expected value ", lqual_cb_exp));
		} else {
			setverdict(pass);
		}
		}
	/* If expected link quality is below the threshold */
	[lqual_cb_exp < thresh] PCU.receive(sdt) -> value sd {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str("Rx unexpected PCUIF_DATA.ind: ", sd.data));
		}
	/* Ignore PCUIF_RTS.req and PCUIF_TIME.ind */
	[] PCU.receive { repeat; }
	[lqual_cb_exp < thresh] T.timeout {
		log("Rx nothing, as expected");
		setverdict(pass);
		}
	[lqual_cb_exp >= thresh] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					"Timeout waiting for PCUIF_DATA.ind");
		}
	}
}

/* Verify C/I (Carrier-to-Interference ratio) processing of PDTCH frames */
testcase TC_pcu_data_ind_lqual_cb() runs on test_CT {
	f_init_pcu_test();
	PCU.clear;

	f_init_l1ctl();
	f_l1_tune(L1CTL);

	/* Activate a PDCH channel on TS7 */
	f_TC_pcu_act_req(0, 0, 7, true);

	/* Tune trxcon to that PDCH channel on TS7 */
	f_L1CTL_DM_EST_REQ(L1CTL, { false, mp_trx0_arfcn },
			   valueof(ts_RslChanNr_PDCH(7)), 7);

	/* C/I in centiBels, test range: -256 .. +1280, step 128 */
	for (var int16_t i := -256; i <= 1280; i := i + 128) {
		var TrxcMessage ret;

		ret := f_TRXC_transceive(BTS_TRXC, g_bts_trxc_conn_id,
					 valueof(ts_TRXC_FAKE_CI(i)));

		/* FIXME: OsmoBTS may have different threshold (see MIN_QUAL_NORM) */
		f_TC_pcu_data_ind_lqual_cb(i, thresh := 0);
	}
}

/* Send PAGING via RSL, expect it to shw up on PCU socket */
testcase TC_pcu_paging_from_rsl() runs on test_CT {
	f_init_pcu_test();

	for (var integer i := 0; i < 100; i := i+1) {
		var MobileL3_CommonIE_Types.MobileIdentityLV mi;
		timer T := 3.0;
		if (i < 50) {
			mi := valueof(ts_MI_TMSI_LV(f_rnd_octstring(4)));
		} else {
			mi := valueof(ts_MI_IMSI_LV(f_gen_imsi(i)));
		}
		var octetstring mi_enc_lv := enc_MobileIdentityLV(mi);
		var octetstring mi_enc := substr(mi_enc_lv, 1, lengthof(mi_enc_lv)-1);
		var octetstring t_mi_lv := f_pad_oct(mi_enc_lv, 9, '00'O);

		/* Send RSL PAGING COMMAND */
		RSL_CCHAN.send(ts_RSL_UD(ts_RSL_PAGING_CMD(mi_enc, i mod 4)));
		T.start;
		alt {
		[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_PAG_REQ(0, t_mi_lv))) {
			}
		[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_PAG_REQ)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unexpected PAGING REQ");
			}
		[] PCU.receive { repeat; }
		[] T.timeout {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for PAGING REQ");
			}
		}
	}
	setverdict(pass);
}

/* test for periodic TIME_IND; check number of FN expired and number of TIME_IND within frames */
testcase TC_pcu_time_ind() runs on test_CT {
	var PCUIF_send_data pcu_sd;
	var integer num_time_ind := 0;
	var integer first_fn, last_fn;
	var float test_duration := 5.0;
	timer T;

	f_init_pcu_test();
	f_TC_pcu_act_req(0, 0, 7, true);

	PCU.clear;
	T.start(test_duration);
	alt {
	[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_TIME_IND(0, ?))) -> value pcu_sd {
		num_time_ind := num_time_ind + 1;
		if (not isbound(first_fn)) {
			first_fn := pcu_sd.data.u.time_ind.fn;
		}
		last_fn := pcu_sd.data.u.time_ind.fn;
		repeat;
		}
	[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_TIME_IND(?, ?))) -> value pcu_sd {
		setverdict(fail, "Received unexpected PCUIF_TIME_IND: ", pcu_sd.data);
		repeat;
		}
	[] PCU.receive {
		repeat;
		}
	[] T.timeout {}
	}
	var integer fn_expired := last_fn - first_fn;
	log(fn_expired, " fn expired with ", num_time_ind, " PCU_TIME.ind");

	/* verify the number of frames expired matches our expectation */
	const float c_GSM_FN_DURATION_MS := 4.61538;
	var float fn_expected := test_duration * 1000.0 / c_GSM_FN_DURATION_MS;
	var template integer t_fn_expected := f_tolerance(float2int(fn_expected), 1, 100000, 20);
	if (not match(fn_expired, t_fn_expected)) {
		setverdict(fail, "Number of TDMA Frames (", fn_expired, ") not matching ", t_fn_expected);
	}

	/* There are three TIME.ind in every fn MOD 13 */
	var float time_ind_expected := int2float(fn_expired) * 3.0 / 13.0;
	/* Add some tolerance */
	var template integer t_time_ind_exp := f_tolerance(float2int(time_ind_expected), 1, 100000, 5);
	if (not match(num_time_ind, t_time_ind_exp)) {
		setverdict(fail, "Number of TIME.ind (", num_time_ind, ") not matching ", t_time_ind_exp);
	}

	setverdict(pass);
}

/* test for periodic RTS_REQ; check number of FN expired and number of RTS_IND per SAPI */
testcase TC_pcu_rts_req() runs on test_CT {
	var PCUIF_send_data pcu_sd;
	var integer first_fn, last_fn;
	var integer num_rts_pdtch := 0;
	var integer num_rts_ptcch := 0;
	var float test_duration := 5.0;
	timer T;

	f_init_pcu_test();
	f_TC_pcu_act_req(0, 0, 7, true);

	PCU.clear;
	T.start(test_duration);
	alt {
	[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_RTS_REQ(0, 0, 7, PCU_IF_SAPI_PDTCH, ?, ?)))
			-> value pcu_sd {
		num_rts_pdtch := num_rts_pdtch + 1;
		if (not isbound(first_fn)) {
			first_fn := pcu_sd.data.u.rts_req.fn;
		}
		last_fn := pcu_sd.data.u.rts_req.fn;
		repeat;
		}
	[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_RTS_REQ(0, 0, 7, PCU_IF_SAPI_PTCCH, ?, ?)))
			-> value pcu_sd {
		num_rts_ptcch := num_rts_ptcch + 1;
		if (not isbound(first_fn)) {
			first_fn := pcu_sd.data.u.rts_req.fn;
		}
		last_fn := pcu_sd.data.u.rts_req.fn;
		repeat;
		}
	[] PCU.receive(t_SD_PCUIF(g_pcu_conn_id, tr_PCUIF_RTS_REQ)) -> value pcu_sd {
		setverdict(fail, "Received unexpected PCUIF_RTS_REQ: ", pcu_sd.data);
		repeat;
		}
	[] PCU.receive {
		repeat;
		}
	[] T.timeout {}
	}
	var integer fn_expired := last_fn - first_fn;
	log(fn_expired, " fn expired with num_rts_pdtch=", num_rts_pdtch,
		", num_rts_ptcch=", num_rts_ptcch);

	/* verify the number of frames expired matches our expectation */
	const float c_GSM_FN_DURATION_MS := 4.61538;
	var float fn_expected := test_duration * 1000.0 / c_GSM_FN_DURATION_MS;
	var template integer t_fn_expected := f_tolerance(float2int(fn_expected), 1, 100000, 20);
	if (not match(fn_expired, t_fn_expected)) {
		setverdict(fail, "Number of TDMA Frames (", fn_expired, ") not matching ", t_fn_expected);
	}

	/* PTCCH is in pos. 12 + 38 of 52-multiframe, but four slots/bursts required per block */
	var float ptcch_expected := int2float(fn_expired) / 52.0 * 0.5;
	var template integer t_ptcch_exp := f_tolerance(float2int(ptcch_expected), 1, 100000, 1);
	if (not match(num_rts_ptcch, t_ptcch_exp)) {
		setverdict(fail, "Number of RTS.ind for PTCCH (", num_rts_ptcch, ") not matching ",
				t_ptcch_exp);
	}

	/* We have 12 PDTCH blocks every 52-multiframe */
	var float pdtch_expected := int2float(fn_expired) / 52.0 * 12.0;
	var template integer t_pdtch_exp := f_tolerance(float2int(pdtch_expected), 1, 100000, 2);
	if (not match(num_rts_pdtch, t_pdtch_exp)) {
		setverdict(fail, "Number of RTS.ind for PDTCH (", num_rts_pdtch, ") not matching ",
				t_pdtch_exp);
	}

	setverdict(pass);
}

/* test for generating Abis side OML ALERT from the PCU */
testcase TC_pcu_oml_alert() runs on test_CT {
	var PCUIF_send_data pcu_sd;
	var integer num_time_ind := 0;
	var integer first_fn, last_fn;
	var float test_duration := 5.0;
	timer T;

	f_init_pcu_test();
	f_TC_pcu_act_req(0, 0, 7, true);

	/* re-connect CTRL port from BTS to BSC */
	f_ipa_ctrl_stop();
	f_ipa_ctrl_start(mp_bsc_ctrl_ip, mp_bsc_ctrl_port);

	/* Send that OML Alert */
	PCU.send(t_SD_PCUIF(g_pcu_conn_id, ts_PCUIF_TXT_IND(0, PCU_OML_ALERT, testcasename())));

	/* This requires https://gerrit.osmocom.org/#/c/osmo-bsc/+/14177 to be merged */
	f_ctrl_exp_trap(IPA_CTRL, "bts.0.oml_failure_report", ?);
	setverdict(pass);
}

template (value) PDU_ML3_MS_NW ts_RRM_GprsSuspReq(template (value) OCT4 tlli,
						  template (value) RoutingAreaIdentificationV rai,
						  template (value) OCT1 cause) := {
	discriminator := '0000'B, /* overwritten */
	tiOrSkip := {
	skipIndicator := '0000'B
	},
	msgs := {
		rrm := {
			gPRS_suspensionRequest := {
				messageType := '00110100'B,
				tLLI := tlli,
				routingAreaIdentification := rai,
				suspensionCause := cause,
				service_Support := omit
			}
		}
	}
}

/* test for forwarding of RR SUSPEND from CS lchan to PCU via PCU socket */
private function f_TC_rr_suspend_req(charstring id) runs on ConnHdlr {
	var PCUIF_Message first_info;
	var integer pcu_conn_id := -1;
	var RslLinkId link_id := valueof(ts_RslLinkID_DCCH(0));
	var RoutingAreaIdentificationV rai := f_RAI('262'H, '42F'H, '2342'O, '55'O);
	var OCT4 tlli := '01020304'O;
	var OCT1 cause := '23'O;
	timer T := 5.0;

	f_init_pcu(PCU, id, pcu_conn_id, first_info);

	f_l1_tune(L1CTL);
	RSL.clear;

	f_est_dchan();
	L1CTL.clear;

	f_est_rll_mo(link_id.sapi, link_id, '23420815'O);

	var PDU_ML3_MS_NW susp_req := valueof(ts_RRM_GprsSuspReq(tlli, rai, cause));
	var octetstring l3 := enc_PDU_ML3_MS_NW(susp_req);
	f_tx_lapdm(ts_LAPDm_I(link_id.sapi, cr_MO_CMD, true, 1, 0, l3), link_id);

	/* ConnHdlr has terminated after sending the RR SUSP REQ over a dedicaed channel */
	T.start;
	alt {
	[] PCU.receive(t_SD_PCUIF(pcu_conn_id, tr_PCUIF_SUSP_REQ(0, tlli, ?, oct2int(cause)))) {
		setverdict(pass);
		}
	[] PCU.receive(t_SD_PCUIF(pcu_conn_id, tr_PCUIF_SUSP_REQ(?, ?, ?, ?))) {
		setverdict(fail, "Received unexpected PCUIF SUSPE REQ: ");
		}
	[] PCU.receive {
		repeat;
		}
	[] T.timeout {
		setverdict(fail, "Timeout waiting for SUSP REQ on PCUIF");
		}
	}

	/* release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_pcu_rr_suspend() runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;

	f_init();

	pars := valueof(t_Pars(t_RslChanNr_SDCCH4(0,3), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_TC_rr_suspend_req), pars, true);
	vc_conn.done;
}

/* Ensure that PCUIF socket can accept only a single connection */
testcase TC_pcu_socket_connect_multi() runs on test_CT {
	timer T := 5.0;

	/* this (among other things) establishes the first connection to the PCUIF socket */
	f_init();

	/* try to establish a second connection, expect it to fail */
	PCU.send(UD_connect:{mp_pcu_socket, -1});
	T.start;
	alt {
	[] PCU.receive(UD_connect_result:{id := ?, result := { result_code := ERROR, err := ? }}) {
		setverdict(pass);
		}
	[] PCU.receive(UD_connect_result:?) {
		setverdict(fail, "Unexpected unix domain connect result");
		}
	[] T.timeout {
		setverdict(pass);
		}
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Ensure that PCUIF socket can disconnect + reconnect */
testcase TC_pcu_socket_reconnect() runs on test_CT {
	/* this (among other things) establishes the first connection to the PCUIF socket */
	f_init();

	f_sleep(1.0);

	f_pcuif_close(PCU, g_pcu_conn_id);
	g_pcu_conn_id := -1;

	f_sleep(1.0);

	/* re-connect */
	PCU.clear;
	f_init_pcu(PCU, testcasename(), g_pcu_conn_id, g_pcu_last_info);
	setverdict(pass);

	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Ensure that GPRS capability is not advertised before PCU socket conncet */
private function f_get_si3(L1CTL_PT pt) runs on test_CT return SystemInformationType3 {
	var L1ctlDlMessage l1_dl;
	var SystemInformation si;
	timer T := 5.0;
	T.start;
	alt {
	[] pt.receive(tr_L1CTL_DATA_IND(t_RslChanNr_BCCH(0), ?)) -> value l1_dl {
		/* somehow dec_SystemInformation will try to decode even non-RR as SI */
		if (not (l1_dl.payload.data_ind.payload[1] ==  '06'O)) {
			log("Ignoring non-RR SI ", l1_dl);
			repeat;
		}
		si := dec_SystemInformation(l1_dl.payload.data_ind.payload)
		if (not ischosen(si.payload.si3)) {
			repeat;
		}
		}
	[] pt.receive {
		repeat;
		}
	[] T.timeout {
		setverdict(fail, "Timeout waiting for SI3");
		}
	}
	return si.payload.si3;
}

/* CSN.1 L/H logic: is the bit at the current position using "inverted logic" (true) or not? */
private function f_bitpos_is_inv(integer idx) return boolean {
	select (idx mod 8) {
	case ((2, 4, 6, 7)) { return true; } /* 1-bits of 0x2B */
	case else { return false; } /* 0-bits of 0x2B */
	}
}
/* determine if the bit at position 'idx' in 'str' is a CSN.1 'H' (true) or 'L' (false) */
private function f_bit_is_high(bitstring str, integer idx) return boolean {
	var boolean invert := f_bitpos_is_inv(idx);
	if (invert) {
		if (str[idx] == '1'B) {
			return false;
		} else {
			return true;
		}
	} else {
		if (str[idx] == '1'B) {
			return true;
		} else {
			return false;
		}
	}
}
/* As the TITAN RAW codec cannot expres the CSN.1 L/H concept yet, we have to do this
   manually.  Let's hope https://www.eclipse.org/forums/index.php/t/1099087/ takes off and
   we can replace this piece of code soon ... */
private function f_si3_has_gprs_indicator(OCT4 si3_restoctets) return boolean {
	var bitstring bits := oct2bit(si3_restoctets);
	var integer idx := 0;

	if (f_bit_is_high(bits, idx)) {
		/* skip Optional selection parameters */
		idx := idx + 16;
	} else {
		idx := idx + 1;
	}

	if (f_bit_is_high(bits, idx)) {
		/* skip Optional power offset */
		idx := idx + 3;
	} else {
		idx := idx + 1;
	}

	/* skip SI2ter Indicator */
	idx := idx + 1;

	/* skip Early CM Sending Control */
	idx := idx + 1;

	/* skip Scheduling if and where */
	if (f_bit_is_high(bits, idx)) {
		idx := idx + 4;
	} else {
		idx := idx + 1;
	}

	return f_bit_is_high(bits, idx);
}

testcase TC_pcu_socket_noconnect_nosi3gprs() runs on test_CT {
	var SystemInformationType3 si3;
	timer T := 5.0;

	/* don't call f_init() as this would connect PCU socket */
	f_init_rsl(testcasename());
	T.start;
	alt {
	[] RSL_CCHAN.receive(ASP_IPA_Event:{up_down := ASP_IPA_EVENT_UP});
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for ASP_IPA_EVENT_UP");
		}
	}
	f_rsl_bcch_fill(RSL_SYSTEM_INFO_3, ts_SI3_default);

	f_init_l1ctl();
	f_l1_tune(L1CTL);

	f_sleep(2.0);
	L1CTL.clear;
	si3 := f_get_si3(L1CTL);
	if (f_si3_has_gprs_indicator(si3.rest_octets)) {
		setverdict(fail, "SI3 indicates GPRS even before PCU socket connected");
	} else {
		setverdict(pass);
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Ensure that GPRS capability is advertised after PCU socket connect */
testcase TC_pcu_socket_connect_si3gprs() runs on test_CT {
	var SystemInformationType3 si3;

	/* this (among other things) establishes the first connection to the PCUIF socket */
	f_init();
	f_init_l1ctl();
	f_l1_tune(L1CTL);

	f_sleep(2.0);
	L1CTL.clear;
	si3 := f_get_si3(L1CTL);
	if (not f_si3_has_gprs_indicator(si3.rest_octets)) {
		setverdict(fail, "SI3 indicates no GPRS despite PCU socket connected");
	} else {
		setverdict(pass);
	}
	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Ensure that GPRS capability is no longer advertised after PCU socket disconnect */
testcase TC_pcu_socket_disconnect_nosi3gprs() runs on test_CT {
	var SystemInformationType3 si3;

	/* this (among other things) establishes the first connection to the PCUIF socket */
	f_init();
	f_init_l1ctl();
	f_l1_tune(L1CTL);

	f_pcuif_close(PCU, g_pcu_conn_id);
	g_pcu_conn_id := -1;

	f_sleep(1.0);

	/* re-connect */
	PCU.clear;
	f_init_pcu(PCU, testcasename(), g_pcu_conn_id, g_pcu_last_info);

	f_sleep(2.0);
	L1CTL.clear;
	si3 := f_get_si3(L1CTL);
	if (f_si3_has_gprs_indicator(si3.rest_octets)) {
		setverdict(fail, "SI3 indicates GPRS after PCU socket disconnected");
	} else {
		setverdict(pass);
	}

	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* Verify that the cell_id of SI3 (TS 04.08 9.1.35) and other values are passed properly to the PCU socket (OS#3854) */
testcase TC_pcu_socket_verify_info_ind() runs on test_CT {
	var SystemInformation si3 := valueof(ts_SI3_default);

	f_init();

	/* Verify cell_id */
	var uint16_t cell_id_si3 := si3.payload.si3.cell_id;
	var uint16_t cell_id_pcu := g_pcu_last_info.u.info_ind.cell_id;
	if (cell_id_si3 != cell_id_pcu) {
		setverdict(fail, "Expected cell_id '", cell_id_si3, "' and got '", cell_id_pcu, "'. This either means,",
				 " that the BTS is sending the wrong cell_id, or that the BTS sent it too early",
				 " (OS#4179)");
	}

	/* Verify LAC */
	var uint16_t lac_si3 := si3.payload.si3.lai.lac;
	var uint16_t lac_pcu := g_pcu_last_info.u.info_ind.lac;
	if (lac_si3 != lac_pcu) {
		setverdict(fail, "Expected LAC ", lac_si3, " got: ", lac_pcu);
	}

	setverdict(pass);
}

/***********************************************************************
 * Osmocom Style Dynamic Timeslot Support
 ***********************************************************************/

private function f_dyn_osmo_pdch_act(integer pcu_conn_id, integer bts_nr, integer trx_nr)
runs on ConnHdlr {
	var PCUIF_send_data sd;
	/* Expect BTS to immediately acknowledge activation as PDCH */
	PCU.clear;
	f_rsl_chan_act(g_pars.chan_mode);
	/* expect INFO_IND on PCU interface listing TS as PDCH */
	timer T_wait := 2.0;
	T_wait.start;
	alt {
	[] PCU.receive(t_SD_PCUIF(pcu_conn_id, tr_PCUIF_INFO_IND(bts_nr, ?))) -> value sd {
		if (substr(sd.data.u.info_ind.trx[trx_nr].pdch_mask, g_chan_nr.tn, 1) != '1'B) {
			log("PCUIF_INFO_IND PDCH_MASK not yet '1' after PDCH ACT on TS", g_chan_nr.tn,
			    " mask:", sd.data.u.info_ind.trx[trx_nr].pdch_mask);
			repeat;
		}
		}
	[] PCU.receive { repeat; }
	[] T_wait.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			log2str("Timeout waiting for PCUIF_INFO_IND PDCH_MASK to be '1' on TS", g_chan_nr.tn));
		}
	}
	/* try to activate this PDCH from the PCU point of view */
	PCU.send(t_SD_PCUIF(pcu_conn_id, ts_PCUIF_ACT_REQ(bts_nr, trx_nr, g_chan_nr.tn)));
	/* FIXME: is there a response? */
}

private function f_dyn_osmo_pdch_deact(integer pcu_conn_id, integer bts_nr, integer trx_nr)
runs on ConnHdlr {
	var PCUIF_send_data sd;
	/* Send RSL CHAN REL (deactivate) */
	PCU.clear;
	RSL.send(ts_RSL_RF_CHAN_REL(g_chan_nr));
	/* expect BTS to ask PCU to deactivate the channel */
	timer T_wait := 2.0;
	T_wait.start;
	alt {
	[] PCU.receive(t_SD_PCUIF(pcu_conn_id, tr_PCUIF_INFO_IND(bts_nr, ?))) -> value sd {
		if (substr(sd.data.u.info_ind.trx[trx_nr].pdch_mask, g_chan_nr.tn, 1) != '0'B) {
			log("PCUIF_INFO_IND PDCH_MASK not yet '0' after PDCH DEACT on TS", g_chan_nr.tn,
			    " mask:", sd.data.u.info_ind.trx[trx_nr].pdch_mask);
			repeat;
		}
		}
	[] PCU.receive { repeat; }
	[] T_wait.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			log2str("Timeout waiting for PCUIF_INFO_IND PDCH_MASK to be '0' on TS", g_chan_nr.tn));
		}
	}
	/* Emulate PCU asking BTS to deactivate PDCH */
	PCU.send(t_SD_PCUIF(pcu_conn_id, ts_PCUIF_DEACT_REQ(bts_nr, trx_nr, g_chan_nr.tn)));
	alt {
	[] RSL.receive(tr_RSL_RF_CHAN_REL_ACK(g_chan_nr)) {
		setverdict(pass);
		}
	[] RSL.receive { repeat; }
	}
}

/* Activate Osmocom-style dynamic PDCH from BSC side */
function f_TC_dyn_osmo_pdch_act_deact(charstring id) runs on ConnHdlr {
	var PCUIF_Message first_info;
	var integer ts_nr := g_chan_nr.tn;
	var integer trx_nr := 0;
	var integer bts_nr := 0;
	var integer pcu_conn_id := -1;

	f_init_pcu(PCU, id, pcu_conn_id, first_info);

	f_dyn_osmo_pdch_act(pcu_conn_id, bts_nr, trx_nr);
	f_sleep(3.0);
	f_dyn_osmo_pdch_deact(pcu_conn_id, bts_nr, trx_nr);
	setverdict(pass);
}
testcase TC_dyn_osmo_pdch_act_deact() runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;
	f_init();

	pars := valueof(t_Pars(t_RslChanNr_PDCH(4), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_TC_dyn_osmo_pdch_act_deact), pars, true);
	vc_conn.done;
}

/* send a RF CHAN REL for PDCH on an osmocom dynamci PDCH that's already inactive */
function f_TC_dyn_osmo_pdch_unsol_deact(charstring id) runs on ConnHdlr {
	var PCUIF_Message first_info;
	var integer pcu_conn_id := -1;

	f_init_pcu(PCU, id, pcu_conn_id, first_info);

	RSL.send(ts_RSL_RF_CHAN_REL(g_chan_nr));
	/* since the lchan is already released, we don't expect any PCU changes, just a rel ack. */
	RSL.receive(tr_RSL_RF_CHAN_REL_ACK(g_chan_nr));
	setverdict(pass);
}
testcase TC_dyn_osmo_pdch_unsol_deact() runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;
	f_init();

	pars := valueof(t_Pars(t_RslChanNr_PDCH(4), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_TC_dyn_osmo_pdch_unsol_deact), pars, true);
	vc_conn.done;
}

/* try to RSL CHAN ACT a PDCH on an osmocom-style PDCH that's already active */
function f_TC_dyn_osmo_pdch_double_act(charstring id) runs on ConnHdlr {
	var PCUIF_Message first_info;
	var integer ts_nr := g_chan_nr.tn;
	var integer trx_nr := 0;
	var integer bts_nr := 0;
	var integer pcu_conn_id := -1;

	f_init_pcu(PCU, id, pcu_conn_id, first_info);

	f_dyn_osmo_pdch_act(pcu_conn_id, bts_nr, trx_nr);
	/* Send a second Chan Activ and expect it to be NACKed */
	f_rsl_transceive(ts_RSL_CHAN_ACT(g_chan_nr, g_pars.chan_mode), tr_RSL_CHAN_ACT_NACK(g_chan_nr),
			 "RSL CHAN ACT NACK");
	setverdict(pass);
}
testcase TC_dyn_osmo_pdch_double_act() runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;
	f_init();

	pars := valueof(t_Pars(t_RslChanNr_PDCH(4), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_TC_dyn_osmo_pdch_double_act), pars, true);
	vc_conn.done;
}

/* try to RSL CHAN ACT a TCH/F on an osmocom-style PDCH */
function f_TC_dyn_osmo_pdch_tchf_act(charstring id) runs on ConnHdlr {
	var PCUIF_Message first_info;
	var integer ts_nr := g_chan_nr.tn;
	var integer trx_nr := 0;
	var integer bts_nr := 0;
	var integer pcu_conn_id := -1;
	var RslChannelNr chan_nr := valueof(t_RslChanNr_Bm(g_chan_nr.tn));

	/* register for the TCH/F channel number */
	f_rslem_register(0, chan_nr);

	f_init_pcu(PCU, id, pcu_conn_id, first_info);

	f_rsl_transceive(ts_RSL_CHAN_ACT(chan_nr, g_pars.chan_mode), tr_RSL_CHAN_ACT_ACK(chan_nr),
			 "RSL CHAN ACT");
	setverdict(pass);
}
testcase TC_dyn_osmo_pdch_tchf_act() runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;
	f_init();

	pars := valueof(t_Pars(t_RslChanNr_PDCH(4), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_TC_dyn_osmo_pdch_tchf_act), pars, true);
	vc_conn.done;
}

/* try to RSL CHAN ACT the TCH/H on an osmocom-style PDCH */
function f_TC_dyn_osmo_pdch_tchh_act(charstring id) runs on ConnHdlr {
	var PCUIF_Message first_info;
	var integer ts_nr := g_chan_nr.tn;
	var integer trx_nr := 0;
	var integer bts_nr := 0;
	var integer pcu_conn_id := -1;
	var RslChannelNr chan_nr[2] := { valueof(t_RslChanNr_Lm(g_chan_nr.tn, 0)),
					 valueof(t_RslChanNr_Lm(g_chan_nr.tn, 1)) };

	/* register for the TCH/H channel numbers */
	f_rslem_register(0, chan_nr[0]);
	f_rslem_register(0, chan_nr[1]);

	f_init_pcu(PCU, id, pcu_conn_id, first_info);

	f_rsl_transceive(ts_RSL_CHAN_ACT(chan_nr[1], g_pars.chan_mode),
			 tr_RSL_CHAN_ACT_ACK(chan_nr[1]), "RSL CHAN ACT [1]");
	f_rsl_transceive(ts_RSL_CHAN_ACT(chan_nr[0], g_pars.chan_mode),
			 tr_RSL_CHAN_ACT_ACK(chan_nr[0]), "RSL CHAN ACT [0]");
	setverdict(pass);
}
testcase TC_dyn_osmo_pdch_tchh_act() runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;
	f_init();

	pars := valueof(t_Pars(t_RslChanNr_PDCH(4), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_TC_dyn_osmo_pdch_tchh_act), pars, true);
	vc_conn.done;
}

/***********************************************************************
 * IPA Style Dynamic Timeslot Support
 ***********************************************************************/

private function f_dyn_ipa_pdch_act(integer pcu_conn_id, integer bts_nr, integer trx_nr)
runs on ConnHdlr {
	var PCUIF_send_data sd;
	/* Expect BTS to immediately acknowledge activation as PDCH */
	PCU.clear;
	RSL.send(ts_RSL_IPA_PDCH_ACT(g_chan_nr));
	/* expect INFO_IND on PCU interface listing TS as PDCH */
	timer T_wait := 2.0;
	T_wait.start;
	alt {
	[] PCU.receive(t_SD_PCUIF(pcu_conn_id, tr_PCUIF_INFO_IND(bts_nr, ?))) -> value sd {
		if (substr(sd.data.u.info_ind.trx[trx_nr].pdch_mask, g_chan_nr.tn, 1) != '1'B) {
			log("PCUIF_INFO_IND PDCH_MASK not yet '1' after PDCH ACT on TS", g_chan_nr.tn,
			    " mask:", sd.data.u.info_ind.trx[trx_nr].pdch_mask);
			repeat;
		}
		}
	[] PCU.receive { repeat; }
	[] T_wait.timeout {
	        Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			log2str("Timeout waiting for PCUIF_INFO_IND PDCH_MASK to be '1' on TS", g_chan_nr.tn));
	        }
	}
	/* try to activate this PDCH from the PCU point of view */
	PCU.send(t_SD_PCUIF(pcu_conn_id, ts_PCUIF_ACT_REQ(bts_nr, trx_nr, g_chan_nr.tn)));
	/* FIXME: is there a response? */

	RSL.receive(tr_RSL_IPA_PDCH_ACT_ACK(g_chan_nr, ?));
}

private function f_dyn_ipa_pdch_deact(integer pcu_conn_id, integer bts_nr, integer trx_nr)
runs on ConnHdlr {
	var PCUIF_send_data sd;
	/* Send RSL CHAN REL (deactivate) */
	RSL.send(ts_RSL_IPA_PDCH_DEACT(g_chan_nr));
	PCU.clear;
	/* expect BTS to ask PCU to deactivate the channel */
	timer T_wait := 2.0;
	T_wait.start;
	alt {
	[] PCU.receive(t_SD_PCUIF(pcu_conn_id, tr_PCUIF_INFO_IND(bts_nr, ?))) -> value sd {
		if (substr(sd.data.u.info_ind.trx[trx_nr].pdch_mask, g_chan_nr.tn, 1) != '0'B) {
			log("PCUIF_INFO_IND PDCH_MASK not yet '0' after PDCH DEACT on TS", g_chan_nr.tn,
			    " mask:", sd.data.u.info_ind.trx[trx_nr].pdch_mask);
			repeat;
		}
		}
	[] PCU.receive { repeat; }
	[] T_wait.timeout {
	        Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			log2str("Timeout waiting for PCUIF_INFO_IND PDCH_MASK to be '0' on TS", g_chan_nr.tn));
	        }
	}
	/* Emulate PCU asking BTS to deactivate PDCH */
	PCU.send(t_SD_PCUIF(pcu_conn_id, ts_PCUIF_DEACT_REQ(bts_nr, trx_nr, g_chan_nr.tn)));
	alt {
	[] RSL.receive(tr_RSL_IPA_PDCH_DEACT_ACK(g_chan_nr)) {
		setverdict(pass);
		}
	[] RSL.receive { repeat; }
	}
}

/* Activate and de-activate an IPA-style dynamic TCH/F + PDCH */
function f_TC_dyn_ipa_pdch_act_deact(charstring id) runs on ConnHdlr {
	var PCUIF_Message first_info;
	var integer ts_nr := g_chan_nr.tn;
	var integer trx_nr := 0;
	var integer bts_nr := 0;
	var integer pcu_conn_id := -1;

	f_init_pcu(PCU, id, pcu_conn_id, first_info);

	f_dyn_ipa_pdch_act(pcu_conn_id, bts_nr, trx_nr);
	f_sleep(3.0);
	f_dyn_ipa_pdch_deact(pcu_conn_id, bts_nr, trx_nr);

	setverdict(pass);

}
testcase TC_dyn_ipa_pdch_act_deact() runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;
	f_init();

	pars := valueof(t_Pars(t_RslChanNr_Bm(3), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_TC_dyn_ipa_pdch_act_deact), pars, true);
	vc_conn.done;
}

/* try to RSL CHAN ACT a TCH/F on an IPA-style PDCH */
function f_TC_dyn_ipa_pdch_tchf_act(charstring id) runs on ConnHdlr {
	var PCUIF_Message first_info;
	var integer ts_nr := g_chan_nr.tn;
	var integer trx_nr := 0;
	var integer bts_nr := 0;
	var integer pcu_conn_id := -1;

	f_init_pcu(PCU, id, pcu_conn_id, first_info);

	f_rsl_transceive(ts_RSL_CHAN_ACT(g_chan_nr, g_pars.chan_mode), tr_RSL_CHAN_ACT_ACK(g_chan_nr),
			 "RSL CHAN ACT");
	f_rsl_transceive(ts_RSL_RF_CHAN_REL(g_chan_nr), tr_RSL_RF_CHAN_REL_ACK(g_chan_nr),
			"RF CHAN REL", true);
	setverdict(pass);
}
testcase TC_dyn_ipa_pdch_tchf_act() runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;
	f_init();

	pars := valueof(t_Pars(t_RslChanNr_Bm(3), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_TC_dyn_ipa_pdch_tchf_act), pars, true);
	vc_conn.done;
}

/* Activate IPA style dyn PDCH as TCH/F and then illegally try to activate it as PDCH, too */
function f_TC_dyn_ipa_pdch_tchf_act_pdch_act_nack(charstring id) runs on ConnHdlr {
	var PCUIF_Message first_info;
	var integer ts_nr := g_chan_nr.tn;
	var integer trx_nr := 0;
	var integer bts_nr := 0;
	var integer pcu_conn_id := -1;

	f_init_pcu(PCU, id, pcu_conn_id, first_info);

	f_rsl_transceive(ts_RSL_CHAN_ACT(g_chan_nr, g_pars.chan_mode), tr_RSL_CHAN_ACT_ACK(g_chan_nr),
			 "RSL CHAN ACT");

	RSL.send(ts_RSL_IPA_PDCH_ACT(g_chan_nr));
	alt {
	[] RSL.receive(tr_RSL_IPA_PDCH_ACT_NACK(g_chan_nr, ?));
	[] RSL.receive(tr_RSL_IPA_PDCH_ACT_ACK(g_chan_nr, ?)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unexpected PDCH ACT ACK");
		}
	[] RSL.receive { repeat; }
	}

	f_rsl_transceive(ts_RSL_RF_CHAN_REL(g_chan_nr), tr_RSL_RF_CHAN_REL_ACK(g_chan_nr),
			"RF CHAN REL", true);
	setverdict(pass);
}
testcase TC_dyn_ipa_pdch_tchf_act_pdch_act_nack() runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;
	f_init();

	pars := valueof(t_Pars(t_RslChanNr_Bm(3), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_TC_dyn_ipa_pdch_tchf_act_pdch_act_nack), pars, true);
	vc_conn.done;
}

/* try to RSL CHAN ACT a TCH/F on an IPA-style PDCH that's already in PDCH mode; expect NACK */
function f_TC_dyn_ipa_pdch_act_tchf_act_nack(charstring id) runs on ConnHdlr {
	var PCUIF_Message first_info;
	var integer ts_nr := g_chan_nr.tn;
	var integer trx_nr := 0;
	var integer bts_nr := 0;
	var integer pcu_conn_id := -1;

	/* register for the TCH/F channel number */
	f_rslem_register(0, g_chan_nr);

	f_init_pcu(PCU, id, pcu_conn_id, first_info);

	f_dyn_ipa_pdch_act(pcu_conn_id, bts_nr, trx_nr);

	f_rsl_transceive(ts_RSL_CHAN_ACT(g_chan_nr, g_pars.chan_mode), tr_RSL_CHAN_ACT_NACK(g_chan_nr),
			 "RSL CHAN ACT");

	f_dyn_ipa_pdch_deact(pcu_conn_id, bts_nr, trx_nr);

	setverdict(pass);
}
testcase TC_dyn_ipa_pdch_act_tchf_act_nack() runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;
	f_init();

	pars := valueof(t_Pars(t_RslChanNr_Bm(3), ts_RSL_ChanMode_SIGN));
	vc_conn := f_start_handler(refers(f_TC_dyn_ipa_pdch_act_tchf_act_nack), pars, true);
	vc_conn.done;
}


/***********************************************************************
 * LAPDm / RLL related
 ***********************************************************************/

private function f_tx_lapdm(template (value) LapdmFrame l,
			    template (value) RslLinkId link_id) runs on ConnHdlr {
	var octetstring l2 := enc_LapdmFrame(valueof(l));
	var template (value) SacchL1Header l1h;

	/* TODO: we can use an extension of TTCN-3 for padding, i.e. PADDING('2B'O) */
	if (valueof(link_id.c) == SACCH) {
		/* Compose dummy L1 header */
		l1h := ts_SacchL1Header(g_pars.l1_pars.ms_power_level, false, g_pars.l1_pars.ms_actual_ta);
		L1CTL.send(ts_L1CTL_DATA_REQ_SACCH(g_chan_nr, link_id, l1h, f_pad_oct(l2, 21, '2B'O)));
	} else {
		/* If required, pad L2 frame with constant 0x2b filling */
		L1CTL.send(ts_L1CTL_DATA_REQ(g_chan_nr, link_id, f_pad_oct(l2, 23, '2B'O)));
	}
}

type record RllTestCase {
	uint3_t		sapi,
	RslLinkId	link_id,
	octetstring	l3,
	boolean		exp
}
type record of RllTestCase RllTestCases;
template RllTestCase t_EITC(uint3_t sapi, RslLinkId id, octetstring l3, boolean exp) := {
	sapi := sapi,
	link_id := id,
	l3 := l3,
	exp := exp
}

/* execute the same callback function with a set of different parameters (tcs) on a
 * variety of logical channels */
private function f_rll_testmatrix(RllTestCases tcs, void_fn fn) runs on test_CT {
	var ConnHdlrPars pars;
	var ConnHdlr vc_conn;
	f_init();

	/* test on each of the channels we have */
	for (var integer i := 0; i < sizeof(g_AllChanTypes); i := i+1) {
		pars := valueof(t_Pars(g_AllChanTypes[i], ts_RSL_ChanMode_SIGN));

		/* test each of the test cases on the current channel */
		for (var integer j := 0; j < sizeof(tcs); j := j+1) {
			pars.spec.rll := tcs[j];
			log(testcasename(), ": XXX Starting ", tcs[j] , " on ", g_AllChanTypes[i]);
			vc_conn := f_start_handler(fn, pars);
			vc_conn.done;
		}
	}

	Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
}

/* test if SABM on Um triggers EST IND (TS 48.058 3.1) */
private function f_TC_rll_est_ind(charstring id) runs on ConnHdlr {
	var RllTestCase tc := g_pars.spec.rll;
	timer T := 3.0;

	f_l1_tune(L1CTL);
	RSL.clear;

	/* activate the logical channel */
	f_est_dchan();
	L1CTL.clear;

	f_tx_lapdm(ts_LAPDm_SABM(tc.sapi, cr_MO_CMD, true, tc.l3), tc.link_id);
	T.start;
	alt {
	[tc.l3 != ''O] RSL.receive(tr_RSL_EST_IND(g_chan_nr, tc.link_id, tc.l3)) {
		if (tc.exp) {
			setverdict(pass);
		} else {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Unexpected EST IND with L3 in ", tc));
		}
		}
	[tc.l3 == ''O] RSL.receive(tr_RSL_EST_IND_NOL3(g_chan_nr, tc.link_id)) {
		if (tc.exp) {
			setverdict(pass);
		} else {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Unexpected EST IND without L3 in ", tc));
		}
		}
	/* We also expect to receive the measurements */
	[] as_meas_res(verify_meas := false);
	[tc.exp] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for EST IND");
		}
	[not tc.exp] T.timeout {
		setverdict(pass);
		}
	}

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_rll_est_ind() runs on test_CT {
	var RllTestCases tcs := {
		/* SAPI0 establishment (contention resolution) */
		valueof(t_EITC(0, valueof(ts_RslLinkID_DCCH(0)), '01020304'O, true)),
		/* normal SAPI0 establishment */
		valueof(t_EITC(0, valueof(ts_RslLinkID_DCCH(0)), ''O, true)),
		/* SAPI 3 doesn't support contention resolution */
		valueof(t_EITC(3, valueof(ts_RslLinkID_DCCH(3)), '01020304'O, false)),
		valueof(t_EITC(3, valueof(ts_RslLinkID_SACCH(3)), '01020304'O, false)),
		/* normal SAPI3 establishment on main DCCH */
		valueof(t_EITC(3, valueof(ts_RslLinkID_DCCH(3)), ''O, true)),
		/* normal SAPI3 establishment on SACCH */
		valueof(t_EITC(3, valueof(ts_RslLinkID_SACCH(3)), ''O, true))
	};
	f_rll_testmatrix(tcs, refers(f_TC_rll_est_ind));
}

/* test if RLL EST REQ trigeres SABM on Um; UA on Um triggers EST CONF (TS 48.058 3.2) */
private function f_TC_rll_est_req(charstring id) runs on ConnHdlr {
	var RllTestCase tc := g_pars.spec.rll;
	var L1ctlDlMessage dl;
	timer T := 3.0;

	f_l1_tune(L1CTL);
	RSL.clear;

	/* activate the logical channel */
	f_est_dchan();
	L1CTL.clear;

	/* Send a RSL EST REQ for SAPI3 on main DCCH */
	RSL.send(ts_RSL_EST_REQ(g_chan_nr, tc.link_id));
	T.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, ?)) -> value dl {
		var LapdmFrame lapdm;
		var octetstring l2 := dl.payload.data_ind.payload;
		if (dl.dl_info.link_id.c == SACCH) {
			/* remove L1 header */
			l2 := substr(l2, 2, lengthof(l2)-2);
		}
		lapdm.ab := dec_LapdmFrameAB(l2);
		if (match(lapdm, tr_LAPDm_SABM(tc.sapi, cr_MT_CMD, true, ''O))) {
			setverdict(pass);
		} else {
			repeat;
		}
		}
	[] L1CTL.receive { repeat; }
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for SABM");
		}
	}

	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_rll_est_req_DCCH_3() runs on test_CT {
	var RllTestCases tcs := {
		/* normal SAPI3 establishment on main DCCH */
		valueof(t_EITC(3, valueof(ts_RslLinkID_DCCH(3)), ''O, true))//,
	};
	f_rll_testmatrix(tcs, refers(f_TC_rll_est_req));
}
testcase TC_rll_est_req_ACCH_3() runs on test_CT {
	var RllTestCases tcs := {
		/* normal SAPI3 establishment on SACCH */
		valueof(t_EITC(3, valueof(ts_RslLinkID_SACCH(3)), ''O, true))
	}
	f_rll_testmatrix(tcs, refers(f_TC_rll_est_req));
}

/* altstep to receive a LAPDm frame matching the given template */
private altstep as_l1_exp_lapdm(template LapdmFrame exp) runs on ConnHdlr {
	var L1ctlDlMessage dl;
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, ?)) -> value dl {
		var LapdmFrame lapdm;
		var octetstring l2 := dl.payload.data_ind.payload;
		if (dl.dl_info.link_id.c == SACCH) {
			/* remove L1 header */
			l2 := substr(l2, 2, lengthof(l2)-2);
		}
		if (ischosen(exp.ab)) {
			lapdm.ab := dec_LapdmFrameAB(l2);
		} else if (ischosen(exp.b4)) {
			lapdm.b4 := dec_LapdmFrameB4(l2);
		} else if (ischosen(exp.bbis)) {
			lapdm.bbis := dec_LapdmFrameBbis(l2);
		}
		log("Rx LAPDm ", lapdm);
		if (match(lapdm, exp)) {
			setverdict(pass);
		} else {
			repeat;
		}
		}
	[] L1CTL.receive { repeat; }
}
private function f_l1_exp_lapdm(template LapdmFrame exp, float t := 3.0) runs on ConnHdlr {
	timer T := t;
	T.start;
	alt {
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str("Timeout waiting for LAPDm ", exp));
		}
	[] as_l1_exp_lapdm(exp);
	}
}

/* establish one Radio Link Layer via SABM -> UA. Use l3 for contention resolution */
private function f_est_rll_mo(uint3_t sapi, RslLinkId link_id, octetstring l3) runs on ConnHdlr {
	/* send SABM from MS -> BTS */
	f_tx_lapdm(ts_LAPDm_SABM(sapi, cr_MO_CMD, true, l3), link_id);
	/* expect RLL EST IND on Abis */
	alt {
	[l3 != ''O] RSL.receive(tr_RSL_EST_IND(g_chan_nr, link_id, l3));
	[l3 == ''O] RSL.receive(tr_RSL_EST_IND_NOL3(g_chan_nr, link_id));
	[] RSL.receive(tr_RSL_ERROR_IND(g_chan_nr, link_id, ?)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Failing due to RSL_ERROR_IND");
		}
	[] RSL.receive { repeat; }
	}
	/* expect UA from BTS -> MS */
	f_l1_exp_lapdm(tr_LAPDm_UA(sapi, cr_MT_RSP, true, l3));
}

/* test if DISC on Um triggers RLL REL IND (TS 48.058 3.3) */
private function f_TC_rll_rel_ind(charstring id) runs on ConnHdlr {
	var RllTestCase tc := g_pars.spec.rll;

	f_l1_tune(L1CTL);
	RSL.clear;

	/* activate the logical channel */
	f_est_dchan();
	L1CTL.clear;

	/* first establish the link-layer */
	f_est_rll_mo(tc.sapi, tc.link_id, tc.l3);

	/* then send the DISC */
	f_tx_lapdm(ts_LAPDm_DISC(tc.sapi, cr_MO_CMD, true), tc.link_id);
	/* ... and expect the REL IND on the RSL side */
	alt {
	[] RSL.receive(tr_RSL_REL_IND(g_chan_nr, tc.link_id)) {
		setverdict(pass);
		}
	/* We also expect to receive the measurements */
	[] as_meas_res(verify_meas := false);
	}

	/* release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_rll_rel_ind_DCCH_0() runs on test_CT {
	var RllTestCases tcs := {
		valueof(t_EITC(0, valueof(ts_RslLinkID_DCCH(0)), '01020304'O, true))
	};
	f_rll_testmatrix(tcs, refers(f_TC_rll_rel_ind));
}

testcase TC_rll_rel_ind_ACCH_0() runs on test_CT {
	var RllTestCases tcs := {
		valueof(t_EITC(0, valueof(ts_RslLinkID_SACCH(0)), ''O, true))
	};
	f_rll_testmatrix(tcs, refers(f_TC_rll_rel_ind));
}
testcase TC_rll_rel_ind_DCCH_3() runs on test_CT {
	var RllTestCases tcs := {
		valueof(t_EITC(3, valueof(ts_RslLinkID_DCCH(3)), ''O, true))
	};
	f_rll_testmatrix(tcs, refers(f_TC_rll_rel_ind));
}
testcase TC_rll_rel_ind_ACCH_3() runs on test_CT {
	var RllTestCases tcs := {
		valueof(t_EITC(3, valueof(ts_RslLinkID_SACCH(3)), ''O, true))
	};
	f_rll_testmatrix(tcs, refers(f_TC_rll_rel_ind));
}

/* test if RLL REL REQ triggers DISC on Um; UA/DM triggers RLL REL CONF (TS 48.058 3.4) */
private function f_TC_rll_rel_req(charstring id) runs on ConnHdlr {
	var RllTestCase tc := g_pars.spec.rll;
	f_l1_tune(L1CTL);
	RSL.clear;

	/* activate the logical channel */
	f_est_dchan();
	L1CTL.clear;

	/* first establish the link-layer */
	f_est_rll_mo(tc.sapi, tc.link_id, tc.l3);

	/* then send the REL REQ via RSL */
	RSL.send(ts_RSL_REL_REQ(g_chan_nr, tc.link_id, RSL_REL_MODE_NORMAL));
	/* ... and expect the DISC on the Um side */
	alt {
	[] as_l1_exp_lapdm(tr_LAPDm_DISC(tc.sapi, cr_MT_CMD, true))  {
		/* FIXME: send a UA in resposne to the DISC */
		}
	}

	/* release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_rll_rel_req() runs on test_CT {
	var RllTestCases tcs := {
		valueof(t_EITC(0, valueof(ts_RslLinkID_DCCH(0)), '01020304'O, true)),
		valueof(t_EITC(0, valueof(ts_RslLinkID_SACCH(0)), ''O, true)),
		valueof(t_EITC(3, valueof(ts_RslLinkID_DCCH(3)), ''O, true)),
		valueof(t_EITC(3, valueof(ts_RslLinkID_SACCH(3)), ''O, true))
	};
	f_rll_testmatrix(tcs, refers(f_TC_rll_rel_req));
}

/* test if RLL DATA REQ triggers I-frames on Um (TS 48.058 3.5) */
testcase TC_rll_data_req() runs on test_CT {
}

/* test if I-frames on Um trigger RLL DATA IND (TS 48.058 3.6) */
testcase TC_rll_data_ind() runs on test_CT {
}

/* test if RLL UNIT DATA REQ triggers UI-frame on Um (TS 48.058 3.7) */
private function f_TC_rll_ud_req(charstring id) runs on ConnHdlr {
	var RllTestCase tc := g_pars.spec.rll;

	f_l1_tune(L1CTL);
	RSL.clear;

	f_est_dchan();
	L1CTL.clear;

	/* Send UNITDATA REQ on RSL side */
	RSL.send(ts_RSL_UNITDATA_REQ(g_chan_nr, tc.link_id, tc.l3));
	/* Expect it to arrive on the other side */
	if (tc.link_id.c == SACCH) {
		f_l1_exp_lapdm(tr_LAPDm_B4_UI(tc.sapi, cr_MT_CMD, tc.l3));
	} else {
		f_l1_exp_lapdm(tr_LAPDm_UI(tc.sapi, cr_MT_CMD, tc.l3));
	}

	/* release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_rll_unit_data_req_DCCH() runs on test_CT {
	var octetstring l3 := f_rnd_octstring(15);
	var RllTestCases tcs := {
		valueof(t_EITC(0, valueof(ts_RslLinkID_DCCH(0)), l3, true)),
		valueof(t_EITC(3, valueof(ts_RslLinkID_DCCH(3)), l3, true))
	};
	f_rll_testmatrix(tcs, refers(f_TC_rll_ud_req));
}
testcase TC_rll_unit_data_req_ACCH() runs on test_CT {
	var octetstring l3 := f_rnd_octstring(19);
	var RllTestCases tcs := {
		valueof(t_EITC(0, valueof(ts_RslLinkID_SACCH(0)), l3, true)),
		valueof(t_EITC(3, valueof(ts_RslLinkID_SACCH(3)), l3, true))
	};
	f_rll_testmatrix(tcs, refers(f_TC_rll_ud_req));
}

/* test if UI-frames on Um trigger RLL UNIT DATA IND (TS 48.058 3.8) */
private function f_TC_rll_ud_ind(charstring id) runs on ConnHdlr {
	var RllTestCase tc := g_pars.spec.rll;

	f_l1_tune(L1CTL);
	RSL.clear;

	f_est_dchan();
	L1CTL.clear;

	/* Send LAPDm UI frame. There is no B4 format in uplink! */
	f_tx_lapdm(ts_LAPDm_UI(tc.sapi, cr_MO_CMD, tc.l3), tc.link_id);
	/* Expdct RLL UNITDATA IND on RSL side */
	alt {
	[] RSL.receive(tr_RSL_UNITDATA_IND(g_chan_nr, tc.link_id, tc.l3)) {
		setverdict(pass);
		}
	[] RSL.receive { repeat; }
	}

	/* release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_rll_unit_data_ind_DCCH() runs on test_CT {
	var octetstring l3 := f_rnd_octstring(20);
	var RllTestCases tcs := {
		valueof(t_EITC(0, valueof(ts_RslLinkID_DCCH(0)), l3, true)),
		valueof(t_EITC(3, valueof(ts_RslLinkID_DCCH(3)), l3, true))
	};
	f_rll_testmatrix(tcs, refers(f_TC_rll_ud_ind));
}
testcase TC_rll_unit_data_ind_ACCH() runs on test_CT {
	var octetstring l3 := f_rnd_octstring(18);
	var RllTestCases tcs := {
		valueof(t_EITC(0, valueof(ts_RslLinkID_SACCH(0)), l3, true)),
		valueof(t_EITC(3, valueof(ts_RslLinkID_SACCH(3)), l3, true))
	};
	f_rll_testmatrix(tcs, refers(f_TC_rll_ud_ind));
}

/***********************************************************************
 * Encryption Related
 ***********************************************************************/

/* send UNITDATA_REQ from BTS to MS and expect it to arrive */
function f_unitdata_mt(RslLinkId link_id, octetstring l3) runs on ConnHdlr {
	RSL.send(ts_RSL_UNITDATA_REQ(g_chan_nr, link_id, l3));
	if (link_id.c == SACCH) {
		f_l1_exp_lapdm(tr_LAPDm_B4_UI(link_id.sapi, cr_MT_CMD, l3));
	} else {
		f_l1_exp_lapdm(tr_LAPDm_UI(link_id.sapi, cr_MT_CMD, l3));
	}
}

/* Expect (or not expect) other kinds of messages */
private altstep as_rsl_any_ind(boolean exp_any) runs on ConnHdlr {
	[exp_any] RSL.receive { repeat; }
	[not exp_any] RSL.receive {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unexpected RSL message!");
		}
}

/* Send UI frame from MS and expect it to arrive as RLL UNITDATA IND on Abis */
private function f_unitdata_mo(
	RslLinkId link_id,
	octetstring l3,
	boolean exp_sacch := true, /* Should tolerate SACCH messages? */
	boolean exp_any := false /* Should tolerate any other RSL messages? */
) runs on ConnHdlr {
	timer T := 3.0;
	f_tx_lapdm(ts_LAPDm_UI(link_id.sapi, cr_MO_CMD, l3), link_id);
	T.start;
	/* Expect RLL UNITDATA IND on RSL side */
	alt {
	[] RSL.receive(tr_RSL_UNITDATA_IND(g_chan_nr, link_id, l3)) {
		setverdict(pass);
		}
	[exp_sacch] as_meas_res(verify_meas := false);
	[] as_rsl_any_ind(exp_any);
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for UNIT_DATA_IND");
		}
	}
}

/* Send I-frame from MS and expect it to arrive as RLL DATA IND on Abis */
private function f_data_mo(
	RslLinkId link_id,
	boolean p, uint3_t nr, uint3_t ns,
	octetstring l3,
	boolean exp_sacch := true, /* Should tolerate SACCH messages? */
	boolean exp_any := false /* Should tolerate any other RSL messages? */
) runs on ConnHdlr {
	timer T := 3.0;
	f_tx_lapdm(ts_LAPDm_I(link_id.sapi, cr_MO_CMD, p, nr, ns, l3), link_id);
	T.start;
	/* Expect RLL DATA IND on RSL side */
	alt {
	[] RSL.receive(tr_RSL_DATA_IND(g_chan_nr, link_id, l3)) {
		setverdict(pass);
		}
	[exp_sacch] as_meas_res(verify_meas := false);
	[] as_rsl_any_ind(exp_any);
	[] T.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for DATA_IND");
		}
	}
}

/* Test channel activation with A5/n right from the beginning (like in assignment + hand-over) */
function f_TC_chan_act_encr(charstring id) runs on ConnHdlr {
	f_l1_tune(L1CTL);
	f_est_dchan(true);

	/* now we actually need to transmit some data both ways to check if the encryption works */
	var L1ctlDlMessage dl;

	var octetstring l3 := f_rnd_octstring(20);
	var RslLinkId link_id := valueof(ts_RslLinkID_DCCH(0));

	/* send UNITDATA_REQ from BTS to MS and expect it to arrive */
	f_unitdata_mt(link_id, l3);

	/* Send UI frame from MS and expect it to arrive as RLL UNITDATA IND on Abis */
	f_unitdata_mo(link_id, l3);

	/* release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_chan_act_a51() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	pars.encr := valueof(ts_RSL_IE_EncrInfo(RSL_ALG_ID_A5_1, f_rnd_octstring(8)));
	f_testmatrix_each_chan(pars, refers(f_TC_chan_act_encr));
}
testcase TC_chan_act_a52() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	pars.encr := valueof(ts_RSL_IE_EncrInfo(RSL_ALG_ID_A5_2, f_rnd_octstring(8)));
	f_testmatrix_each_chan(pars, refers(f_TC_chan_act_encr));
}
testcase TC_chan_act_a53() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	pars.encr := valueof(ts_RSL_IE_EncrInfo(RSL_ALG_ID_A5_3, f_rnd_octstring(8)));
	f_testmatrix_each_chan(pars, refers(f_TC_chan_act_encr));
}

/* Test channel activation with A5/n right from the beginning and RSL MODE MODIFY
 which should break the en/decryption on purpose by supplying a new key that is unknown to the MS*/
function f_TC_rsl_modify_encr(charstring id) runs on ConnHdlr {
	f_l1_tune(L1CTL);
	f_est_dchan(true);

	/* now we actually need to transmit some data both ways to check if the encryption works */
	var L1ctlDlMessage dl;

	var octetstring l3 := f_rnd_octstring(20);
	var RslLinkId link_id := valueof(ts_RslLinkID_DCCH(0));

	/* send UNITDATA_REQ from BTS to MS and expect it to arrive */
	f_unitdata_mt(link_id, l3);

	/* Send UI frame from MS and expect it to arrive as RLL UNITDATA IND on Abis */
	f_unitdata_mo(link_id, l3);

	var RSL_Message rsl;
	rsl := valueof(ts_RSL_MODE_MODIFY_REQ(g_chan_nr, valueof(ts_RSL_ChanMode_SIGN(false))));

	/* modify key to break proper encryption */
	g_pars.encr.key :=  f_rnd_octstring(8);
	var RSL_IE ei := valueof(t_RSL_IE(RSL_IE_ENCR_INFO, RSL_IE_Body:{encr_info := g_pars.encr}));
	rsl.ies := rsl.ies & { ei };
	RSL.send(rsl);

	timer T0 := 1.0;
	T0.start;
	/* Expect RSL MODIFY ACK */
	alt {
	[] RSL.receive(tr_RSL_MODE_MODIFY_ACK(g_chan_nr)) {}
	[] RSL.receive(tr_RSL_MODE_MODIFY_NACK(g_chan_nr, ?)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,"MODE MODIFY NACK");
		}
	[] T0.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for MODE MODIFY (N)ACK");
		}
	}

	var octetstring l3msg := f_rnd_octstring(15);
	timer T1 := 3.0;
	/* Send UI frame from MS, do not expect it to arrive as RLL UNITDATA IND on Abis
	due to broken encryption  */
	f_tx_lapdm(ts_LAPDm_UI(link_id.sapi, cr_MO_CMD, l3msg), link_id);
	T1.start;
	alt {
	[] RSL.receive(tr_RSL_UNITDATA_IND(g_chan_nr, link_id, l3msg)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "BTS shouldn't be able to decrypt after key change")
		}
	[] T1.timeout {
		setverdict(pass);
		}
	}

	/* release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_rsl_modify_encr() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	pars.encr := valueof(ts_RSL_IE_EncrInfo(RSL_ALG_ID_A5_1, f_rnd_octstring(8)));
	f_testmatrix_each_chan(pars, refers(f_TC_rsl_modify_encr));
}

/* Test unencrypted channel activation followed by explicit ENCR CMD later */
function f_TC_encr_cmd(charstring id) runs on ConnHdlr {
	/* L3 payload doesn't matter, as it is passed transparently */
	var BIT3 l3_alg_id := f_alg_id_to_l3(g_pars.encr.alg_id);
	var octetstring l3 := enc_PDU_ML3_NW_MS(valueof(ts_RRM_CiphModeCmd(l3_alg_id)));
	var RslLinkId link_id := valueof(ts_RslLinkID_DCCH(0));

	f_l1_tune(L1CTL);

	/* first establish a dedicated channel in the clear */
	f_est_dchan(false);

	/* Establish ABM */
	f_est_rll_mo(link_id.sapi, link_id, '23420815'O);

	/* then send the RSL ENCR CMD with an actual RR CIPH MOD CMD inside */
	RSL.send(ts_RSL_ENCR_CMD(g_chan_nr, link_id, g_pars.encr.alg_id, g_pars.encr.key, l3));
	/* expect the L3 to arrive still unencrypted on the MS side */
	f_l1_exp_lapdm(tr_LAPDm_I(link_id.sapi, cr_MT_CMD, ?, ?, ?, l3));

	/* configure L1 to apply ciphering */
	var uint8_t alg_id := f_alg_id_to_l1ctl(g_pars.encr.alg_id);
	f_L1CTL_CRYPTO_REQ(L1CTL, g_pars.chan_nr, alg_id, g_pars.encr.key);

	/* send first ciphered I-frame in response and expect it on RSL */
	f_data_mo(link_id, true, 1, 0, '0a0b0c0d'O, exp_sacch := true);

	/* now the BTS code should have detected the first properly encrypted uplink I-frame,
	 * and hence enable encryption also on the downlink */

	/* expect bi-directional communication work in encrypted mode */
	f_unitdata_mo(link_id, f_rnd_octstring(15));
	f_unitdata_mt(link_id, f_rnd_octstring(15));

	/* release the channel */
	f_rsl_chan_deact();
	f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
	f_rslem_unregister(0, g_chan_nr);
}
testcase TC_encr_cmd_a51() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	pars.encr := valueof(ts_RSL_IE_EncrInfo(RSL_ALG_ID_A5_1, f_rnd_octstring(8)));
	f_testmatrix_each_chan(pars, refers(f_TC_encr_cmd));
}
testcase TC_encr_cmd_a52() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	pars.encr := valueof(ts_RSL_IE_EncrInfo(RSL_ALG_ID_A5_2, f_rnd_octstring(8)));
	f_testmatrix_each_chan(pars, refers(f_TC_encr_cmd));
}
testcase TC_encr_cmd_a53() runs on test_CT {
	var ConnHdlrPars pars := valueof(t_Pars(t_RslChanNr_Bm(1), ts_RSL_ChanMode_SIGN));
	pars.encr := valueof(ts_RSL_IE_EncrInfo(RSL_ALG_ID_A5_3, f_rnd_octstring(8)));
	f_testmatrix_each_chan(pars, refers(f_TC_encr_cmd));
}

private function f_assert_lapdm(octetstring enc, template LapdmFrame exp_match, charstring name := "") {
	var LapdmFrame lf;
	var octetstring reenc;

	/* decode the LAPDm frame */
	if (ischosen(exp_match.ab)) {
		lf.ab := dec_LapdmFrameAB(enc);
	} else {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "unsupported frame type");
	}

	/* check if decoder result matches expectation */
	if (not match(lf, exp_match)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str(name, ": decoded LAPDm doesn't match"));
	} else {
		log(name, ": matched");
		setverdict(pass);
	}

	/* test if re-encoded frame equals original input */
	reenc := enc_LapdmFrame(lf);
	if (enc != reenc) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, log2str(name, ": re-encoded LAPDm frame doesn't match"));
	} else {
		setverdict(pass);
	}
}

testcase TC_lapdm_selftest() runs on test_CT {
	f_assert_lapdm('030301'O, tr_LAPDm_UI(0, true, ''O), "ui_s0_empty");
	f_assert_lapdm('0F0301'O, tr_LAPDm_UI(3, true, ''O), "ui_s3_empty");
	f_assert_lapdm('013F01'O, tr_LAPDm_SABM(0, false, true, ''O), "sabm_s0_empty");
	f_assert_lapdm('013F1123420815'O, tr_LAPDm_SABM(0, false, true, '23420815'O), "sabm_s0_l3");
	f_assert_lapdm('03E101'O, tr_LAPDm_RR(0, true, false, 7), "rr_s0_7");
	f_assert_lapdm('03000d063505'O, tr_LAPDm_I(0, true, false, 0, 0, '063505'O), "I/0/0");
	f_assert_lapdm('03e00d063505'O, tr_LAPDm_I(0, true, false, 7, 0, '063505'O), "I/7/0");
}

/***********************************************************************
 * DTX Related (see GSM 05.08, section 8.3)
 ***********************************************************************/

/* XXX These functions must be kept in sync with g_AllChannels defined on test_CT. */
function f_g_chan_is_tchf() runs on ConnHdlr return boolean {
	return (g_chan_nr == valueof(ts_RslChanNr_Bm(1)) or
		g_chan_nr == valueof(ts_RslChanNr_Bm(2)) or
		g_chan_nr == valueof(ts_RslChanNr_Bm(3)) or
		g_chan_nr == valueof(ts_RslChanNr_Bm(4)));
}
function f_g_chan_is_tchh() runs on ConnHdlr return boolean {
	return (g_chan_nr == valueof(ts_RslChanNr_Lm(5,0)) or
		g_chan_nr == valueof(ts_RslChanNr_Lm(5,1)));
}
function f_g_chan_is_sdcch4() runs on ConnHdlr return boolean {
	return (g_chan_nr == valueof(ts_RslChanNr_SDCCH4(0,0)) or
		g_chan_nr == valueof(ts_RslChanNr_SDCCH4(0,1)) or
		g_chan_nr == valueof(ts_RslChanNr_SDCCH4(0,2)) or
		g_chan_nr == valueof(ts_RslChanNr_SDCCH4(0,3)));
}
function f_g_chan_is_sdcch8() runs on ConnHdlr return boolean {
	return (g_chan_nr == valueof(ts_RslChanNr_SDCCH8(6,0)) or
		g_chan_nr == valueof(ts_RslChanNr_SDCCH8(6,1)) or
		g_chan_nr == valueof(ts_RslChanNr_SDCCH8(6,2)) or
		g_chan_nr == valueof(ts_RslChanNr_SDCCH8(6,3)) or
		g_chan_nr == valueof(ts_RslChanNr_SDCCH8(6,4)) or
		g_chan_nr == valueof(ts_RslChanNr_SDCCH8(6,5)) or
		g_chan_nr == valueof(ts_RslChanNr_SDCCH8(6,6)) or
		g_chan_nr == valueof(ts_RslChanNr_SDCCH8(6,7)));
}

function f_test_l2_fill_frames(boolean dtxd) runs on ConnHdlr {
	var L1ctlDlMessage dl;
	var octetstring l2_fill_frame := '0303012B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B'O;
	var octetstring l2_fill_frame_sacch := substr(l2_fill_frame, 0, lengthof(l2_fill_frame) - 2);
	var GsmFrameNumber first_fn;
	var boolean is_first_frame := true;
	var integer nfill_frames_sacch := 0;
	var integer nfill_frames_nonsacch := 0;
	var integer expected_fill_frames := 10000; /* initial value causes test failure if not overridden */
	/* Frames numbers (mod 104) for which a fill frame is expected on TCHF if DTX is enabled. */
	var Integers required_tdma_frames_dtx_tchf := { 52, 53, 54, 55, 56, 57, 58, 59 };
	const integer frame_dtx_tchf_mod := 104;
	/* Frame numbers (mod 104) for which a fill frame is expected at the L1SAP level,
	 * which operates in terms of blocks rather than frames. */
	var Integers required_tdma_blocks_dtx_tchf := { 52, 56 };
	const integer block_dtx_tchf_mod := 26;
	timer T := 5.0;

	f_l1_tune(L1CTL);
	RSL.clear;
	L1CTL.clear;

	/* activate TCHF signalling channel */
	f_est_dchan(false);

	T.start;
	alt {
	[] L1CTL.receive(tr_L1CTL_DATA_IND(g_chan_nr, ?)) -> value dl {
		var GsmFrameNumber fn := dl.dl_info.frame_nr;
		var octetstring l2 := dl.payload.data_ind.payload;

		if (is_first_frame) {
			is_first_frame := false;
			first_fn := dl.dl_info.frame_nr;
		}

		if (dl.dl_info.link_id.c == SACCH) {
			l2 := substr(l2, 2, lengthof(l2) - 2); /* remove L1 header */
			if (not match(l2_fill_frame_sacch, l2)) {
				repeat;
			}
		} else if (not match(l2_fill_frame, l2)) {
			repeat;
		}

		if (dtxd) {
			if (not f_g_chan_is_tchf()) {
				T.stop;
				f_rsl_chan_deact();
				f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Received fill frame on non-TCH/F channel; DTX is only allowed on TCH/F!");
			}
			if (fn > first_fn + frame_dtx_tchf_mod) {
				T.stop;
				f_rsl_chan_deact();
				f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);

				/* With DTX enabled we can expect at least 3 fill frames for every 104 frames.
				 * 2 SACCH, 1 TCH/F */
				expected_fill_frames := 3;

				if (nfill_frames_sacch + nfill_frames_nonsacch < expected_fill_frames) {
					log("received only ", nfill_frames_sacch, "+", nfill_frames_nonsacch,
					    " (SACCH+other) out of ", expected_fill_frames, " expected fill frames");
					Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Not enough fill frames received");
				} else {
					setverdict(pass);
				}
			} else {
				if (dl.dl_info.link_id.c == SACCH) {
					nfill_frames_sacch := nfill_frames_sacch + 1;
					repeat;
				}
				/* On DTX TCH/F channels, fill frames occur only for specific frame numbers mod 104.
				 * Furthermore, the L1SAP layer gives us frame numbers for the start of a block so
				 * we should only see the subset of frames numbers which correspond to a block boundary.
				 * TCH/F blocks are defined to start at 0,4,8,13,17,21 (modulo 26) */
				for (var integer i := 0; i < lengthof(required_tdma_blocks_dtx_tchf); i := i + 1) {
					if (fn mod frame_dtx_tchf_mod == required_tdma_blocks_dtx_tchf[i]) {
						nfill_frames_nonsacch := nfill_frames_nonsacch + 1;
						repeat;
					}
				}
				log("Received DTX TCH fill frame with bad frame number: ", fn,
				    " (mod ", frame_dtx_tchf_mod, ": ", fn mod frame_dtx_tchf_mod, ")",
				    " (mod ", block_dtx_tchf_mod, ": ", fn mod block_dtx_tchf_mod, ")");
				f_rsl_chan_deact();
				f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unexpected L2 fill frame received on Um");
			}
		} else {
			if (dl.dl_info.link_id.c == SACCH) {
				nfill_frames_sacch := nfill_frames_sacch + 1;
			} else {
				nfill_frames_nonsacch := nfill_frames_nonsacch + 1;
			}
			if (fn > first_fn + frame_dtx_tchf_mod) {
				T.stop;
				if (f_g_chan_is_tchf()) {
					/* Without DTX we can expect 25 fill frames for every 104 frames.
					 * (24 FACCH + 1 SACCH filling) */
					 expected_fill_frames := 25;
				} else if (f_g_chan_is_tchh()) {
					/* We can expect 2 fill frames for every 104 frames. */
					 expected_fill_frames := 2;
				} else if (f_g_chan_is_sdcch4() or f_g_chan_is_sdcch8()) {
					/* We can expect 5 fill frames for every 104 frames. */
					 expected_fill_frames := 5;
				} else {
					f_rsl_chan_deact();
					f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
					Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Unknown channel type");
				}

				f_rsl_chan_deact();
				f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);

				if (nfill_frames_sacch + nfill_frames_nonsacch >= expected_fill_frames) {
					setverdict(pass);
				} else {
					log("received only ", nfill_frames_sacch, "+", nfill_frames_nonsacch,
					    " (SACCH+other) out of ", expected_fill_frames, " expected fill frames");
					Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Not enough fill frames received");
				}
			} else {
				repeat;
			}
		}
	}
	[] L1CTL.receive { repeat; }
	[] T.timeout {
		f_rsl_chan_deact();
		f_L1CTL_DM_REL_REQ(L1CTL, g_chan_nr);
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Timeout waiting for L2 fill frames on Um");
	}
	}
}

function f_TC_tch_sign_l2_fill_frame(charstring id) runs on ConnHdlr {
	f_test_l2_fill_frames(false);
}

function f_TC_tch_sign_l2_fill_frame_dtxd(charstring id) runs on ConnHdlr {
	f_test_l2_fill_frames(true);
}

function f_tch_sign_l2_fill_frame(boolean dtxd) runs on test_CT {
	var ConnHdlr vc_conn;
	var ConnHdlrPars pars;
	pars.t_guard := 60.0;
	f_init();
	for (var integer i := 0; i < sizeof(g_AllChannels); i := i + 1) {
		pars := valueof(t_Pars(g_AllChannels[i], ts_RSL_ChanMode_SIGN(dtxd)));
		if (dtxd) {
			if (i >= 4) { /* DTX is only allowed on TCH/F */
				break;
			}
			vc_conn := f_start_handler(refers(f_TC_tch_sign_l2_fill_frame_dtxd), pars);
		} else {
			vc_conn := f_start_handler(refers(f_TC_tch_sign_l2_fill_frame), pars);
		}
		vc_conn.done;
	}
}

/* Verify that L2 fill frames are sent on TCH in signaling mode if
 * there is nothing to transmit while DTX is disabled on downlink. */
testcase TC_tch_sign_l2_fill_frame() runs on test_CT {
	f_tch_sign_l2_fill_frame(false);
}

/* Verify that particular L2 fill frames are sent on TCH in signaling mode if
 * there is nothing to transmit while DTX is enabled on downlink. */
testcase TC_tch_sign_l2_fill_frame_dtxd() runs on test_CT {
	f_tch_sign_l2_fill_frame(true);
}

testcase TC_chopped_ipa_ping() runs on test_CT {
	IPA_Testing.f_run_TC_chopped_ipa_ping(mp_rsl_ip, mp_rsl_port, LISTEN_FOR_CLIENT);
}

testcase TC_chopped_ipa_payload() runs on test_CT {
	IPA_Testing.f_run_TC_chopped_ipa_payload(mp_rsl_ip, mp_rsl_port, LISTEN_FOR_CLIENT);
}

/* test generation of RLL ERR IND based on Um errors (TS 48.058 3.9) */
/*	protocol error as per 44.006 */
/*	link layer failure (repetition of I-frame N200 times without ACK */
/*	repetition of SABM or DISC N200 times without ACK */
/*	receptiom of SABM in multi-frame established state */


/* TODO Areas:

* channel activation
** with BS_Power / MS_Power, bypassing power control loop
** on primary vs. secondary TRX
** with timing advance from initial activation on
* mode modify
** encryption
** multirate
* check DEACTIVATE SACCH
** unsupported algorithm
* handover detection
* BS Power Control
* Physical Context
* RF resource ind
* error handling
** IE duplicated?
* PCU interface
** DATA_IND from BTS->PCU
** verification of PCU-originated DATA_REQ arrival on Um/MS side

*/

control {
	execute( TC_chan_act_stress() );
	execute( TC_chan_act_react() );
	execute( TC_chan_deact_not_active() );
	execute( TC_chan_act_wrong_nr() );
	execute( TC_deact_sacch() );
	execute( TC_sacch_filling() );
	execute( TC_sacch_info_mod() );
	execute( TC_sacch_multi() );
	execute( TC_sacch_multi_chg() );
	execute( TC_sacch_chan_act() );
	execute( TC_sacch_chan_act_ho_async() );
	execute( TC_sacch_chan_act_ho_sync() );
	execute( TC_rach_content() );
	execute( TC_rach_count() );
	execute( TC_rach_max_ta() );
	execute( TC_ho_rach() );
	execute( TC_rach_load_idle_thresh0() );
	execute( TC_rach_load_idle_below_thresh() );
	execute( TC_rach_load_count() );
	execute( TC_meas_res_sign_tchf() );
	execute( TC_meas_res_sign_tchh() );
	execute( TC_meas_res_sign_sdcch4() );
	execute( TC_meas_res_sign_sdcch8() );
	execute( TC_meas_res_sign_tchh_toa256() );
	execute( TC_rsl_bs_pwr_static_ass() );
	execute( TC_rsl_bs_pwr_static_power_control() );
	execute( TC_rsl_ms_pwr_ctrl() );
	execute( TC_rsl_ms_pwr_dyn_active() );
	execute( TC_rsl_ms_pwr_dyn_active2() );
	execute( TC_rsl_ms_pwr_dyn_up() );
	execute( TC_rsl_ms_pwr_dyn_down() );
	execute( TC_rsl_ms_pwr_dyn_ass_updown() );
	execute( TC_rsl_ms_pwr_dyn_max() );
	execute( TC_rsl_chan_initial_ms_pwr() );
	execute( TC_rsl_chan_initial_ta() );
	execute( TC_rsl_modify_encr() );
	execute( TC_conn_fail_crit() );
	execute( TC_paging_imsi_80percent() );
	execute( TC_paging_tmsi_80percent() );
	execute( TC_paging_imsi_200percent() );
	execute( TC_paging_tmsi_200percent() );
	execute( TC_rsl_protocol_error() );
	execute( TC_rsl_mand_ie_error() );
	execute( TC_rsl_ie_content_error() );
	execute( TC_si_sched_default() );
	execute( TC_si_sched_1() );
	execute( TC_si_sched_2bis() );
	execute( TC_si_sched_2ter() );
	execute( TC_si_sched_2ter_2bis() );
	execute( TC_si_sched_2quater() );
	execute( TC_si_sched_13() );
	execute( TC_si_sched_13_2bis_2ter_2quater() );
	execute( TC_ipa_dlcx_not_active() );
	execute( TC_ipa_crcx_twice_not_active() );
	execute( TC_ipa_crcx_mdcx_dlcx_not_active() );
	execute( TC_ipa_crcx_mdcx_mdcx_dlcx_not_active() );
	execute( TC_ipa_crcx_sdcch_not_active() );

	if (mp_pcu_socket != "") {
		execute( TC_pcu_act_req() );
		execute( TC_pcu_act_req_wrong_ts() );
		execute( TC_pcu_act_req_wrong_bts() );
		execute( TC_pcu_act_req_wrong_trx() );
		execute( TC_pcu_deact_req() );
		execute( TC_pcu_deact_req_wrong_ts() );
		execute( TC_pcu_ver_si13() );
		if (mp_l1_supports_gprs) {
			execute( TC_pcu_data_req_pdtch() );
			execute( TC_pcu_data_req_ptcch() );
			execute( TC_pcu_data_req_wrong_bts() );
			execute( TC_pcu_data_req_wrong_trx() );
			execute( TC_pcu_data_req_wrong_ts() );
			execute( TC_pcu_data_req_ts_inactive() );
		}
		execute( TC_pcu_data_req_agch() );
		execute( TC_pcu_data_req_pch() );
		execute( TC_pcu_data_req_imm_ass_pch() );
		execute( TC_pcu_rach_content() );
		execute( TC_pcu_ext_rach_content() );
		execute( TC_pcu_data_ind_lqual_cb() );
		execute( TC_pcu_paging_from_rsl() );
		execute( TC_pcu_time_ind() );
		execute( TC_pcu_rts_req() );
		execute( TC_pcu_oml_alert() );
		execute( TC_pcu_rr_suspend() );
		execute( TC_pcu_socket_connect_multi() );
		execute( TC_pcu_socket_reconnect() );
		execute( TC_pcu_socket_noconnect_nosi3gprs() );
		execute( TC_pcu_socket_connect_si3gprs() );
		execute( TC_pcu_socket_disconnect_nosi3gprs() );
		execute( TC_pcu_socket_verify_info_ind() );
	} else {
		log("PCU socket path not available, skipping PCU tests");
	}

	execute( TC_dyn_osmo_pdch_act_deact() );
	execute( TC_dyn_osmo_pdch_unsol_deact() );
	execute( TC_dyn_osmo_pdch_double_act() );
	execute( TC_dyn_osmo_pdch_tchf_act() );
	execute( TC_dyn_osmo_pdch_tchh_act() );
	execute( TC_dyn_ipa_pdch_act_deact() );
	execute( TC_dyn_ipa_pdch_tchf_act() );
	execute( TC_dyn_ipa_pdch_tchf_act_pdch_act_nack() );
	execute( TC_dyn_ipa_pdch_act_tchf_act_nack() );

	execute( TC_rll_est_ind() );
	execute( TC_rll_est_req_DCCH_3() );
	execute( TC_rll_est_req_ACCH_3() );
	execute( TC_rll_rel_ind_DCCH_0() );
	execute( TC_rll_rel_ind_DCCH_3() );
	execute( TC_rll_rel_ind_ACCH_0() );
	execute( TC_rll_rel_ind_ACCH_3() );
	execute( TC_rll_rel_req() );
	execute( TC_rll_unit_data_req_DCCH() );
	execute( TC_rll_unit_data_req_ACCH() );
	execute( TC_rll_unit_data_ind_DCCH() );
	execute( TC_rll_unit_data_ind_ACCH() );

	execute( TC_chan_act_a51() );
	execute( TC_chan_act_a52() );
	execute( TC_chan_act_a53() );
	execute( TC_encr_cmd_a51() );
	execute( TC_encr_cmd_a52() );
	execute( TC_encr_cmd_a53() );

	execute( TC_err_rep_wrong_mdisc() );
	execute( TC_err_rep_wrong_msg_type() );
	execute( TC_err_rep_wrong_sequence() );

	execute( TC_lapdm_selftest() );

	execute( TC_tch_sign_l2_fill_frame() );
	execute( TC_tch_sign_l2_fill_frame_dtxd() );

	execute( TC_chopped_ipa_ping() );
	execute( TC_chopped_ipa_payload() );
}


}